blob: 065cd7ba00b76bbf4e983cc11eb8958ffda8e95e [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng009ea542007-03-16 08:46:27 +000016#include "llvm/Analysis/LoopInfo.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"
Chris Lattner2e77db62005-05-13 18:50:42 +000019#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000020#include "llvm/Constants.h"
21#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"
Jim Laskeyc56315c2007-01-26 21:22:28 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner90f42382006-11-29 01:12:32 +000037#include "llvm/Target/TargetAsmInfo.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 Lattnerc9950c12005-08-17 06:37:43 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattner975f5c92005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000058#else
Chris Lattneref598052006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000060#endif
61
Jim Laskey29e635d2006-08-02 12:30:23 +000062//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 }
255
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 }
Chris Lattner84a03502006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000292 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner49409cb2006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencer09575ba2007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner7a60d912005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner79084302007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000358
Chris Lattner4d9651c2005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemaned728c12006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattner2fbff4d2007-02-13 20:09:07 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner7a60d912005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
Nate Begemaned728c12006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000408 /// JTCases - Vector of JumpTable structures used to communicate
409 /// SwitchInst code generation information.
410 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000411
Chris Lattner7a60d912005-01-07 07:47:53 +0000412 /// FuncInfo - Information about the function as a whole.
413 ///
414 FunctionLoweringInfo &FuncInfo;
415
416 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000417 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000418 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000419 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 }
421
Chris Lattner4108bb02005-01-17 19:43:36 +0000422 /// getRoot - Return the current virtual root of the Selection DAG.
423 ///
424 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000425 if (PendingLoads.empty())
426 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000427
Chris Lattner4d9651c2005-01-17 22:19:26 +0000428 if (PendingLoads.size() == 1) {
429 SDOperand Root = PendingLoads[0];
430 DAG.setRoot(Root);
431 PendingLoads.clear();
432 return Root;
433 }
434
435 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000436 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
437 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000438 PendingLoads.clear();
439 DAG.setRoot(Root);
440 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000441 }
442
Chris Lattnered0110b2006-10-27 21:36:01 +0000443 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
444
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 void visit(Instruction &I) { visit(I.getOpcode(), I); }
446
447 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000448 // Note: this doesn't use InstVisitor, because it has to work with
449 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 switch (Opcode) {
451 default: assert(0 && "Unknown instruction type encountered!");
452 abort();
453 // Build the switch statement using the Instruction.def file.
454#define HANDLE_INST(NUM, OPCODE, CLASS) \
455 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
456#include "llvm/Instruction.def"
457 }
458 }
459
460 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
461
Chris Lattner4024c002006-03-15 22:19:46 +0000462 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000463 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000464 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000465
466 SDOperand getIntPtrConstant(uint64_t Val) {
467 return DAG.getConstant(Val, TLI.getPointerTy());
468 }
469
Chris Lattner8471b152006-03-16 19:57:50 +0000470 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000471
Chris Lattner79084302007-02-04 01:31:47 +0000472 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 SDOperand &N = NodeMap[V];
474 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000475 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000476 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000477
Chris Lattner6f87d182006-02-22 22:37:12 +0000478 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
479 MVT::ValueType VT,
480 bool OutReg, bool InReg,
481 std::set<unsigned> &OutputRegs,
482 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000483
Chris Lattnered0110b2006-10-27 21:36:01 +0000484 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
485 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
486 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000487 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000488 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000489 void LowerCallTo(Instruction &I,
490 const Type *CalledValueTy, unsigned CallingConv,
491 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000492
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 // Terminator instructions.
494 void visitRet(ReturnInst &I);
495 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000496 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000497 void visitUnreachable(UnreachableInst &I) { /* noop */ }
498
Nate Begemaned728c12006-03-27 01:32:24 +0000499 // Helper for visitSwitch
500 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000501 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000502 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
503 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000504
Chris Lattner7a60d912005-01-07 07:47:53 +0000505 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000506 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000507 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000508 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000509
Reid Spencer2eadb532007-01-21 00:29:26 +0000510 void visitScalarBinary(User &I, unsigned OpCode);
511 void visitVectorBinary(User &I, unsigned OpCode);
512 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000513 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000514 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000515 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000516 visitVectorBinary(I, ISD::VADD);
517 else if (I.getType()->isFloatingPoint())
518 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000519 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000520 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000521 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000522 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000523 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000524 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000525 visitVectorBinary(I, ISD::VMUL);
526 else if (I.getType()->isFloatingPoint())
527 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000528 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000529 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000530 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000531 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
532 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
533 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
534 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
535 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
536 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
537 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
538 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
539 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
540 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000541 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
542 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000543 void visitICmp(User &I);
544 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000545 // Visit the conversion instructions
546 void visitTrunc(User &I);
547 void visitZExt(User &I);
548 void visitSExt(User &I);
549 void visitFPTrunc(User &I);
550 void visitFPExt(User &I);
551 void visitFPToUI(User &I);
552 void visitFPToSI(User &I);
553 void visitUIToFP(User &I);
554 void visitSIToFP(User &I);
555 void visitPtrToInt(User &I);
556 void visitIntToPtr(User &I);
557 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000558
Chris Lattner67271862006-03-29 00:11:43 +0000559 void visitExtractElement(User &I);
560 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000561 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000562
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000564 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000565
566 void visitMalloc(MallocInst &I);
567 void visitFree(FreeInst &I);
568 void visitAlloca(AllocaInst &I);
569 void visitLoad(LoadInst &I);
570 void visitStore(StoreInst &I);
571 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
572 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000573 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000574 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000575 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000576
Chris Lattner7a60d912005-01-07 07:47:53 +0000577 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000578 void visitVAArg(VAArgInst &I);
579 void visitVAEnd(CallInst &I);
580 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000581
Chris Lattner875def92005-01-11 05:56:49 +0000582 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000583
584 void visitUserOp1(Instruction &I) {
585 assert(0 && "UserOp1 should not exist at instruction selection time!");
586 abort();
587 }
588 void visitUserOp2(Instruction &I) {
589 assert(0 && "UserOp2 should not exist at instruction selection time!");
590 abort();
591 }
592};
593} // end namespace llvm
594
Chris Lattner8471b152006-03-16 19:57:50 +0000595SDOperand SelectionDAGLowering::getValue(const Value *V) {
596 SDOperand &N = NodeMap[V];
597 if (N.Val) return N;
598
599 const Type *VTy = V->getType();
600 MVT::ValueType VT = TLI.getValueType(VTy);
601 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
603 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000604 SDOperand N1 = NodeMap[V];
605 assert(N1.Val && "visit didn't populate the ValueMap!");
606 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000607 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
608 return N = DAG.getGlobalAddress(GV, VT);
609 } else if (isa<ConstantPointerNull>(C)) {
610 return N = DAG.getConstant(0, TLI.getPointerTy());
611 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000612 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000613 return N = DAG.getNode(ISD::UNDEF, VT);
614
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000615 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000616 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000617 unsigned NumElements = PTy->getNumElements();
618 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
619
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000620 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000621 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
622
623 // Create a VConstant node with generic Vector type.
624 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
625 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000626 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
627 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000628 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
629 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000630 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000631 unsigned NumElements = PTy->getNumElements();
632 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000633
634 // Now that we know the number and type of the elements, push a
635 // Constant or ConstantFP node onto the ops list for each element of
636 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000637 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000638 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000639 for (unsigned i = 0; i != NumElements; ++i)
640 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000641 } else {
642 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
643 SDOperand Op;
644 if (MVT::isFloatingPoint(PVT))
645 Op = DAG.getConstantFP(0, PVT);
646 else
647 Op = DAG.getConstant(0, PVT);
648 Ops.assign(NumElements, Op);
649 }
650
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000651 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000652 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
653 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000654 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
655 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000656 } else {
657 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000658 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000659 }
660 }
661
662 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
663 std::map<const AllocaInst*, int>::iterator SI =
664 FuncInfo.StaticAllocaMap.find(AI);
665 if (SI != FuncInfo.StaticAllocaMap.end())
666 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
667 }
668
Chris Lattner8c504cf2007-02-25 18:40:32 +0000669 unsigned InReg = FuncInfo.ValueMap[V];
670 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000671
672 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000673 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000674 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000675 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000676 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000677 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
678 unsigned NumVals = TLI.getNumElements(VT);
679 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
680 if (NumVals == 1)
681 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
682 else {
683 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
684 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
685 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
686 }
687 } else {
688 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
689 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
690 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
691 N = MVT::isFloatingPoint(VT)
692 ? DAG.getNode(ISD::FP_ROUND, VT, N)
693 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000694 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000695 } else {
696 // Otherwise, if this is a vector, make it available as a generic vector
697 // here.
698 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000699 const VectorType *PTy = cast<VectorType>(VTy);
700 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000701 PTyLegalElementVT);
702
703 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000704 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000705 if (PTyElementVT == PTyLegalElementVT) {
706 // If the value types are legal, just VBUILD the CopyFromReg nodes.
707 for (unsigned i = 0; i != NE; ++i)
708 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT));
710 } else if (PTyElementVT < PTyLegalElementVT) {
711 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
712 for (unsigned i = 0; i != NE; ++i) {
713 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
714 PTyElementVT);
715 if (MVT::isFloatingPoint(PTyElementVT))
716 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
717 else
718 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
719 Ops.push_back(Op);
720 }
721 } else {
722 // If the register was expanded, use BUILD_PAIR.
723 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
724 for (unsigned i = 0; i != NE/2; ++i) {
725 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 PTyElementVT);
727 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 PTyElementVT);
729 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
730 }
731 }
732
733 Ops.push_back(DAG.getConstant(NE, MVT::i32));
734 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000735 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000736
737 // Finally, use a VBIT_CONVERT to make this available as the appropriate
738 // vector type.
739 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
740 DAG.getConstant(PTy->getNumElements(),
741 MVT::i32),
742 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000743 }
744
745 return N;
746}
747
748
Chris Lattner7a60d912005-01-07 07:47:53 +0000749void SelectionDAGLowering::visitRet(ReturnInst &I) {
750 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000751 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000752 return;
753 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000754 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000755 NewValues.push_back(getRoot());
756 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
757 SDOperand RetOp = getValue(I.getOperand(i));
758
759 // If this is an integer return value, we need to promote it ourselves to
760 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
761 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000762 // FIXME: C calling convention requires the return type to be promoted to
763 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000764 if (MVT::isInteger(RetOp.getValueType()) &&
765 RetOp.getValueType() < MVT::i64) {
766 MVT::ValueType TmpVT;
767 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
768 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
769 else
770 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000771 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000772 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000773 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
774 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000775 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
776 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000777 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000778 }
779 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000780 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000784}
785
Chris Lattnered0110b2006-10-27 21:36:01 +0000786/// ExportFromCurrentBlock - If this condition isn't known to be exported from
787/// the current basic block, add it to ValueMap now so that we'll get a
788/// CopyTo/FromReg.
789void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790 // No need to export constants.
791 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792
793 // Already exported?
794 if (FuncInfo.isExportedInst(V)) return;
795
796 unsigned Reg = FuncInfo.InitializeRegForValue(V);
797 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798}
799
Chris Lattner84a03502006-10-27 23:50:33 +0000800bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801 const BasicBlock *FromBB) {
802 // The operands of the setcc have to be in this block. We don't know
803 // how to export them from some other block.
804 if (Instruction *VI = dyn_cast<Instruction>(V)) {
805 // Can export from current BB.
806 if (VI->getParent() == FromBB)
807 return true;
808
809 // Is already exported, noop.
810 return FuncInfo.isExportedInst(V);
811 }
812
813 // If this is an argument, we can export it if the BB is the entry block or
814 // if it is already exported.
815 if (isa<Argument>(V)) {
816 if (FromBB == &FromBB->getParent()->getEntryBlock())
817 return true;
818
819 // Otherwise, can only export this if it is already exported.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // Otherwise, constants can always be exported.
824 return true;
825}
826
Chris Lattnere60ae822006-10-29 21:01:20 +0000827static bool InBlock(const Value *V, const BasicBlock *BB) {
828 if (const Instruction *I = dyn_cast<Instruction>(V))
829 return I->getParent() == BB;
830 return true;
831}
832
Chris Lattnered0110b2006-10-27 21:36:01 +0000833/// FindMergedConditions - If Cond is an expression like
834void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835 MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB,
837 MachineBasicBlock *CurBB,
838 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000839 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000840 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000841
Reid Spencer266e42b2006-12-23 06:05:41 +0000842 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
843 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000844 BOp->getParent() != CurBB->getBasicBlock() ||
845 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
846 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000847 const BasicBlock *BB = CurBB->getBasicBlock();
848
Reid Spencer266e42b2006-12-23 06:05:41 +0000849 // If the leaf of the tree is a comparison, merge the condition into
850 // the caseblock.
851 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
852 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000853 // how to export them from some other block. If this is the first block
854 // of the sequence, no exporting is needed.
855 (CurBB == CurMBB ||
856 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
857 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000858 BOp = cast<Instruction>(Cond);
859 ISD::CondCode Condition;
860 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
861 switch (IC->getPredicate()) {
862 default: assert(0 && "Unknown icmp predicate opcode!");
863 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
864 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
865 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
866 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
867 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
868 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
869 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
870 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
871 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
872 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
873 }
874 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
875 ISD::CondCode FPC, FOC;
876 switch (FC->getPredicate()) {
877 default: assert(0 && "Unknown fcmp predicate opcode!");
878 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
879 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
880 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
881 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
882 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
883 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
884 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
885 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
886 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
887 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
888 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
889 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
890 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
891 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
892 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
893 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
894 }
895 if (FiniteOnlyFPMath())
896 Condition = FOC;
897 else
898 Condition = FPC;
899 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000900 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000901 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000902 }
903
Chris Lattnered0110b2006-10-27 21:36:01 +0000904 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
905 BOp->getOperand(1), TBB, FBB, CurBB);
906 SwitchCases.push_back(CB);
907 return;
908 }
909
910 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000911 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000912 TBB, FBB, CurBB);
913 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000914 return;
915 }
916
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000917
918 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000919 MachineFunction::iterator BBI = CurBB;
920 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
921 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
922
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000923 if (Opc == Instruction::Or) {
924 // Codegen X | Y as:
925 // jmp_if_X TBB
926 // jmp TmpBB
927 // TmpBB:
928 // jmp_if_Y TBB
929 // jmp FBB
930 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000931
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000932 // Emit the LHS condition.
933 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
934
935 // Emit the RHS condition into TmpBB.
936 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
937 } else {
938 assert(Opc == Instruction::And && "Unknown merge op!");
939 // Codegen X & Y as:
940 // jmp_if_X TmpBB
941 // jmp FBB
942 // TmpBB:
943 // jmp_if_Y TBB
944 // jmp FBB
945 //
946 // This requires creation of TmpBB after CurBB.
947
948 // Emit the LHS condition.
949 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
950
951 // Emit the RHS condition into TmpBB.
952 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
953 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000954}
955
Chris Lattner427301f2006-10-31 22:37:42 +0000956/// If the set of cases should be emitted as a series of branches, return true.
957/// If we should emit this as a bunch of and/or'd together conditions, return
958/// false.
959static bool
960ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
961 if (Cases.size() != 2) return true;
962
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000963 // If this is two comparisons of the same values or'd or and'd together, they
964 // will get folded into a single comparison, so don't emit two blocks.
965 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
966 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
967 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
968 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
969 return false;
970 }
971
Chris Lattner427301f2006-10-31 22:37:42 +0000972 return true;
973}
974
Chris Lattner7a60d912005-01-07 07:47:53 +0000975void SelectionDAGLowering::visitBr(BranchInst &I) {
976 // Update machine-CFG edges.
977 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000978
979 // Figure out which block is immediately after the current one.
980 MachineBasicBlock *NextBlock = 0;
981 MachineFunction::iterator BBI = CurMBB;
982 if (++BBI != CurMBB->getParent()->end())
983 NextBlock = BBI;
984
985 if (I.isUnconditional()) {
986 // If this is not a fall-through branch, emit the branch.
987 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000988 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000989 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000990
Chris Lattner963ddad2006-10-24 17:57:59 +0000991 // Update machine-CFG edges.
992 CurMBB->addSuccessor(Succ0MBB);
993
994 return;
995 }
996
997 // If this condition is one of the special cases we handle, do special stuff
998 // now.
999 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001000 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001001
1002 // If this is a series of conditions that are or'd or and'd together, emit
1003 // this as a sequence of branches instead of setcc's with and/or operations.
1004 // For example, instead of something like:
1005 // cmp A, B
1006 // C = seteq
1007 // cmp D, E
1008 // F = setle
1009 // or C, F
1010 // jnz foo
1011 // Emit:
1012 // cmp A, B
1013 // je foo
1014 // cmp D, E
1015 // jle foo
1016 //
1017 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1018 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001019 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001020 BOp->getOpcode() == Instruction::Or)) {
1021 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001022 // If the compares in later blocks need to use values not currently
1023 // exported from this block, export them now. This block should always
1024 // be the first entry.
1025 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1026
Chris Lattner427301f2006-10-31 22:37:42 +00001027 // Allow some cases to be rejected.
1028 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001029 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1030 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1031 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1032 }
1033
1034 // Emit the branch for this block.
1035 visitSwitchCase(SwitchCases[0]);
1036 SwitchCases.erase(SwitchCases.begin());
1037 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001038 }
1039
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001040 // Okay, we decided not to do this, remove any inserted MBB's and clear
1041 // SwitchCases.
1042 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1043 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1044
Chris Lattner427301f2006-10-31 22:37:42 +00001045 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001046 }
1047 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001048
1049 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001050 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001051 Succ0MBB, Succ1MBB, CurMBB);
1052 // Use visitSwitchCase to actually insert the fast branch sequence for this
1053 // cond branch.
1054 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001055}
1056
Nate Begemaned728c12006-03-27 01:32:24 +00001057/// visitSwitchCase - Emits the necessary code to represent a single node in
1058/// the binary search tree resulting from lowering a switch instruction.
1059void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001060 SDOperand Cond;
1061 SDOperand CondLHS = getValue(CB.CmpLHS);
1062
Chris Lattnered0110b2006-10-27 21:36:01 +00001063 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1064 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001065 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001066 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001067 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001068 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1069 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1070 } else
1071 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001072
Nate Begemaned728c12006-03-27 01:32:24 +00001073 // Set NextBlock to be the MBB immediately after the current one, if any.
1074 // This is used to avoid emitting unnecessary branches to the next block.
1075 MachineBasicBlock *NextBlock = 0;
1076 MachineFunction::iterator BBI = CurMBB;
1077 if (++BBI != CurMBB->getParent()->end())
1078 NextBlock = BBI;
1079
1080 // If the lhs block is the next block, invert the condition so that we can
1081 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001082 if (CB.TrueBB == NextBlock) {
1083 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001084 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1085 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1086 }
1087 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001088 DAG.getBasicBlock(CB.TrueBB));
1089 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001090 DAG.setRoot(BrCond);
1091 else
1092 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001093 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001094 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001095 CurMBB->addSuccessor(CB.TrueBB);
1096 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001097}
1098
Anton Korobeynikov70378262007-03-25 15:07:15 +00001099/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001100void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001101 // Emit the code for the jump table
Anton Korobeynikov70378262007-03-25 15:07:15 +00001102 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001103 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001104 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1105 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1106 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1107 Table, Index));
1108 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001109}
1110
Anton Korobeynikov70378262007-03-25 15:07:15 +00001111/// visitJumpTableHeader - This function emits necessary code to produce index
1112/// in the JumpTable from switch case.
1113void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1114 SelectionDAGISel::JumpTableHeader &JTH) {
1115 // Subtract the lowest switch case value from the value being switched on
1116 // and conditional branch to default mbb if the result is greater than the
1117 // difference between smallest and largest cases.
1118 SDOperand SwitchOp = getValue(JTH.SValue);
1119 MVT::ValueType VT = SwitchOp.getValueType();
1120 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1121 DAG.getConstant(JTH.First, VT));
1122
1123 // The SDNode we just created, which holds the value being switched on
1124 // minus the the smallest case value, needs to be copied to a virtual
1125 // register so it can be used as an index into the jump table in a
1126 // subsequent basic block. This value may be smaller or larger than the
1127 // target's pointer type, and therefore require extension or truncating.
1128 if (VT > TLI.getPointerTy())
1129 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1130 else
1131 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1132
1133 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1134 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1135 JT.Reg = JumpTableReg;
1136
1137 // Emit the range check for the jump table, and branch to the default
1138 // block for the switch statement if the value being switched on exceeds
1139 // the largest case in the switch.
1140 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1141 DAG.getConstant(JTH.Last-JTH.First,VT),
1142 ISD::SETUGT);
1143
1144 // Set NextBlock to be the MBB immediately after the current one, if any.
1145 // This is used to avoid emitting unnecessary branches to the next block.
1146 MachineBasicBlock *NextBlock = 0;
1147 MachineFunction::iterator BBI = CurMBB;
1148 if (++BBI != CurMBB->getParent()->end())
1149 NextBlock = BBI;
1150
1151 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1152 DAG.getBasicBlock(JT.Default));
1153
1154 if (JT.MBB == NextBlock)
1155 DAG.setRoot(BrCond);
1156 else
1157 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1158 DAG.getBasicBlock(JT.MBB)));
1159}
1160
1161
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001162void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001163 assert(0 && "Should never be visited directly");
1164}
1165void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001166 // Retrieve successors.
1167 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1168 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1169
Jim Laskey14059d92007-02-25 21:43:59 +00001170 if (!AsTerminator) {
1171 // Mark landing pad so that it doesn't get deleted in branch folding.
1172 LandingPad->setIsLandingPad();
1173
1174 // Insert a label before the invoke call to mark the try range.
1175 // This can be used to detect deletion of the invoke via the
1176 // MachineModuleInfo.
1177 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1178 unsigned BeginLabel = MMI->NextLabelID();
1179 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1180 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001181
Jim Laskey14059d92007-02-25 21:43:59 +00001182 LowerCallTo(I, I.getCalledValue()->getType(),
1183 I.getCallingConv(),
1184 false,
1185 getValue(I.getOperand(0)),
1186 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001187
Jim Laskey14059d92007-02-25 21:43:59 +00001188 // Insert a label before the invoke call to mark the try range.
1189 // This can be used to detect deletion of the invoke via the
1190 // MachineModuleInfo.
1191 unsigned EndLabel = MMI->NextLabelID();
1192 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1193 DAG.getConstant(EndLabel, MVT::i32)));
1194
1195 // Inform MachineModuleInfo of range.
1196 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1197
1198 // Update successor info
1199 CurMBB->addSuccessor(Return);
1200 CurMBB->addSuccessor(LandingPad);
1201 } else {
1202 // Drop into normal successor.
1203 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1204 DAG.getBasicBlock(Return)));
1205 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001206}
1207
1208void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1209}
1210
Anton Korobeynikov70378262007-03-25 15:07:15 +00001211void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
Nate Begemaned728c12006-03-27 01:32:24 +00001212 // Figure out which block is immediately after the current one.
1213 MachineBasicBlock *NextBlock = 0;
1214 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001215
Chris Lattner6d6fc262006-10-22 21:36:53 +00001216 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1217
Nate Begemaned728c12006-03-27 01:32:24 +00001218 // If there is only the default destination, branch to it if it is not the
1219 // next basic block. Otherwise, just fall through.
1220 if (I.getNumOperands() == 2) {
1221 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001222
Nate Begemaned728c12006-03-27 01:32:24 +00001223 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001224 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001225 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001226 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001227
Chris Lattner6d6fc262006-10-22 21:36:53 +00001228 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001229 return;
1230 }
1231
1232 // If there are any non-default case statements, create a vector of Cases
1233 // representing each one, and sort the vector so that we can efficiently
1234 // create a binary search tree from them.
1235 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001236
Nate Begemaned728c12006-03-27 01:32:24 +00001237 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1238 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1239 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1240 }
1241 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1242
1243 // Get the Value to be switched on and default basic blocks, which will be
1244 // inserted into CaseBlock records, representing basic blocks in the binary
1245 // search tree.
1246 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001247
1248 // Get the MachineFunction which holds the current MBB. This is used during
1249 // emission of jump tables, and when inserting any additional MBBs necessary
1250 // to represent the switch.
Anton Korobeynikov70378262007-03-25 15:07:15 +00001251 MachineFunction *CurMF = CurMBB->getParent();
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001252
Nate Begemaned728c12006-03-27 01:32:24 +00001253 // Push the initial CaseRec onto the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001254 std::vector<CaseRec> WorkList;
1255 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1256
1257 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001258 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001259 CaseRec CR = WorkList.back();
1260 WorkList.pop_back();
1261 Case& FrontCase = *CR.Range.first;
1262 Case& BackCase = *(CR.Range.second-1);
1263 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1264
1265 // Figure out which block is immediately after the current one.
1266 NextBlock = 0;
1267 BBI = CR.CaseBB;
1268
1269 if (++BBI != CurMBB->getParent()->end())
1270 NextBlock = BBI;
Nate Begemaned728c12006-03-27 01:32:24 +00001271
Anton Korobeynikov70378262007-03-25 15:07:15 +00001272 // Size is the number of Cases represented by this range.
Nate Begemaned728c12006-03-27 01:32:24 +00001273 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001274
1275 // If the range has few cases (two or less) emit a series of specific
1276 // tests.
1277 if (Size < 3) {
1278 // TODO: If any two of the cases has the same destination, and if one value
1279 // is the same as the other, but has one bit unset that the other has set,
1280 // use bit manipulation to do two compares at once. For example:
1281 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Nate Begemaned728c12006-03-27 01:32:24 +00001282
Anton Korobeynikov70378262007-03-25 15:07:15 +00001283 // Rearrange the case blocks so that the last one falls through if possible.
1284 if (NextBlock && Default != NextBlock && BackCase.second != NextBlock) {
1285 // The last case block won't fall through into 'NextBlock' if we emit the
1286 // branches in this order. See if rearranging a case value would help.
1287 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1288 if (I->second == NextBlock) {
1289 std::swap(*I, BackCase);
1290 break;
1291 }
1292 }
1293 }
1294
1295 // Create a CaseBlock record representing a conditional branch to
1296 // the Case's target mbb if the value being switched on SV is equal
1297 // to C.
1298 MachineBasicBlock *CurBlock = CR.CaseBB;
1299 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1300 MachineBasicBlock *FallThrough;
1301 if (I != E-1) {
1302 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1303 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1304 } else {
1305 // If the last case doesn't match, go to the default block.
1306 FallThrough = Default;
1307 }
1308
1309 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, I->first,
1310 I->second, FallThrough, CurBlock);
1311
1312 // If emitting the first comparison, just call visitSwitchCase to emit the
1313 // code into the current block. Otherwise, push the CaseBlock onto the
1314 // vector to be later processed by SDISel, and insert the node's MBB
1315 // before the next MBB.
1316 if (CurBlock == CurMBB)
1317 visitSwitchCase(CB);
1318 else
1319 SwitchCases.push_back(CB);
1320
1321 CurBlock = FallThrough;
1322 }
1323
1324 continue;
1325 }
1326
1327 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1328 // target supports indirect branches, then emit a jump table rather than
1329 // lowering the switch to a binary tree of conditional branches.
1330
1331 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1332 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1333 Size > 5) {
1334 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1335 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1336 double Density = (double)Size / (double)((Last - First) + 1ULL);
1337
1338 if (Density >= 0.3125) {
1339 // Create a new basic block to hold the code for loading the address
1340 // of the jump table, and jumping to it. Update successor information;
1341 // we will either branch to the default case for the switch, or the jump
1342 // table.
1343 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1344 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1345 CR.CaseBB->addSuccessor(Default);
1346 CR.CaseBB->addSuccessor(JumpTableBB);
1347
1348 // Build a vector of destination BBs, corresponding to each target
1349 // of the jump table. If the value of the jump table slot corresponds to
1350 // a case statement, push the case's BB onto the vector, otherwise, push
1351 // the default BB.
1352 std::vector<MachineBasicBlock*> DestBBs;
1353 int64_t TEI = First;
1354 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI)
1355 if (cast<ConstantInt>(I->first)->getSExtValue() == TEI) {
1356 DestBBs.push_back(I->second);
1357 ++I;
1358 } else {
1359 DestBBs.push_back(Default);
1360 }
1361
1362 // Update successor info. Add one edge to each unique successor.
1363 // Vector bool would be better, but vector<bool> is really slow.
1364 std::vector<unsigned char> SuccsHandled;
1365 SuccsHandled.resize(CR.CaseBB->getParent()->getNumBlockIDs());
1366
1367 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1368 E = DestBBs.end(); I != E; ++I) {
1369 if (!SuccsHandled[(*I)->getNumber()]) {
1370 SuccsHandled[(*I)->getNumber()] = true;
1371 JumpTableBB->addSuccessor(*I);
1372 }
1373 }
1374
1375 // Create a jump table index for this jump table, or return an existing
1376 // one.
1377 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1378
1379 // Set the jump table information so that we can codegen it as a second
1380 // MachineBasicBlock
1381 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1382 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1383 (CR.CaseBB == CurMBB));
1384 if (CR.CaseBB == CurMBB)
1385 visitJumpTableHeader(JT, JTH);
1386
1387 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1388
1389 continue;
1390 }
1391 }
1392
1393 // Emit binary tree. If Size is 1, then we are processing a leaf of the
1394 // binary search tree. Otherwise, we need to pick a pivot, and push left
1395 // and right ranges onto the worklist.
1396
1397 if (Size == 1) {
Nate Begemaned728c12006-03-27 01:32:24 +00001398 // Create a CaseBlock record representing a conditional branch to
1399 // the Case's target mbb if the value being switched on SV is equal
1400 // to C. Otherwise, branch to default.
Anton Korobeynikov70378262007-03-25 15:07:15 +00001401 Constant *C = FrontCase.first;
1402 MachineBasicBlock *Target = FrontCase.second;
Nate Begemaned728c12006-03-27 01:32:24 +00001403 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1404 CR.CaseBB);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001405
Nate Begemaned728c12006-03-27 01:32:24 +00001406 // If the MBB representing the leaf node is the current MBB, then just
1407 // call visitSwitchCase to emit the code into the current block.
1408 // Otherwise, push the CaseBlock onto the vector to be later processed
1409 // by SDISel, and insert the node's MBB before the next MBB.
1410 if (CR.CaseBB == CurMBB)
1411 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001412 else
Nate Begemaned728c12006-03-27 01:32:24 +00001413 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001414 } else {
Anton Korobeynikov70378262007-03-25 15:07:15 +00001415 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1416 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1417 double Density = 0;
1418 CaseItr Pivot;
1419
1420 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1421 // (heuristically) allow us to emit JumpTable's later.
1422 unsigned LSize = 1;
1423 unsigned RSize = Size-1;
1424 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1425 J!=E; ++I, ++J, ++LSize, --RSize) {
1426 uint64_t LEnd = cast<ConstantInt>(I->first)->getSExtValue();
1427 uint64_t RBegin = cast<ConstantInt>(J->first)->getSExtValue();
1428 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1429 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1430 if (Density < (LDensity + RDensity)) {
1431 Pivot = J;
1432 Density = LDensity + RDensity;
1433 }
1434 }
1435
Nate Begemaned728c12006-03-27 01:32:24 +00001436 CaseRange LHSR(CR.Range.first, Pivot);
1437 CaseRange RHSR(Pivot, CR.Range.second);
1438 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001439 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001440
Nate Begemaned728c12006-03-27 01:32:24 +00001441 // We know that we branch to the LHS if the Value being switched on is
1442 // less than the Pivot value, C. We use this to optimize our binary
1443 // tree a bit, by recognizing that if SV is greater than or equal to the
1444 // LHS's Case Value, and that Case Value is exactly one less than the
1445 // Pivot's Value, then we can branch directly to the LHS's Target,
1446 // rather than creating a leaf node for it.
1447 if ((LHSR.second - LHSR.first) == 1 &&
1448 LHSR.first->first == CR.GE &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001449 cast<ConstantInt>(C)->getZExtValue() ==
1450 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001451 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001452 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001453 TrueBB = new MachineBasicBlock(LLVMBB);
1454 CurMF->getBasicBlockList().insert(BBI, TrueBB);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001455 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001456 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00001457
Nate Begemaned728c12006-03-27 01:32:24 +00001458 // Similar to the optimization above, if the Value being switched on is
1459 // known to be less than the Constant CR.LT, and the current Case Value
1460 // is CR.LT - 1, then we can branch directly to the target block for
1461 // the current Case Value, rather than emitting a RHS leaf node for it.
1462 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001463 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1464 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001465 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001466 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001467 FalseBB = new MachineBasicBlock(LLVMBB);
1468 CurMF->getBasicBlockList().insert(BBI, FalseBB);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001469 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001470 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001471
Nate Begemaned728c12006-03-27 01:32:24 +00001472 // Create a CaseBlock record representing a conditional branch to
1473 // the LHS node if the value being switched on SV is less than C.
1474 // Otherwise, branch to LHS.
Chris Lattner1cf84d22007-02-14 07:18:16 +00001475 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1476 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001477
Nate Begemaned728c12006-03-27 01:32:24 +00001478 if (CR.CaseBB == CurMBB)
1479 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001480 else
Nate Begemaned728c12006-03-27 01:32:24 +00001481 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001482 }
1483 }
1484}
1485
Anton Korobeynikov70378262007-03-25 15:07:15 +00001486
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001487void SelectionDAGLowering::visitSub(User &I) {
1488 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001489 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001490 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001491 visitVectorBinary(I, ISD::VSUB);
1492 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1494 if (CFP->isExactlyValue(-0.0)) {
1495 SDOperand Op2 = getValue(I.getOperand(1));
1496 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1497 return;
1498 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001499 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001500 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001501 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001502}
1503
Reid Spencer2eadb532007-01-21 00:29:26 +00001504void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001505 SDOperand Op1 = getValue(I.getOperand(0));
1506 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001507
1508 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001509}
1510
Reid Spencer2eadb532007-01-21 00:29:26 +00001511void
1512SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001513 assert(isa<VectorType>(I.getType()));
1514 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001515 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001516
Reid Spencer2eadb532007-01-21 00:29:26 +00001517 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1518 getValue(I.getOperand(0)),
1519 getValue(I.getOperand(1)),
1520 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1521 Typ));
1522}
1523
1524void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1525 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001526 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001527 visitVectorBinary(I, VectorOp);
1528 else
1529 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001530}
Chris Lattner96c26752005-01-19 22:31:21 +00001531
Nate Begeman127321b2005-11-18 07:42:56 +00001532void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1533 SDOperand Op1 = getValue(I.getOperand(0));
1534 SDOperand Op2 = getValue(I.getOperand(1));
1535
Reid Spencer2341c222007-02-02 02:16:23 +00001536 if (TLI.getShiftAmountTy() < Op2.getValueType())
1537 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1538 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1539 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001540
Chris Lattner7a60d912005-01-07 07:47:53 +00001541 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1542}
1543
Reid Spencerd9436b62006-11-20 01:22:35 +00001544void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001545 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1546 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1547 predicate = IC->getPredicate();
1548 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1549 predicate = ICmpInst::Predicate(IC->getPredicate());
1550 SDOperand Op1 = getValue(I.getOperand(0));
1551 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001552 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001553 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001554 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1555 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1556 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1557 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1558 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1559 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1560 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1561 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1562 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1563 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1564 default:
1565 assert(!"Invalid ICmp predicate value");
1566 Opcode = ISD::SETEQ;
1567 break;
1568 }
1569 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1570}
1571
1572void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001573 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1574 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1575 predicate = FC->getPredicate();
1576 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1577 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001578 SDOperand Op1 = getValue(I.getOperand(0));
1579 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001580 ISD::CondCode Condition, FOC, FPC;
1581 switch (predicate) {
1582 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1583 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1584 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1585 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1586 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1587 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1588 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1589 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1590 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1591 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1592 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1593 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1594 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1595 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1596 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1597 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1598 default:
1599 assert(!"Invalid FCmp predicate value");
1600 FOC = FPC = ISD::SETFALSE;
1601 break;
1602 }
1603 if (FiniteOnlyFPMath())
1604 Condition = FOC;
1605 else
1606 Condition = FPC;
1607 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001608}
1609
1610void SelectionDAGLowering::visitSelect(User &I) {
1611 SDOperand Cond = getValue(I.getOperand(0));
1612 SDOperand TrueVal = getValue(I.getOperand(1));
1613 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001614 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001615 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1616 TrueVal, FalseVal));
1617 } else {
1618 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1619 *(TrueVal.Val->op_end()-2),
1620 *(TrueVal.Val->op_end()-1)));
1621 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001622}
1623
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001624
1625void SelectionDAGLowering::visitTrunc(User &I) {
1626 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1627 SDOperand N = getValue(I.getOperand(0));
1628 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1629 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1630}
1631
1632void SelectionDAGLowering::visitZExt(User &I) {
1633 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1634 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1635 SDOperand N = getValue(I.getOperand(0));
1636 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1637 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1638}
1639
1640void SelectionDAGLowering::visitSExt(User &I) {
1641 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1642 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1643 SDOperand N = getValue(I.getOperand(0));
1644 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1645 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1646}
1647
1648void SelectionDAGLowering::visitFPTrunc(User &I) {
1649 // FPTrunc is never a no-op cast, no need to check
1650 SDOperand N = getValue(I.getOperand(0));
1651 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1652 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1653}
1654
1655void SelectionDAGLowering::visitFPExt(User &I){
1656 // FPTrunc is never a no-op cast, no need to check
1657 SDOperand N = getValue(I.getOperand(0));
1658 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1659 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1660}
1661
1662void SelectionDAGLowering::visitFPToUI(User &I) {
1663 // FPToUI is never a no-op cast, no need to check
1664 SDOperand N = getValue(I.getOperand(0));
1665 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1666 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1667}
1668
1669void SelectionDAGLowering::visitFPToSI(User &I) {
1670 // FPToSI is never a no-op cast, no need to check
1671 SDOperand N = getValue(I.getOperand(0));
1672 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1673 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1674}
1675
1676void SelectionDAGLowering::visitUIToFP(User &I) {
1677 // UIToFP is never a no-op cast, no need to check
1678 SDOperand N = getValue(I.getOperand(0));
1679 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1680 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1681}
1682
1683void SelectionDAGLowering::visitSIToFP(User &I){
1684 // UIToFP is never a no-op cast, no need to check
1685 SDOperand N = getValue(I.getOperand(0));
1686 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1687 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1688}
1689
1690void SelectionDAGLowering::visitPtrToInt(User &I) {
1691 // What to do depends on the size of the integer and the size of the pointer.
1692 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001693 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001694 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001695 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001696 SDOperand Result;
1697 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1698 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1699 else
1700 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1701 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1702 setValue(&I, Result);
1703}
Chris Lattner7a60d912005-01-07 07:47:53 +00001704
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001705void SelectionDAGLowering::visitIntToPtr(User &I) {
1706 // What to do depends on the size of the integer and the size of the pointer.
1707 // We can either truncate, zero extend, or no-op, accordingly.
1708 SDOperand N = getValue(I.getOperand(0));
1709 MVT::ValueType SrcVT = N.getValueType();
1710 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1711 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1712 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1713 else
1714 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1715 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1716}
1717
1718void SelectionDAGLowering::visitBitCast(User &I) {
1719 SDOperand N = getValue(I.getOperand(0));
1720 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001721 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001722 // This is a cast to a vector from something else.
1723 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001724 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001725 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1726 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1727 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1728 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001729 return;
1730 }
1731 MVT::ValueType SrcVT = N.getValueType();
1732 if (SrcVT == MVT::Vector) {
1733 // This is a cast from a vctor to something else.
1734 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001735 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001736 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001737 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001738
1739 // BitCast assures us that source and destination are the same size so this
1740 // is either a BIT_CONVERT or a no-op.
1741 if (DestVT != N.getValueType())
1742 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1743 else
1744 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001745}
1746
Chris Lattner67271862006-03-29 00:11:43 +00001747void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001748 SDOperand InVec = getValue(I.getOperand(0));
1749 SDOperand InVal = getValue(I.getOperand(1));
1750 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1751 getValue(I.getOperand(2)));
1752
Chris Lattner29b23012006-03-19 01:17:20 +00001753 SDOperand Num = *(InVec.Val->op_end()-2);
1754 SDOperand Typ = *(InVec.Val->op_end()-1);
1755 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1756 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001757}
1758
Chris Lattner67271862006-03-29 00:11:43 +00001759void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001760 SDOperand InVec = getValue(I.getOperand(0));
1761 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1762 getValue(I.getOperand(1)));
1763 SDOperand Typ = *(InVec.Val->op_end()-1);
1764 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1765 TLI.getValueType(I.getType()), InVec, InIdx));
1766}
Chris Lattner32206f52006-03-18 01:44:44 +00001767
Chris Lattner098c01e2006-04-08 04:15:24 +00001768void SelectionDAGLowering::visitShuffleVector(User &I) {
1769 SDOperand V1 = getValue(I.getOperand(0));
1770 SDOperand V2 = getValue(I.getOperand(1));
1771 SDOperand Mask = getValue(I.getOperand(2));
1772
1773 SDOperand Num = *(V1.Val->op_end()-2);
1774 SDOperand Typ = *(V2.Val->op_end()-1);
1775 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1776 V1, V2, Mask, Num, Typ));
1777}
1778
1779
Chris Lattner7a60d912005-01-07 07:47:53 +00001780void SelectionDAGLowering::visitGetElementPtr(User &I) {
1781 SDOperand N = getValue(I.getOperand(0));
1782 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001783
1784 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1785 OI != E; ++OI) {
1786 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001787 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001788 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001789 if (Field) {
1790 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001791 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001792 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001793 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001794 }
1795 Ty = StTy->getElementType(Field);
1796 } else {
1797 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001798
Chris Lattner43535a12005-11-09 04:45:33 +00001799 // If this is a constant subscript, handle it quickly.
1800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001801 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001802 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001803 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001804 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1805 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001806 }
Chris Lattner43535a12005-11-09 04:45:33 +00001807
1808 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001809 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001810 SDOperand IdxN = getValue(Idx);
1811
1812 // If the index is smaller or larger than intptr_t, truncate or extend
1813 // it.
1814 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001815 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001816 } else if (IdxN.getValueType() > N.getValueType())
1817 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1818
1819 // If this is a multiply by a power of two, turn it into a shl
1820 // immediately. This is a very common case.
1821 if (isPowerOf2_64(ElementSize)) {
1822 unsigned Amt = Log2_64(ElementSize);
1823 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001824 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001825 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1826 continue;
1827 }
1828
1829 SDOperand Scale = getIntPtrConstant(ElementSize);
1830 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1831 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001832 }
1833 }
1834 setValue(&I, N);
1835}
1836
1837void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1838 // If this is a fixed sized alloca in the entry block of the function,
1839 // allocate it statically on the stack.
1840 if (FuncInfo.StaticAllocaMap.count(&I))
1841 return; // getValue will auto-populate this.
1842
1843 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001844 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001845 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00001846 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00001847 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001848
1849 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001850 MVT::ValueType IntPtr = TLI.getPointerTy();
1851 if (IntPtr < AllocSize.getValueType())
1852 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1853 else if (IntPtr > AllocSize.getValueType())
1854 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001855
Chris Lattnereccb73d2005-01-22 23:04:37 +00001856 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001857 getIntPtrConstant(TySize));
1858
1859 // Handle alignment. If the requested alignment is less than or equal to the
1860 // stack alignment, ignore it and round the size of the allocation up to the
1861 // stack alignment size. If the size is greater than the stack alignment, we
1862 // note this in the DYNAMIC_STACKALLOC node.
1863 unsigned StackAlign =
1864 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1865 if (Align <= StackAlign) {
1866 Align = 0;
1867 // Add SA-1 to the size.
1868 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1869 getIntPtrConstant(StackAlign-1));
1870 // Mask out the low bits for alignment purposes.
1871 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1872 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1873 }
1874
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001875 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001876 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1877 MVT::Other);
1878 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00001879 setValue(&I, DSA);
1880 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001881
1882 // Inform the Frame Information that we have just allocated a variable-sized
1883 // object.
1884 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1885}
1886
Chris Lattner7a60d912005-01-07 07:47:53 +00001887void SelectionDAGLowering::visitLoad(LoadInst &I) {
1888 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001889
Chris Lattner4d9651c2005-01-17 22:19:26 +00001890 SDOperand Root;
1891 if (I.isVolatile())
1892 Root = getRoot();
1893 else {
1894 // Do not serialize non-volatile loads against each other.
1895 Root = DAG.getRoot();
1896 }
Chris Lattner4024c002006-03-15 22:19:46 +00001897
Evan Chenge71fe34d2006-10-09 20:57:25 +00001898 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001899 Root, I.isVolatile()));
1900}
1901
1902SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001903 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001904 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001905 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001906 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001907 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001908 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1909 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001910 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001911 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001912 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001913
Chris Lattner4024c002006-03-15 22:19:46 +00001914 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001915 DAG.setRoot(L.getValue(1));
1916 else
1917 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001918
1919 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001920}
1921
1922
1923void SelectionDAGLowering::visitStore(StoreInst &I) {
1924 Value *SrcV = I.getOperand(0);
1925 SDOperand Src = getValue(SrcV);
1926 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001927 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001928 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001929}
1930
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001931/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1932/// access memory and has no other side effects at all.
1933static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1934#define GET_NO_MEMORY_INTRINSICS
1935#include "llvm/Intrinsics.gen"
1936#undef GET_NO_MEMORY_INTRINSICS
1937 return false;
1938}
1939
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001940// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1941// have any side-effects or if it only reads memory.
1942static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1943#define GET_SIDE_EFFECT_INFO
1944#include "llvm/Intrinsics.gen"
1945#undef GET_SIDE_EFFECT_INFO
1946 return false;
1947}
1948
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001949/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1950/// node.
1951void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1952 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001953 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001954 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001955
1956 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001957 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001958 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1959 if (OnlyLoad) {
1960 // We don't need to serialize loads against other loads.
1961 Ops.push_back(DAG.getRoot());
1962 } else {
1963 Ops.push_back(getRoot());
1964 }
1965 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001966
1967 // Add the intrinsic ID as an integer operand.
1968 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1969
1970 // Add all operands of the call to the operand list.
1971 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1972 SDOperand Op = getValue(I.getOperand(i));
1973
Reid Spencer09575ba2007-02-15 03:39:18 +00001974 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001975 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001976 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001977 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1978
1979 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1980 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1981 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1982 }
1983
1984 assert(TLI.isTypeLegal(Op.getValueType()) &&
1985 "Intrinsic uses a non-legal type?");
1986 Ops.push_back(Op);
1987 }
1988
1989 std::vector<MVT::ValueType> VTs;
1990 if (I.getType() != Type::VoidTy) {
1991 MVT::ValueType VT = TLI.getValueType(I.getType());
1992 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001993 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001994 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1995
1996 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1997 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1998 }
1999
2000 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2001 VTs.push_back(VT);
2002 }
2003 if (HasChain)
2004 VTs.push_back(MVT::Other);
2005
Chris Lattnerbd887772006-08-14 23:53:35 +00002006 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2007
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002008 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002009 SDOperand Result;
2010 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002011 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2012 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002013 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002014 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2015 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002016 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002017 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2018 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002019
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002020 if (HasChain) {
2021 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2022 if (OnlyLoad)
2023 PendingLoads.push_back(Chain);
2024 else
2025 DAG.setRoot(Chain);
2026 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002027 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002028 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002029 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2030 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2031 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2032 DAG.getValueType(EVT));
2033 }
2034 setValue(&I, Result);
2035 }
2036}
2037
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002038/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2039/// we want to emit this as a call to a named external function, return the name
2040/// otherwise lower it and return null.
2041const char *
2042SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2043 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002044 default:
2045 // By default, turn this into a target intrinsic node.
2046 visitTargetIntrinsic(I, Intrinsic);
2047 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002048 case Intrinsic::vastart: visitVAStart(I); return 0;
2049 case Intrinsic::vaend: visitVAEnd(I); return 0;
2050 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002051 case Intrinsic::returnaddress:
2052 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2053 getValue(I.getOperand(1))));
2054 return 0;
2055 case Intrinsic::frameaddress:
2056 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2057 getValue(I.getOperand(1))));
2058 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002059 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002060 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002061 break;
2062 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002063 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002064 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002065 case Intrinsic::memcpy_i32:
2066 case Intrinsic::memcpy_i64:
2067 visitMemIntrinsic(I, ISD::MEMCPY);
2068 return 0;
2069 case Intrinsic::memset_i32:
2070 case Intrinsic::memset_i64:
2071 visitMemIntrinsic(I, ISD::MEMSET);
2072 return 0;
2073 case Intrinsic::memmove_i32:
2074 case Intrinsic::memmove_i64:
2075 visitMemIntrinsic(I, ISD::MEMMOVE);
2076 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002077
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002078 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002079 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002080 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002081 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002082 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002083
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002084 Ops[0] = getRoot();
2085 Ops[1] = getValue(SPI.getLineValue());
2086 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002087
Jim Laskeyc56315c2007-01-26 21:22:28 +00002088 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002089 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002090 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2091
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002092 Ops[3] = DAG.getString(CompileUnit->getFileName());
2093 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002094
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002095 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002096 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002097
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002098 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002099 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002100 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002101 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002102 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002103 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2104 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002105 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002106 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002107 }
2108
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002109 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002110 }
2111 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002112 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002113 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002114 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2115 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002116 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002117 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002118 }
2119
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002120 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002121 }
2122 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002123 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002124 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002125 if (MMI && FSI.getSubprogram() &&
2126 MMI->Verify(FSI.getSubprogram())) {
2127 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002128 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002129 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002130 }
2131
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002132 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002133 }
2134 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002135 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002136 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002137 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002138 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002139 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002140 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002141 }
2142
2143 return 0;
2144 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002145
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002146 case Intrinsic::eh_exception: {
2147 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2148
Jim Laskey504e9942007-02-22 15:38:06 +00002149 if (MMI) {
2150 // Add a label to mark the beginning of the landing pad. Deletion of the
2151 // landing pad can thus be detected via the MachineModuleInfo.
2152 unsigned LabelID = MMI->addLandingPad(CurMBB);
2153 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2154 DAG.getConstant(LabelID, MVT::i32)));
2155
2156 // Mark exception register as live in.
2157 unsigned Reg = TLI.getExceptionAddressRegister();
2158 if (Reg) CurMBB->addLiveIn(Reg);
2159
2160 // Insert the EXCEPTIONADDR instruction.
2161 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2162 SDOperand Ops[1];
2163 Ops[0] = DAG.getRoot();
2164 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2165 setValue(&I, Op);
2166 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002167 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002168 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002169 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002170 return 0;
2171 }
2172
Jim Laskeyd5453d72007-03-01 20:24:30 +00002173 case Intrinsic::eh_selector:
2174 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002175 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2176
Jim Laskey504e9942007-02-22 15:38:06 +00002177 if (MMI) {
2178 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002179 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2180 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2181 isa<Function>(CE->getOperand(0)) &&
2182 "Personality should be a function");
2183 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002184 if (Intrinsic == Intrinsic::eh_filter)
2185 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002186
Jim Laskey504e9942007-02-22 15:38:06 +00002187 // Gather all the type infos for this landing pad and pass them along to
2188 // MachineModuleInfo.
2189 std::vector<GlobalVariable *> TyInfo;
2190 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002191 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2192 if (CE && CE->getOpcode() == Instruction::BitCast &&
2193 isa<GlobalVariable>(CE->getOperand(0))) {
2194 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2195 } else {
2196 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2197 assert(CI && CI->getZExtValue() == 0 &&
2198 "TypeInfo must be a global variable typeinfo or NULL");
2199 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002200 }
Jim Laskey504e9942007-02-22 15:38:06 +00002201 }
2202 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2203
2204 // Mark exception selector register as live in.
2205 unsigned Reg = TLI.getExceptionSelectorRegister();
2206 if (Reg) CurMBB->addLiveIn(Reg);
2207
2208 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002209 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002210 SDOperand Ops[2];
2211 Ops[0] = getValue(I.getOperand(1));
2212 Ops[1] = getRoot();
2213 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2214 setValue(&I, Op);
2215 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002216 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002217 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002218 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002219
2220 return 0;
2221 }
2222
2223 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002224 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002225
Jim Laskey504e9942007-02-22 15:38:06 +00002226 if (MMI) {
2227 // Find the type id for the given typeinfo.
2228 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002229 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2230 if (CE && CE->getOpcode() == Instruction::BitCast &&
2231 isa<GlobalVariable>(CE->getOperand(0))) {
2232 GV = cast<GlobalVariable>(CE->getOperand(0));
2233 } else {
2234 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2235 assert(CI && CI->getZExtValue() == 0 &&
2236 "TypeInfo must be a global variable typeinfo or NULL");
2237 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002238 }
2239
2240 unsigned TypeID = MMI->getTypeIDFor(GV);
2241 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002242 } else {
2243 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002244 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002245
2246 return 0;
2247 }
2248
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002249 case Intrinsic::sqrt_f32:
2250 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002251 setValue(&I, DAG.getNode(ISD::FSQRT,
2252 getValue(I.getOperand(1)).getValueType(),
2253 getValue(I.getOperand(1))));
2254 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002255 case Intrinsic::powi_f32:
2256 case Intrinsic::powi_f64:
2257 setValue(&I, DAG.getNode(ISD::FPOWI,
2258 getValue(I.getOperand(1)).getValueType(),
2259 getValue(I.getOperand(1)),
2260 getValue(I.getOperand(2))));
2261 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002262 case Intrinsic::pcmarker: {
2263 SDOperand Tmp = getValue(I.getOperand(1));
2264 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2265 return 0;
2266 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002267 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002268 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002269 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2270 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2271 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002272 setValue(&I, Tmp);
2273 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002274 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002275 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002276 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002277 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002278 case Intrinsic::bswap_i64:
2279 setValue(&I, DAG.getNode(ISD::BSWAP,
2280 getValue(I.getOperand(1)).getValueType(),
2281 getValue(I.getOperand(1))));
2282 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002283 case Intrinsic::cttz_i8:
2284 case Intrinsic::cttz_i16:
2285 case Intrinsic::cttz_i32:
2286 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002287 setValue(&I, DAG.getNode(ISD::CTTZ,
2288 getValue(I.getOperand(1)).getValueType(),
2289 getValue(I.getOperand(1))));
2290 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002291 case Intrinsic::ctlz_i8:
2292 case Intrinsic::ctlz_i16:
2293 case Intrinsic::ctlz_i32:
2294 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002295 setValue(&I, DAG.getNode(ISD::CTLZ,
2296 getValue(I.getOperand(1)).getValueType(),
2297 getValue(I.getOperand(1))));
2298 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002299 case Intrinsic::ctpop_i8:
2300 case Intrinsic::ctpop_i16:
2301 case Intrinsic::ctpop_i32:
2302 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002303 setValue(&I, DAG.getNode(ISD::CTPOP,
2304 getValue(I.getOperand(1)).getValueType(),
2305 getValue(I.getOperand(1))));
2306 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002307 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002308 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002309 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2310 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002311 setValue(&I, Tmp);
2312 DAG.setRoot(Tmp.getValue(1));
2313 return 0;
2314 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002315 case Intrinsic::stackrestore: {
2316 SDOperand Tmp = getValue(I.getOperand(1));
2317 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002318 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002319 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002320 case Intrinsic::prefetch:
2321 // FIXME: Currently discarding prefetches.
2322 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002323 }
2324}
2325
2326
Jim Laskey31fef782007-02-23 21:45:01 +00002327void SelectionDAGLowering::LowerCallTo(Instruction &I,
2328 const Type *CalledValueTy,
2329 unsigned CallingConv,
2330 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002331 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002332 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002333 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2334
2335 TargetLowering::ArgListTy Args;
2336 TargetLowering::ArgListEntry Entry;
2337 Args.reserve(I.getNumOperands());
2338 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2339 Value *Arg = I.getOperand(i);
2340 SDOperand ArgNode = getValue(Arg);
2341 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00002342 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2343 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002344 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2345 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2346 Args.push_back(Entry);
2347 }
2348
2349 std::pair<SDOperand,SDOperand> Result =
2350 TLI.LowerCallTo(getRoot(), I.getType(),
2351 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002352 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002353 Callee, Args, DAG);
2354 if (I.getType() != Type::VoidTy)
2355 setValue(&I, Result.first);
2356 DAG.setRoot(Result.second);
2357}
2358
2359
Chris Lattner7a60d912005-01-07 07:47:53 +00002360void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002361 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002362 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002363 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002364 if (unsigned IID = F->getIntrinsicID()) {
2365 RenameFn = visitIntrinsicCall(I, IID);
2366 if (!RenameFn)
2367 return;
2368 } else { // Not an LLVM intrinsic.
2369 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002370 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2371 if (I.getNumOperands() == 3 && // Basic sanity checks.
2372 I.getOperand(1)->getType()->isFloatingPoint() &&
2373 I.getType() == I.getOperand(1)->getType() &&
2374 I.getType() == I.getOperand(2)->getType()) {
2375 SDOperand LHS = getValue(I.getOperand(1));
2376 SDOperand RHS = getValue(I.getOperand(2));
2377 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2378 LHS, RHS));
2379 return;
2380 }
2381 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002382 if (I.getNumOperands() == 2 && // Basic sanity checks.
2383 I.getOperand(1)->getType()->isFloatingPoint() &&
2384 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002385 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002386 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2387 return;
2388 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002389 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002390 if (I.getNumOperands() == 2 && // Basic sanity checks.
2391 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002392 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002393 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002394 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2395 return;
2396 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002397 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002398 if (I.getNumOperands() == 2 && // Basic sanity checks.
2399 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002400 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002401 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002402 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2403 return;
2404 }
2405 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002406 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002407 } else if (isa<InlineAsm>(I.getOperand(0))) {
2408 visitInlineAsm(I);
2409 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002410 }
Misha Brukman835702a2005-04-21 22:36:52 +00002411
Chris Lattner18d2b342005-01-08 22:48:57 +00002412 SDOperand Callee;
2413 if (!RenameFn)
2414 Callee = getValue(I.getOperand(0));
2415 else
2416 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002417
Jim Laskey31fef782007-02-23 21:45:01 +00002418 LowerCallTo(I, I.getCalledValue()->getType(),
2419 I.getCallingConv(),
2420 I.isTailCall(),
2421 Callee,
2422 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002423}
2424
Jim Laskey504e9942007-02-22 15:38:06 +00002425
Chris Lattner6f87d182006-02-22 22:37:12 +00002426SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002427 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002428 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2429 Chain = Val.getValue(1);
2430 Flag = Val.getValue(2);
2431
2432 // If the result was expanded, copy from the top part.
2433 if (Regs.size() > 1) {
2434 assert(Regs.size() == 2 &&
2435 "Cannot expand to more than 2 elts yet!");
2436 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002437 Chain = Hi.getValue(1);
2438 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002439 if (DAG.getTargetLoweringInfo().isLittleEndian())
2440 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2441 else
2442 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002443 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002444
Chris Lattner705948d2006-06-08 18:22:48 +00002445 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002446 // appropriate type.
2447 if (RegVT == ValueVT)
2448 return Val;
2449
Chris Lattner77f04792007-03-25 05:00:54 +00002450 if (MVT::isVector(RegVT)) {
2451 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2452 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2453 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2454 MVT::i32),
2455 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2456 }
2457
Chris Lattner705948d2006-06-08 18:22:48 +00002458 if (MVT::isInteger(RegVT)) {
2459 if (ValueVT < RegVT)
2460 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2461 else
2462 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002463 }
Chris Lattner77f04792007-03-25 05:00:54 +00002464
2465 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2466 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002467}
2468
Chris Lattner571d9642006-02-23 19:21:04 +00002469/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2470/// specified value into the registers specified by this object. This uses
2471/// Chain/Flag as the input and updates them for the output Chain/Flag.
2472void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002473 SDOperand &Chain, SDOperand &Flag,
2474 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002475 if (Regs.size() == 1) {
2476 // If there is a single register and the types differ, this must be
2477 // a promotion.
2478 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002479 if (MVT::isVector(RegVT)) {
2480 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2481 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2482 } else if (MVT::isInteger(RegVT)) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002483 if (RegVT < ValueVT)
2484 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2485 else
2486 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2487 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002488 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2489 }
2490 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2491 Flag = Chain.getValue(1);
2492 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002493 std::vector<unsigned> R(Regs);
2494 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2495 std::reverse(R.begin(), R.end());
2496
2497 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002498 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002499 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002500 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002501 Flag = Chain.getValue(1);
2502 }
2503 }
2504}
Chris Lattner6f87d182006-02-22 22:37:12 +00002505
Chris Lattner571d9642006-02-23 19:21:04 +00002506/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2507/// operand list. This adds the code marker and includes the number of
2508/// values added into it.
2509void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002510 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002511 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2512 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2513 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2514}
Chris Lattner6f87d182006-02-22 22:37:12 +00002515
2516/// isAllocatableRegister - If the specified register is safe to allocate,
2517/// i.e. it isn't a stack pointer or some other special register, return the
2518/// register class for the register. Otherwise, return null.
2519static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002520isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2521 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002522 MVT::ValueType FoundVT = MVT::Other;
2523 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002524 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2525 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002526 MVT::ValueType ThisVT = MVT::Other;
2527
Chris Lattnerb1124f32006-02-22 23:09:03 +00002528 const TargetRegisterClass *RC = *RCI;
2529 // If none of the the value types for this register class are valid, we
2530 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002531 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2532 I != E; ++I) {
2533 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002534 // If we have already found this register in a different register class,
2535 // choose the one with the largest VT specified. For example, on
2536 // PowerPC, we favor f64 register classes over f32.
2537 if (FoundVT == MVT::Other ||
2538 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2539 ThisVT = *I;
2540 break;
2541 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002542 }
2543 }
2544
Chris Lattnerbec582f2006-04-02 00:24:45 +00002545 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002546
Chris Lattner6f87d182006-02-22 22:37:12 +00002547 // NOTE: This isn't ideal. In particular, this might allocate the
2548 // frame pointer in functions that need it (due to them not being taken
2549 // out of allocation, because a variable sized allocation hasn't been seen
2550 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002551 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2552 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002553 if (*I == Reg) {
2554 // We found a matching register class. Keep looking at others in case
2555 // we find one with larger registers that this physreg is also in.
2556 FoundRC = RC;
2557 FoundVT = ThisVT;
2558 break;
2559 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002560 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002561 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002562}
2563
2564RegsForValue SelectionDAGLowering::
2565GetRegistersForValue(const std::string &ConstrCode,
2566 MVT::ValueType VT, bool isOutReg, bool isInReg,
2567 std::set<unsigned> &OutputRegs,
2568 std::set<unsigned> &InputRegs) {
2569 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2570 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2571 std::vector<unsigned> Regs;
2572
2573 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2574 MVT::ValueType RegVT;
2575 MVT::ValueType ValueVT = VT;
2576
Chris Lattner55402d42006-11-02 01:41:49 +00002577 // If this is a constraint for a specific physical register, like {r17},
2578 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002579 if (PhysReg.first) {
2580 if (VT == MVT::Other)
2581 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002582
2583 // Get the actual register value type. This is important, because the user
2584 // may have asked for (e.g.) the AX register in i32 type. We need to
2585 // remember that AX is actually i16 to get the right extension.
2586 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002587
2588 // This is a explicit reference to a physical register.
2589 Regs.push_back(PhysReg.first);
2590
2591 // If this is an expanded reference, add the rest of the regs to Regs.
2592 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002593 TargetRegisterClass::iterator I = PhysReg.second->begin();
2594 TargetRegisterClass::iterator E = PhysReg.second->end();
2595 for (; *I != PhysReg.first; ++I)
2596 assert(I != E && "Didn't find reg!");
2597
2598 // Already added the first reg.
2599 --NumRegs; ++I;
2600 for (; NumRegs; --NumRegs, ++I) {
2601 assert(I != E && "Ran out of registers to allocate!");
2602 Regs.push_back(*I);
2603 }
2604 }
2605 return RegsForValue(Regs, RegVT, ValueVT);
2606 }
2607
Chris Lattner55402d42006-11-02 01:41:49 +00002608 // Otherwise, if this was a reference to an LLVM register class, create vregs
2609 // for this reference.
2610 std::vector<unsigned> RegClassRegs;
2611 if (PhysReg.second) {
2612 // If this is an early clobber or tied register, our regalloc doesn't know
2613 // how to maintain the constraint. If it isn't, go ahead and create vreg
2614 // and let the regalloc do the right thing.
2615 if (!isOutReg || !isInReg) {
2616 if (VT == MVT::Other)
2617 ValueVT = *PhysReg.second->vt_begin();
2618 RegVT = *PhysReg.second->vt_begin();
2619
2620 // Create the appropriate number of virtual registers.
2621 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2622 for (; NumRegs; --NumRegs)
2623 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2624
2625 return RegsForValue(Regs, RegVT, ValueVT);
2626 }
2627
2628 // Otherwise, we can't allocate it. Let the code below figure out how to
2629 // maintain these constraints.
2630 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2631
2632 } else {
2633 // This is a reference to a register class that doesn't directly correspond
2634 // to an LLVM register class. Allocate NumRegs consecutive, available,
2635 // registers from the class.
2636 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2637 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002638
2639 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2640 MachineFunction &MF = *CurMBB->getParent();
2641 unsigned NumAllocated = 0;
2642 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2643 unsigned Reg = RegClassRegs[i];
2644 // See if this register is available.
2645 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2646 (isInReg && InputRegs.count(Reg))) { // Already used.
2647 // Make sure we find consecutive registers.
2648 NumAllocated = 0;
2649 continue;
2650 }
2651
2652 // Check to see if this register is allocatable (i.e. don't give out the
2653 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002654 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002655 if (!RC) {
2656 // Make sure we find consecutive registers.
2657 NumAllocated = 0;
2658 continue;
2659 }
2660
2661 // Okay, this register is good, we can use it.
2662 ++NumAllocated;
2663
2664 // If we allocated enough consecutive
2665 if (NumAllocated == NumRegs) {
2666 unsigned RegStart = (i-NumAllocated)+1;
2667 unsigned RegEnd = i+1;
2668 // Mark all of the allocated registers used.
2669 for (unsigned i = RegStart; i != RegEnd; ++i) {
2670 unsigned Reg = RegClassRegs[i];
2671 Regs.push_back(Reg);
2672 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2673 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2674 }
2675
2676 return RegsForValue(Regs, *RC->vt_begin(), VT);
2677 }
2678 }
2679
2680 // Otherwise, we couldn't allocate enough registers for this.
2681 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002682}
2683
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002684/// getConstraintGenerality - Return an integer indicating how general CT is.
2685static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2686 switch (CT) {
2687 default: assert(0 && "Unknown constraint type!");
2688 case TargetLowering::C_Other:
2689 case TargetLowering::C_Unknown:
2690 return 0;
2691 case TargetLowering::C_Register:
2692 return 1;
2693 case TargetLowering::C_RegisterClass:
2694 return 2;
2695 case TargetLowering::C_Memory:
2696 return 3;
2697 }
2698}
2699
2700static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2701 const TargetLowering &TLI) {
2702 assert(!C.empty() && "Must have at least one constraint");
2703 if (C.size() == 1) return C[0];
2704
2705 std::string *Current = &C[0];
2706 // If we have multiple constraints, try to pick the most general one ahead
2707 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00002708 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002709 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002710 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002711 if (getConstraintGenerality(ThisFlavor) >
2712 getConstraintGenerality(Flavor)) {
2713 // This constraint letter is more general than the previous one,
2714 // use it.
2715 Flavor = ThisFlavor;
2716 Current = &C[j];
2717 }
2718 }
2719 return *Current;
2720}
2721
Chris Lattner6f87d182006-02-22 22:37:12 +00002722
Chris Lattner476e67b2006-01-26 22:24:51 +00002723/// visitInlineAsm - Handle a call to an InlineAsm object.
2724///
2725void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2726 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2727
2728 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2729 MVT::Other);
2730
Chris Lattner3a5ed552006-02-01 01:28:23 +00002731 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002732 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002733
2734 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2735 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2736 /// if it is a def of that register.
2737 std::vector<SDOperand> AsmNodeOperands;
2738 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2739 AsmNodeOperands.push_back(AsmStr);
2740
2741 SDOperand Chain = getRoot();
2742 SDOperand Flag;
2743
Chris Lattner1558fc62006-02-01 18:59:47 +00002744 // We fully assign registers here at isel time. This is not optimal, but
2745 // should work. For register classes that correspond to LLVM classes, we
2746 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2747 // over the constraints, collecting fixed registers that we know we can't use.
2748 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002749 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002750 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002751 std::string ConstraintCode =
2752 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002753
Chris Lattner7ad77df2006-02-22 00:56:39 +00002754 MVT::ValueType OpVT;
2755
2756 // Compute the value type for each operand and add it to ConstraintVTs.
2757 switch (Constraints[i].Type) {
2758 case InlineAsm::isOutput:
2759 if (!Constraints[i].isIndirectOutput) {
2760 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2761 OpVT = TLI.getValueType(I.getType());
2762 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002763 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002764 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2765 OpNum++; // Consumes a call operand.
2766 }
2767 break;
2768 case InlineAsm::isInput:
2769 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2770 OpNum++; // Consumes a call operand.
2771 break;
2772 case InlineAsm::isClobber:
2773 OpVT = MVT::Other;
2774 break;
2775 }
2776
2777 ConstraintVTs.push_back(OpVT);
2778
Chris Lattner6f87d182006-02-22 22:37:12 +00002779 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2780 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002781
Chris Lattner6f87d182006-02-22 22:37:12 +00002782 // Build a list of regs that this operand uses. This always has a single
2783 // element for promoted/expanded operands.
2784 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2785 false, false,
2786 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002787
2788 switch (Constraints[i].Type) {
2789 case InlineAsm::isOutput:
2790 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002791 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002792 // If this is an early-clobber output, it cannot be assigned to the same
2793 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002794 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002795 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002796 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002797 case InlineAsm::isInput:
2798 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002799 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002800 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002801 case InlineAsm::isClobber:
2802 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002803 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2804 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002805 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002806 }
2807 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002808
Chris Lattner5c79f982006-02-21 23:12:12 +00002809 // Loop over all of the inputs, copying the operand values into the
2810 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002811 RegsForValue RetValRegs;
2812 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002813 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002814
Chris Lattner2e56e892006-01-31 02:03:41 +00002815 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002816 std::string ConstraintCode =
2817 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002818
Chris Lattner3a5ed552006-02-01 01:28:23 +00002819 switch (Constraints[i].Type) {
2820 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002821 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2822 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002823 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00002824
2825 if (CTy == TargetLowering::C_Memory) {
2826 // Memory output.
2827 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2828
2829 // Check that the operand (the address to store to) isn't a float.
2830 if (!MVT::isInteger(InOperandVal.getValueType()))
2831 assert(0 && "MATCH FAIL!");
2832
2833 if (!Constraints[i].isIndirectOutput)
2834 assert(0 && "MATCH FAIL!");
2835
2836 OpNum++; // Consumes a call operand.
2837
2838 // Extend/truncate to the right pointer type if needed.
2839 MVT::ValueType PtrType = TLI.getPointerTy();
2840 if (InOperandVal.getValueType() < PtrType)
2841 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2842 else if (InOperandVal.getValueType() > PtrType)
2843 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2844
2845 // Add information to the INLINEASM node to know about this output.
2846 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2847 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2848 AsmNodeOperands.push_back(InOperandVal);
2849 break;
2850 }
2851
2852 // Otherwise, this is a register output.
2853 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2854
Chris Lattner6f87d182006-02-22 22:37:12 +00002855 // If this is an early-clobber output, or if there is an input
2856 // constraint that matches this, we need to reserve the input register
2857 // so no other inputs allocate to it.
2858 bool UsesInputRegister = false;
2859 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2860 UsesInputRegister = true;
2861
2862 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002863 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002864 RegsForValue Regs =
2865 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2866 true, UsesInputRegister,
2867 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002868 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002869 cerr << "Couldn't allocate output reg for contraint '"
2870 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002871 exit(1);
2872 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002873
Chris Lattner3a5ed552006-02-01 01:28:23 +00002874 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002875 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002876 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002877 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002878 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002879 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002880 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2881 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002882 OpNum++; // Consumes a call operand.
2883 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002884
2885 // Add information to the INLINEASM node to know that this register is
2886 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002887 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002888 break;
2889 }
2890 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002891 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002892 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002893
Chris Lattner7f5880b2006-02-02 00:25:23 +00002894 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2895 // If this is required to match an output register we have already set,
2896 // just use its register.
2897 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002898
Chris Lattner571d9642006-02-23 19:21:04 +00002899 // Scan until we find the definition we already emitted of this operand.
2900 // When we find it, create a RegsForValue operand.
2901 unsigned CurOp = 2; // The first operand.
2902 for (; OperandNo; --OperandNo) {
2903 // Advance to the next operand.
2904 unsigned NumOps =
2905 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002906 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2907 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002908 "Skipped past definitions?");
2909 CurOp += (NumOps>>3)+1;
2910 }
2911
2912 unsigned NumOps =
2913 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00002914 if ((NumOps & 7) == 2 /*REGDEF*/) {
2915 // Add NumOps>>3 registers to MatchedRegs.
2916 RegsForValue MatchedRegs;
2917 MatchedRegs.ValueVT = InOperandVal.getValueType();
2918 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2919 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2920 unsigned Reg =
2921 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2922 MatchedRegs.Regs.push_back(Reg);
2923 }
Chris Lattner571d9642006-02-23 19:21:04 +00002924
Chris Lattnere3eeb242007-02-01 01:21:12 +00002925 // Use the produced MatchedRegs object to
2926 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2927 TLI.getPointerTy());
2928 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2929 break;
2930 } else {
2931 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2932 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00002933 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00002934 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002935
2936 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2937 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002938 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00002939
2940 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002941 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2942 ConstraintCode[0], DAG);
2943 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002944 cerr << "Invalid operand for inline asm constraint '"
2945 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00002946 exit(1);
2947 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002948
2949 // Add information to the INLINEASM node to know about this input.
2950 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2951 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2952 AsmNodeOperands.push_back(InOperandVal);
2953 break;
2954 } else if (CTy == TargetLowering::C_Memory) {
2955 // Memory input.
2956
Chris Lattnerce8aba02007-03-08 22:29:47 +00002957 // If the operand is a float, spill to a constant pool entry to get its
2958 // address.
2959 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
2960 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
2961
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00002962 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00002963 cerr << "Match failed, cannot handle this yet!\n";
2964 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00002965 exit(1);
2966 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002967
2968 // Extend/truncate to the right pointer type if needed.
2969 MVT::ValueType PtrType = TLI.getPointerTy();
2970 if (InOperandVal.getValueType() < PtrType)
2971 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2972 else if (InOperandVal.getValueType() > PtrType)
2973 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2974
2975 // Add information to the INLINEASM node to know about this input.
2976 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2977 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2978 AsmNodeOperands.push_back(InOperandVal);
2979 break;
2980 }
2981
2982 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2983
2984 // Copy the input into the appropriate registers.
2985 RegsForValue InRegs =
2986 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2987 false, true, OutputRegs, InputRegs);
2988 // FIXME: should be match fail.
2989 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2990
Evan Chengef9e07d2006-06-15 08:11:54 +00002991 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002992
2993 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002994 break;
2995 }
Chris Lattner571d9642006-02-23 19:21:04 +00002996 case InlineAsm::isClobber: {
2997 RegsForValue ClobberedRegs =
2998 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2999 OutputRegs, InputRegs);
3000 // Add the clobbered value to the operand list, so that the register
3001 // allocator is aware that the physreg got clobbered.
3002 if (!ClobberedRegs.Regs.empty())
3003 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003004 break;
3005 }
Chris Lattner571d9642006-02-23 19:21:04 +00003006 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003007 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003008
3009 // Finish up input operands.
3010 AsmNodeOperands[0] = Chain;
3011 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3012
Chris Lattnerbd887772006-08-14 23:53:35 +00003013 Chain = DAG.getNode(ISD::INLINEASM,
3014 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003015 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003016 Flag = Chain.getValue(1);
3017
Chris Lattner2e56e892006-01-31 02:03:41 +00003018 // If this asm returns a register value, copy the result from that register
3019 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003020 if (!RetValRegs.Regs.empty())
3021 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00003022
Chris Lattner2e56e892006-01-31 02:03:41 +00003023 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3024
3025 // Process indirect outputs, first output all of the flagged copies out of
3026 // physregs.
3027 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003028 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003029 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003030 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3031 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003032 }
3033
3034 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003035 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003036 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00003037 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003038 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003039 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003040 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003041 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3042 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003043 DAG.setRoot(Chain);
3044}
3045
3046
Chris Lattner7a60d912005-01-07 07:47:53 +00003047void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3048 SDOperand Src = getValue(I.getOperand(0));
3049
3050 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003051
3052 if (IntPtr < Src.getValueType())
3053 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3054 else if (IntPtr > Src.getValueType())
3055 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003056
3057 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003058 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003059 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3060 Src, getIntPtrConstant(ElementSize));
3061
Reid Spencere63b6512006-12-31 05:55:36 +00003062 TargetLowering::ArgListTy Args;
3063 TargetLowering::ArgListEntry Entry;
3064 Entry.Node = Src;
3065 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003066 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003067
3068 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003069 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003070 DAG.getExternalSymbol("malloc", IntPtr),
3071 Args, DAG);
3072 setValue(&I, Result.first); // Pointers always fit in registers
3073 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003074}
3075
3076void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003077 TargetLowering::ArgListTy Args;
3078 TargetLowering::ArgListEntry Entry;
3079 Entry.Node = getValue(I.getOperand(0));
3080 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003081 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003082 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003083 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003084 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003085 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3086 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003087}
3088
Chris Lattner13d7c252005-08-26 20:54:47 +00003089// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3090// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3091// instructions are special in various ways, which require special support to
3092// insert. The specified MachineInstr is created but not inserted into any
3093// basic blocks, and the scheduler passes ownership of it to this method.
3094MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3095 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003096 cerr << "If a target marks an instruction with "
3097 << "'usesCustomDAGSchedInserter', it must implement "
3098 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003099 abort();
3100 return 0;
3101}
3102
Chris Lattner58cfd792005-01-09 00:00:49 +00003103void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003104 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3105 getValue(I.getOperand(1)),
3106 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003107}
3108
3109void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003110 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3111 getValue(I.getOperand(0)),
3112 DAG.getSrcValue(I.getOperand(0)));
3113 setValue(&I, V);
3114 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003115}
3116
3117void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003118 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3119 getValue(I.getOperand(1)),
3120 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003121}
3122
3123void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003124 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3125 getValue(I.getOperand(1)),
3126 getValue(I.getOperand(2)),
3127 DAG.getSrcValue(I.getOperand(1)),
3128 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003129}
3130
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003131/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3132/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3133static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3134 unsigned &i, SelectionDAG &DAG,
3135 TargetLowering &TLI) {
3136 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3137 return SDOperand(Arg, i++);
3138
3139 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3140 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3141 if (NumVals == 1) {
3142 return DAG.getNode(ISD::BIT_CONVERT, VT,
3143 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3144 } else if (NumVals == 2) {
3145 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3146 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3147 if (!TLI.isLittleEndian())
3148 std::swap(Lo, Hi);
3149 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3150 } else {
3151 // Value scalarized into many values. Unimp for now.
3152 assert(0 && "Cannot expand i64 -> i16 yet!");
3153 }
3154 return SDOperand();
3155}
3156
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003157/// TargetLowering::LowerArguments - This is the default LowerArguments
3158/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003159/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3160/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003161std::vector<SDOperand>
3162TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003163 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003164 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3165 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003166 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003167 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3168 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3169
3170 // Add one result value for each formal argument.
3171 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003172 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003173 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3174 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003175 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003176 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003177 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003178 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003179
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003180 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3181 // that is zero extended!
3182 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003183 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003184 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003185 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003186 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003187 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003188 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003189 Flags |= ISD::ParamFlags::StructReturn;
3190 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003191
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003192 switch (getTypeAction(VT)) {
3193 default: assert(0 && "Unknown type action!");
3194 case Legal:
3195 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003196 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003197 break;
3198 case Promote:
3199 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003200 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003201 break;
3202 case Expand:
3203 if (VT != MVT::Vector) {
3204 // If this is a large integer, it needs to be broken up into small
3205 // integers. Figure out what the destination type is and how many small
3206 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003207 MVT::ValueType NVT = getTypeToExpandTo(VT);
3208 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003209 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003210 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003211 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003212 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003213 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3214 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003215 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3216 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003217 } else {
3218 // Otherwise, this is a vector type. We only support legal vectors
3219 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003220 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3221 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003222
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003223 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003224 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003225 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3226 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3227 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003228 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003229 } else {
3230 assert(0 && "Don't support illegal by-val vector arguments yet!");
3231 }
3232 }
3233 break;
3234 }
3235 }
Evan Cheng9618df12006-04-25 23:03:35 +00003236
Chris Lattner3d826992006-05-16 06:45:34 +00003237 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003238
3239 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003240 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3241 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003242 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003243
3244 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003245
3246 // Set up the return result vector.
3247 Ops.clear();
3248 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003249 unsigned Idx = 1;
3250 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3251 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003252 MVT::ValueType VT = getValueType(I->getType());
3253
3254 switch (getTypeAction(VT)) {
3255 default: assert(0 && "Unknown type action!");
3256 case Legal:
3257 Ops.push_back(SDOperand(Result, i++));
3258 break;
3259 case Promote: {
3260 SDOperand Op(Result, i++);
3261 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00003262 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3263 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3264 DAG.getValueType(VT));
3265 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3266 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3267 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003268 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3269 } else {
3270 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3271 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3272 }
3273 Ops.push_back(Op);
3274 break;
3275 }
3276 case Expand:
3277 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003278 // If this is a large integer or a floating point node that needs to be
3279 // expanded, it needs to be reassembled from small integers. Figure out
3280 // what the source elt type is and how many small integers it is.
3281 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003282 } else {
3283 // Otherwise, this is a vector type. We only support legal vectors
3284 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003285 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003286 unsigned NumElems = PTy->getNumElements();
3287 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003288
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003289 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003290 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003291 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003292 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003293 SDOperand N = SDOperand(Result, i++);
3294 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003295 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3296 DAG.getConstant(NumElems, MVT::i32),
3297 DAG.getValueType(getValueType(EltTy)));
3298 Ops.push_back(N);
3299 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003300 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003301 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003302 }
3303 }
3304 break;
3305 }
3306 }
3307 return Ops;
3308}
3309
Chris Lattneraaa23d92006-05-16 22:53:20 +00003310
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003311/// ExpandScalarCallArgs - Recursively expand call argument node by
3312/// bit_converting it or extract a pair of elements from the larger node.
3313static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003314 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003315 SmallVector<SDOperand, 32> &Ops,
3316 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003317 TargetLowering &TLI,
3318 bool isFirst = true) {
3319
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003320 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003321 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003322 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003323 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3324 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003325 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003326 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003327 return;
3328 }
3329
3330 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3331 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3332 if (NumVals == 1) {
3333 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003334 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003335 } else if (NumVals == 2) {
3336 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3337 DAG.getConstant(0, TLI.getPointerTy()));
3338 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3339 DAG.getConstant(1, TLI.getPointerTy()));
3340 if (!TLI.isLittleEndian())
3341 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003342 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3343 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003344 } else {
3345 // Value scalarized into many values. Unimp for now.
3346 assert(0 && "Cannot expand i64 -> i16 yet!");
3347 }
3348}
3349
Chris Lattneraaa23d92006-05-16 22:53:20 +00003350/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3351/// implementation, which just inserts an ISD::CALL node, which is later custom
3352/// lowered by the target to something concrete. FIXME: When all targets are
3353/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3354std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003355TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3356 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003357 unsigned CallingConv, bool isTailCall,
3358 SDOperand Callee,
3359 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003360 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003361 Ops.push_back(Chain); // Op#0 - Chain
3362 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3363 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3364 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3365 Ops.push_back(Callee);
3366
3367 // Handle all of the outgoing arguments.
3368 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003369 MVT::ValueType VT = getValueType(Args[i].Ty);
3370 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003371 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003372 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003373 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003374
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003375 if (Args[i].isSExt)
3376 Flags |= ISD::ParamFlags::SExt;
3377 if (Args[i].isZExt)
3378 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003379 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003380 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003381 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003382 Flags |= ISD::ParamFlags::StructReturn;
3383 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003384
Chris Lattneraaa23d92006-05-16 22:53:20 +00003385 switch (getTypeAction(VT)) {
3386 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003387 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003388 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003389 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003390 break;
3391 case Promote:
3392 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003393 unsigned ExtOp;
3394 if (Args[i].isSExt)
3395 ExtOp = ISD::SIGN_EXTEND;
3396 else if (Args[i].isZExt)
3397 ExtOp = ISD::ZERO_EXTEND;
3398 else
3399 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003400 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3401 } else {
3402 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3403 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3404 }
3405 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003406 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003407 break;
3408 case Expand:
3409 if (VT != MVT::Vector) {
3410 // If this is a large integer, it needs to be broken down into small
3411 // integers. Figure out what the source elt type is and how many small
3412 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003413 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003414 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003415 // Otherwise, this is a vector type. We only support legal vectors
3416 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003417 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003418 unsigned NumElems = PTy->getNumElements();
3419 const Type *EltTy = PTy->getElementType();
3420
3421 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003422 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003423 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003424 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003425 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003426 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3427 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003428 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003429 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003430 assert(0 && "Don't support illegal by-val vector call args yet!");
3431 abort();
3432 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003433 }
3434 break;
3435 }
3436 }
3437
3438 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003439 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003440
3441 if (RetTy != Type::VoidTy) {
3442 MVT::ValueType VT = getValueType(RetTy);
3443 switch (getTypeAction(VT)) {
3444 default: assert(0 && "Unknown type action!");
3445 case Legal:
3446 RetTys.push_back(VT);
3447 break;
3448 case Promote:
3449 RetTys.push_back(getTypeToTransformTo(VT));
3450 break;
3451 case Expand:
3452 if (VT != MVT::Vector) {
3453 // If this is a large integer, it needs to be reassembled from small
3454 // integers. Figure out what the source elt type is and how many small
3455 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003456 MVT::ValueType NVT = getTypeToExpandTo(VT);
3457 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003458 for (unsigned i = 0; i != NumVals; ++i)
3459 RetTys.push_back(NVT);
3460 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003461 // Otherwise, this is a vector type. We only support legal vectors
3462 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003463 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003464 unsigned NumElems = PTy->getNumElements();
3465 const Type *EltTy = PTy->getElementType();
3466
3467 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003468 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003469 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3470 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3471 RetTys.push_back(TVT);
3472 } else {
3473 assert(0 && "Don't support illegal by-val vector call results yet!");
3474 abort();
3475 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003476 }
3477 }
3478 }
3479
3480 RetTys.push_back(MVT::Other); // Always has a chain.
3481
3482 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003483 SDOperand Res = DAG.getNode(ISD::CALL,
3484 DAG.getVTList(&RetTys[0], RetTys.size()),
3485 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003486
3487 // This returns a pair of operands. The first element is the
3488 // return value for the function (if RetTy is not VoidTy). The second
3489 // element is the outgoing token chain.
3490 SDOperand ResVal;
3491 if (RetTys.size() != 1) {
3492 MVT::ValueType VT = getValueType(RetTy);
3493 if (RetTys.size() == 2) {
3494 ResVal = Res;
3495
3496 // If this value was promoted, truncate it down.
3497 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003498 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003499 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003500 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003501 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3502 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003503
3504 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003505 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003506 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003507 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003508 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3509 // "N x PTyElementVT" MVT::Vector type.
3510 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003511 DAG.getConstant(NumElems, MVT::i32),
3512 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003513 } else {
3514 abort();
3515 }
3516 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003517 unsigned AssertOp = ISD::AssertSext;
3518 if (!RetTyIsSigned)
3519 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003520 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3521 DAG.getValueType(VT));
3522 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3523 } else {
3524 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003525 if (getTypeAction(VT) == Expand)
3526 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3527 else
3528 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003529 }
3530 }
3531 } else if (RetTys.size() == 3) {
3532 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3533 Res.getValue(0), Res.getValue(1));
3534
3535 } else {
3536 assert(0 && "Case not handled yet!");
3537 }
3538 }
3539
3540 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3541}
3542
Chris Lattner29dcc712005-05-14 05:50:48 +00003543SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003544 assert(0 && "LowerOperation not implemented for this target!");
3545 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003546 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003547}
3548
Nate Begeman595ec732006-01-28 03:14:31 +00003549SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3550 SelectionDAG &DAG) {
3551 assert(0 && "CustomPromoteOperation not implemented for this target!");
3552 abort();
3553 return SDOperand();
3554}
3555
Evan Cheng6781b6e2006-02-15 21:59:04 +00003556/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003557/// operand.
3558static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003559 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003560 MVT::ValueType CurVT = VT;
3561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3562 uint64_t Val = C->getValue() & 255;
3563 unsigned Shift = 8;
3564 while (CurVT != MVT::i8) {
3565 Val = (Val << Shift) | Val;
3566 Shift <<= 1;
3567 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003568 }
3569 return DAG.getConstant(Val, VT);
3570 } else {
3571 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3572 unsigned Shift = 8;
3573 while (CurVT != MVT::i8) {
3574 Value =
3575 DAG.getNode(ISD::OR, VT,
3576 DAG.getNode(ISD::SHL, VT, Value,
3577 DAG.getConstant(Shift, MVT::i8)), Value);
3578 Shift <<= 1;
3579 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003580 }
3581
3582 return Value;
3583 }
3584}
3585
Evan Cheng6781b6e2006-02-15 21:59:04 +00003586/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3587/// used when a memcpy is turned into a memset when the source is a constant
3588/// string ptr.
3589static SDOperand getMemsetStringVal(MVT::ValueType VT,
3590 SelectionDAG &DAG, TargetLowering &TLI,
3591 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003592 uint64_t Val = 0;
3593 unsigned MSB = getSizeInBits(VT) / 8;
3594 if (TLI.isLittleEndian())
3595 Offset = Offset + MSB - 1;
3596 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003597 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003598 Offset += TLI.isLittleEndian() ? -1 : 1;
3599 }
3600 return DAG.getConstant(Val, VT);
3601}
3602
Evan Cheng81fcea82006-02-14 08:22:34 +00003603/// getMemBasePlusOffset - Returns base and offset node for the
3604static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3605 SelectionDAG &DAG, TargetLowering &TLI) {
3606 MVT::ValueType VT = Base.getValueType();
3607 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3608}
3609
Evan Chengdb2a7a72006-02-14 20:12:38 +00003610/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003611/// to replace the memset / memcpy is below the threshold. It also returns the
3612/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003613static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3614 unsigned Limit, uint64_t Size,
3615 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003616 MVT::ValueType VT;
3617
3618 if (TLI.allowsUnalignedMemoryAccesses()) {
3619 VT = MVT::i64;
3620 } else {
3621 switch (Align & 7) {
3622 case 0:
3623 VT = MVT::i64;
3624 break;
3625 case 4:
3626 VT = MVT::i32;
3627 break;
3628 case 2:
3629 VT = MVT::i16;
3630 break;
3631 default:
3632 VT = MVT::i8;
3633 break;
3634 }
3635 }
3636
Evan Chengd5026102006-02-14 09:11:59 +00003637 MVT::ValueType LVT = MVT::i64;
3638 while (!TLI.isTypeLegal(LVT))
3639 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3640 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003641
Evan Chengd5026102006-02-14 09:11:59 +00003642 if (VT > LVT)
3643 VT = LVT;
3644
Evan Cheng04514992006-02-14 23:05:54 +00003645 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003646 while (Size != 0) {
3647 unsigned VTSize = getSizeInBits(VT) / 8;
3648 while (VTSize > Size) {
3649 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003650 VTSize >>= 1;
3651 }
Evan Chengd5026102006-02-14 09:11:59 +00003652 assert(MVT::isInteger(VT));
3653
3654 if (++NumMemOps > Limit)
3655 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003656 MemOps.push_back(VT);
3657 Size -= VTSize;
3658 }
Evan Chengd5026102006-02-14 09:11:59 +00003659
3660 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003661}
3662
Chris Lattner875def92005-01-11 05:56:49 +00003663void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003664 SDOperand Op1 = getValue(I.getOperand(1));
3665 SDOperand Op2 = getValue(I.getOperand(2));
3666 SDOperand Op3 = getValue(I.getOperand(3));
3667 SDOperand Op4 = getValue(I.getOperand(4));
3668 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3669 if (Align == 0) Align = 1;
3670
3671 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3672 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003673
3674 // Expand memset / memcpy to a series of load / store ops
3675 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003676 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003677 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003678 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003679 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003680 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3681 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003682 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003683 unsigned Offset = 0;
3684 for (unsigned i = 0; i < NumMemOps; i++) {
3685 MVT::ValueType VT = MemOps[i];
3686 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003687 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003688 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003689 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003690 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003691 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003692 Offset += VTSize;
3693 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003694 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003695 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003696 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003697 case ISD::MEMCPY: {
3698 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3699 Size->getValue(), Align, TLI)) {
3700 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003701 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003702 GlobalAddressSDNode *G = NULL;
3703 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003704 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003705
3706 if (Op2.getOpcode() == ISD::GlobalAddress)
3707 G = cast<GlobalAddressSDNode>(Op2);
3708 else if (Op2.getOpcode() == ISD::ADD &&
3709 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3710 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3711 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003712 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003713 }
3714 if (G) {
3715 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003716 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003717 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003718 if (!Str.empty()) {
3719 CopyFromStr = true;
3720 SrcOff += SrcDelta;
3721 }
3722 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003723 }
3724
Evan Chenge2038bd2006-02-15 01:54:51 +00003725 for (unsigned i = 0; i < NumMemOps; i++) {
3726 MVT::ValueType VT = MemOps[i];
3727 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003728 SDOperand Value, Chain, Store;
3729
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003730 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003731 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3732 Chain = getRoot();
3733 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003734 DAG.getStore(Chain, Value,
3735 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003736 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003737 } else {
3738 Value = DAG.getLoad(VT, getRoot(),
3739 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003740 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003741 Chain = Value.getValue(1);
3742 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003743 DAG.getStore(Chain, Value,
3744 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003745 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003746 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003747 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003748 SrcOff += VTSize;
3749 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003750 }
3751 }
3752 break;
3753 }
3754 }
3755
3756 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003757 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3758 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003759 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003760 }
3761 }
3762
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003763 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003764}
3765
Chris Lattner875def92005-01-11 05:56:49 +00003766//===----------------------------------------------------------------------===//
3767// SelectionDAGISel code
3768//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003769
3770unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3771 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3772}
3773
Chris Lattnerc9950c12005-08-17 06:37:43 +00003774void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003775 // FIXME: we only modify the CFG to split critical edges. This
3776 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003777 AU.addRequired<AliasAnalysis>();
Evan Cheng009ea542007-03-16 08:46:27 +00003778 AU.addRequired<LoopInfo>();
3779 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003780}
Chris Lattner7a60d912005-01-07 07:47:53 +00003781
Chris Lattner35397782005-12-05 07:10:48 +00003782
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003783/// OptimizeNoopCopyExpression - We have determined that the specified cast
3784/// instruction is a noop copy (e.g. it's casting from one pointer type to
3785/// another, int->uint, or int->sbyte on PPC.
3786///
3787/// Return true if any changes are made.
3788static bool OptimizeNoopCopyExpression(CastInst *CI) {
3789 BasicBlock *DefBB = CI->getParent();
3790
3791 /// InsertedCasts - Only insert a cast in each block once.
3792 std::map<BasicBlock*, CastInst*> InsertedCasts;
3793
3794 bool MadeChange = false;
3795 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3796 UI != E; ) {
3797 Use &TheUse = UI.getUse();
3798 Instruction *User = cast<Instruction>(*UI);
3799
3800 // Figure out which BB this cast is used in. For PHI's this is the
3801 // appropriate predecessor block.
3802 BasicBlock *UserBB = User->getParent();
3803 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3804 unsigned OpVal = UI.getOperandNo()/2;
3805 UserBB = PN->getIncomingBlock(OpVal);
3806 }
3807
3808 // Preincrement use iterator so we don't invalidate it.
3809 ++UI;
3810
3811 // If this user is in the same block as the cast, don't change the cast.
3812 if (UserBB == DefBB) continue;
3813
3814 // If we have already inserted a cast into this block, use it.
3815 CastInst *&InsertedCast = InsertedCasts[UserBB];
3816
3817 if (!InsertedCast) {
3818 BasicBlock::iterator InsertPt = UserBB->begin();
3819 while (isa<PHINode>(InsertPt)) ++InsertPt;
3820
3821 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003822 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3823 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003824 MadeChange = true;
3825 }
3826
3827 // Replace a use of the cast with a use of the new casat.
3828 TheUse = InsertedCast;
3829 }
3830
3831 // If we removed all uses, nuke the cast.
3832 if (CI->use_empty())
3833 CI->eraseFromParent();
3834
3835 return MadeChange;
3836}
3837
Chris Lattner35397782005-12-05 07:10:48 +00003838/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3839/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003840static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3841 Instruction *GEPI, Value *Ptr,
3842 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003843 if (V) return V; // Already computed.
3844
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003845 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003846 BasicBlock::iterator InsertPt;
3847 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003848 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003849 InsertPt = GEPI;
3850 ++InsertPt;
3851 } else {
3852 // Otherwise, insert at the top of BB, after any PHI nodes
3853 InsertPt = BB->begin();
3854 while (isa<PHINode>(InsertPt)) ++InsertPt;
3855 }
3856
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003857 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3858 // BB so that there is only one value live across basic blocks (the cast
3859 // operand).
3860 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3861 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003862 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3863 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003864
Chris Lattner35397782005-12-05 07:10:48 +00003865 // Add the offset, cast it to the right type.
3866 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003867 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3868 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3869 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003870}
3871
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003872/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3873/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3874/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3875/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3876/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3877/// the constant add into a load or store instruction. Additionally, if a user
3878/// is a pointer-pointer cast, we look through it to find its users.
3879static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3880 Constant *PtrOffset, BasicBlock *DefBB,
3881 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003882 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003883 while (!RepPtr->use_empty()) {
3884 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003885
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003886 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3887 // used for a Pointer-Pointer cast.
3888 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003889 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003890
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003891 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3892 // could invalidate an iterator.
3893 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3894 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003895 }
3896
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003897 // If this is a load of the pointer, or a store through the pointer, emit
3898 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003899 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003900 if (isa<LoadInst>(User) ||
3901 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3902 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3903 User->getParent(), GEPI,
3904 Ptr, PtrOffset);
3905 } else {
3906 // If this use is not foldable into the addressing mode, use a version
3907 // emitted in the GEP block.
3908 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3909 Ptr, PtrOffset);
3910 }
3911
Chris Lattner21cd9902006-05-06 09:10:37 +00003912 if (GEPI->getType() != RepPtr->getType()) {
3913 BasicBlock::iterator IP = NewVal;
3914 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003915 // NewVal must be a GEP which must be pointer type, so BitCast
3916 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00003917 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003918 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003919 }
3920}
Chris Lattner35397782005-12-05 07:10:48 +00003921
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003922
Chris Lattner35397782005-12-05 07:10:48 +00003923/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3924/// selection, we want to be a bit careful about some things. In particular, if
3925/// we have a GEP instruction that is used in a different block than it is
3926/// defined, the addressing expression of the GEP cannot be folded into loads or
3927/// stores that use it. In this case, decompose the GEP and move constant
3928/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003929static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003930 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003931 // If this GEP is only used inside the block it is defined in, there is no
3932 // need to rewrite it.
3933 bool isUsedOutsideDefBB = false;
3934 BasicBlock *DefBB = GEPI->getParent();
3935 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3936 UI != E; ++UI) {
3937 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3938 isUsedOutsideDefBB = true;
3939 break;
3940 }
3941 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003942 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003943
3944 // If this GEP has no non-zero constant indices, there is nothing we can do,
3945 // ignore it.
3946 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003947 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003948 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3949 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003950 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003951 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003952 hasConstantIndex = true;
3953 break;
3954 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003955 } else {
3956 hasVariableIndex = true;
3957 }
Chris Lattner35397782005-12-05 07:10:48 +00003958 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003959
3960 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3961 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003962 /// The GEP operand must be a pointer, so must its result -> BitCast
3963 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003964 GEPI->getName(), GEPI);
3965 GEPI->replaceAllUsesWith(NC);
3966 GEPI->eraseFromParent();
3967 return true;
3968 }
3969
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003970 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003971 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3972 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003973
3974 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3975 // constant offset (which we now know is non-zero) and deal with it later.
3976 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003977 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003978 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003979 const Type *Ty = GEPI->getOperand(0)->getType();
3980
3981 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3982 E = GEPI->op_end(); OI != E; ++OI) {
3983 Value *Idx = *OI;
3984 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003985 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003986 if (Field)
Chris Lattnerc473d8e2007-02-10 19:55:17 +00003987 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner35397782005-12-05 07:10:48 +00003988 Ty = StTy->getElementType(Field);
3989 } else {
3990 Ty = cast<SequentialType>(Ty)->getElementType();
3991
3992 // Handle constant subscripts.
3993 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003994 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00003995 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003996 continue;
3997 }
3998
3999 // Ptr = Ptr + Idx * ElementSize;
4000
4001 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00004002 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00004003
Owen Anderson20a631f2006-05-03 01:29:57 +00004004 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00004005 // Mask off bits that should not be set.
4006 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004007 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00004008
4009 // Multiply by the element size and add to the base.
4010 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
4011 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
4012 }
4013 }
4014
4015 // Make sure that the offset fits in uintptr_t.
4016 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004017 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00004018
4019 // Okay, we have now emitted all of the variable index parts to the BB that
4020 // the GEP is defined in. Loop over all of the using instructions, inserting
4021 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00004022 // instruction to use the newly computed value, making GEPI dead. When the
4023 // user is a load or store instruction address, we emit the add into the user
4024 // block, otherwise we use a canonical version right next to the gep (these
4025 // won't be foldable as addresses, so we might as well share the computation).
4026
Chris Lattner21cd9902006-05-06 09:10:37 +00004027 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004028 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00004029
4030 // Finally, the GEP is dead, remove it.
4031 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004032
4033 return true;
Chris Lattner35397782005-12-05 07:10:48 +00004034}
4035
Evan Cheng009ea542007-03-16 08:46:27 +00004036/// isLoopInvariantInst - Returns true if all operands of the instruction are
4037/// loop invariants in the specified loop.
4038static bool isLoopInvariantInst(Instruction *I, Loop *L) {
4039 // The instruction is loop invariant if all of its operands are loop-invariant
4040 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4041 if (!L->isLoopInvariant(I->getOperand(i)))
4042 return false;
4043 return true;
4044}
4045
4046/// SinkInvariantGEPIndex - If a GEP instruction has a variable index that has
4047/// been hoisted out of the loop by LICM pass, sink it back into the use BB
4048/// if it can be determined that the index computation can be folded into the
4049/// addressing mode of the load / store uses.
4050static bool SinkInvariantGEPIndex(BinaryOperator *BinOp, LoopInfo *loopInfo,
4051 const TargetLowering &TLI) {
Evan Cheng009ea542007-03-16 08:46:27 +00004052 // Only look at Add / Sub for now.
4053 if (BinOp->getOpcode() != Instruction::Add &&
4054 BinOp->getOpcode() != Instruction::Sub)
4055 return false;
4056
Evan Chengbe222352007-03-17 08:22:49 +00004057 // DestBBs - These are the blocks where a copy of BinOp will be inserted.
Evan Chenga2465df2007-03-17 08:53:30 +00004058 SmallSet<BasicBlock*, 8> DestBBs;
Evan Cheng009ea542007-03-16 08:46:27 +00004059 BasicBlock *DefBB = BinOp->getParent();
Evan Chengbe222352007-03-17 08:22:49 +00004060 bool MadeChange = false;
Evan Cheng009ea542007-03-16 08:46:27 +00004061 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
Evan Chengbe222352007-03-17 08:22:49 +00004062 UI != E; ++UI) {
Evan Cheng009ea542007-03-16 08:46:27 +00004063 Instruction *User = cast<Instruction>(*UI);
Evan Cheng009ea542007-03-16 08:46:27 +00004064 // Only look for GEP use in another block.
4065 if (User->getParent() == DefBB) continue;
4066
4067 if (isa<GetElementPtrInst>(User)) {
4068 BasicBlock *UserBB = User->getParent();
4069 Loop *L = loopInfo->getLoopFor(UserBB);
4070
4071 // Only sink if expression is a loop invariant in the use BB.
Evan Cheng0a9d0ca2007-03-16 17:50:20 +00004072 if (L && isLoopInvariantInst(BinOp, L) && !User->use_empty()) {
Evan Cheng009ea542007-03-16 08:46:27 +00004073 const Type *UseTy = NULL;
4074 // FIXME: We are assuming all the uses of the GEP will have the
4075 // same type.
4076 Instruction *GEPUser = cast<Instruction>(*User->use_begin());
4077 if (LoadInst *Load = dyn_cast<LoadInst>(GEPUser))
4078 UseTy = Load->getType();
4079 else if (StoreInst *Store = dyn_cast<StoreInst>(GEPUser))
4080 UseTy = Store->getOperand(0)->getType();
4081
4082 // Check if it is possible to fold the expression to address mode.
4083 if (UseTy &&
Evan Cheng550cf032007-03-20 19:32:11 +00004084 TLI.isLegalAddressExpression(BinOp->getOpcode(),
4085 BinOp->getOperand(0),
Evan Cheng009ea542007-03-16 08:46:27 +00004086 BinOp->getOperand(1), UseTy)) {
Evan Chengbe222352007-03-17 08:22:49 +00004087 DestBBs.insert(UserBB);
Evan Cheng009ea542007-03-16 08:46:27 +00004088 MadeChange = true;
4089 }
4090 }
4091 }
4092 }
4093
Evan Chengbe222352007-03-17 08:22:49 +00004094 // Nothing to do.
4095 if (!MadeChange)
4096 return false;
4097
4098 /// InsertedOps - Only insert a duplicate in each block once.
4099 std::map<BasicBlock*, BinaryOperator*> InsertedOps;
4100 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
4101 UI != E; ) {
4102 Instruction *User = cast<Instruction>(*UI);
4103 BasicBlock *UserBB = User->getParent();
4104
4105 // Preincrement use iterator so we don't invalidate it.
4106 ++UI;
4107
4108 // If any user in this BB wants it, replace all the uses in the BB.
4109 if (DestBBs.count(UserBB)) {
4110 // Sink it into user block.
4111 BinaryOperator *&InsertedOp = InsertedOps[UserBB];
4112 if (!InsertedOp) {
4113 BasicBlock::iterator InsertPt = UserBB->begin();
4114 while (isa<PHINode>(InsertPt)) ++InsertPt;
4115
4116 InsertedOp =
4117 BinaryOperator::create(BinOp->getOpcode(), BinOp->getOperand(0),
4118 BinOp->getOperand(1), "", InsertPt);
4119 }
4120
4121 User->replaceUsesOfWith(BinOp, InsertedOp);
4122 }
4123 }
4124
Evan Cheng009ea542007-03-16 08:46:27 +00004125 if (BinOp->use_empty())
4126 BinOp->eraseFromParent();
4127
Evan Chengbe222352007-03-17 08:22:49 +00004128 return true;
Evan Cheng009ea542007-03-16 08:46:27 +00004129}
4130
Chris Lattnerbba52192006-10-28 19:22:10 +00004131
4132/// SplitEdgeNicely - Split the critical edge from TI to it's specified
4133/// successor if it will improve codegen. We only do this if the successor has
4134/// phi nodes (otherwise critical edges are ok). If there is already another
4135/// predecessor of the succ that is empty (and thus has no phi nodes), use it
4136/// instead of introducing a new block.
4137static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
4138 BasicBlock *TIBB = TI->getParent();
4139 BasicBlock *Dest = TI->getSuccessor(SuccNum);
4140 assert(isa<PHINode>(Dest->begin()) &&
4141 "This should only be called if Dest has a PHI!");
4142
4143 /// TIPHIValues - This array is lazily computed to determine the values of
4144 /// PHIs in Dest that TI would provide.
4145 std::vector<Value*> TIPHIValues;
4146
4147 // Check to see if Dest has any blocks that can be used as a split edge for
4148 // this terminator.
4149 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
4150 BasicBlock *Pred = *PI;
4151 // To be usable, the pred has to end with an uncond branch to the dest.
4152 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
4153 if (!PredBr || !PredBr->isUnconditional() ||
4154 // Must be empty other than the branch.
4155 &Pred->front() != PredBr)
4156 continue;
4157
4158 // Finally, since we know that Dest has phi nodes in it, we have to make
4159 // sure that jumping to Pred will have the same affect as going to Dest in
4160 // terms of PHI values.
4161 PHINode *PN;
4162 unsigned PHINo = 0;
4163 bool FoundMatch = true;
4164 for (BasicBlock::iterator I = Dest->begin();
4165 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
4166 if (PHINo == TIPHIValues.size())
4167 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
4168
4169 // If the PHI entry doesn't work, we can't use this pred.
4170 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
4171 FoundMatch = false;
4172 break;
4173 }
4174 }
4175
4176 // If we found a workable predecessor, change TI to branch to Succ.
4177 if (FoundMatch) {
4178 Dest->removePredecessor(TIBB);
4179 TI->setSuccessor(SuccNum, Pred);
4180 return;
4181 }
4182 }
4183
4184 SplitCriticalEdge(TI, SuccNum, P, true);
4185}
4186
4187
Chris Lattner7a60d912005-01-07 07:47:53 +00004188bool SelectionDAGISel::runOnFunction(Function &Fn) {
4189 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4190 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004191 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004192
Evan Cheng009ea542007-03-16 08:46:27 +00004193 LoopInfo *loopInfo = &getAnalysis<LoopInfo>();
4194
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004195 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00004196 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004197 // In this pass we also look for GEP and cast instructions that are used
4198 // across basic blocks and rewrite them to improve basic-block-at-a-time
4199 // selection.
4200 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004201 bool MadeChange = true;
4202 while (MadeChange) {
4203 MadeChange = false;
Evan Chengde608342007-02-10 01:08:18 +00004204 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbba52192006-10-28 19:22:10 +00004205 // Split all critical edges where the dest block has a PHI.
Evan Chengde608342007-02-10 01:08:18 +00004206 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004207 if (BBTI->getNumSuccessors() > 1) {
4208 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00004209 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4210 isCriticalEdge(BBTI, i, true))
4211 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004212 }
4213
Chris Lattner35397782005-12-05 07:10:48 +00004214
Evan Chengde608342007-02-10 01:08:18 +00004215 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004216 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00004217
4218 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4219 // If we found an inline asm expession, and if the target knows how to
4220 // lower it to normal LLVM code, do so now.
4221 if (isa<InlineAsm>(CI->getCalledValue()))
4222 if (const TargetAsmInfo *TAI =
4223 TLI.getTargetMachine().getTargetAsmInfo()) {
4224 if (TAI->ExpandInlineAsm(CI))
Evan Chengde608342007-02-10 01:08:18 +00004225 BBI = FNI->begin();
Chris Lattner90f42382006-11-29 01:12:32 +00004226 }
4227 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004228 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004229 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00004230 // If the source of the cast is a constant, then this should have
4231 // already been constant folded. The only reason NOT to constant fold
4232 // it is if something (e.g. LSR) was careful to place the constant
4233 // evaluation in a block other than then one that uses it (e.g. to hoist
4234 // the address of globals out of a loop). If this is the case, we don't
4235 // want to forward-subst the cast.
4236 if (isa<Constant>(CI->getOperand(0)))
4237 continue;
4238
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004239 // If this is a noop copy, sink it into user blocks to reduce the number
4240 // of virtual registers that must be created and coallesced.
4241 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4242 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4243
4244 // This is an fp<->int conversion?
4245 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4246 continue;
4247
4248 // If this is an extension, it will be a zero or sign extension, which
4249 // isn't a noop.
4250 if (SrcVT < DstVT) continue;
4251
4252 // If these values will be promoted, find out what they will be promoted
4253 // to. This helps us consider truncates on PPC as noop copies when they
4254 // are.
4255 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4256 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4257 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4258 DstVT = TLI.getTypeToTransformTo(DstVT);
4259
4260 // If, after promotion, these are the same types, this is a noop copy.
4261 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004262 MadeChange |= OptimizeNoopCopyExpression(CI);
Evan Cheng009ea542007-03-16 08:46:27 +00004263 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I)) {
4264 MadeChange |= SinkInvariantGEPIndex(BinOp, loopInfo, TLI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004265 }
4266 }
Chris Lattner1a908c82005-08-18 17:35:14 +00004267 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004268 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00004269
Chris Lattner7a60d912005-01-07 07:47:53 +00004270 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4271
4272 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4273 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004274
Evan Cheng276b44b2007-02-10 02:43:39 +00004275 // Add function live-ins to entry block live-in set.
4276 BasicBlock *EntryBB = &Fn.getEntryBlock();
4277 BB = FuncInfo.MBBMap[EntryBB];
4278 if (!MF.livein_empty())
4279 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4280 E = MF.livein_end(); I != E; ++I)
4281 BB->addLiveIn(I->first);
4282
Chris Lattner7a60d912005-01-07 07:47:53 +00004283 return true;
4284}
4285
Chris Lattnered0110b2006-10-27 21:36:01 +00004286SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4287 unsigned Reg) {
4288 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004289 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004290 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004291 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004292
4293 // If this type is not legal, we must make sure to not create an invalid
4294 // register use.
4295 MVT::ValueType SrcVT = Op.getValueType();
4296 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004297 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004298 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004299 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004300 // Handle copies from generic vectors to registers.
4301 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004302 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004303 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004304
Chris Lattner5fe1f542006-03-31 02:06:56 +00004305 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4306 // MVT::Vector type.
4307 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4308 DAG.getConstant(NE, MVT::i32),
4309 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004310
Chris Lattner5fe1f542006-03-31 02:06:56 +00004311 // Loop over all of the elements of the resultant vector,
4312 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4313 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004314 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004315 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004316 for (unsigned i = 0; i != NE; ++i) {
4317 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004318 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004319 if (PTyElementVT == PTyLegalElementVT) {
4320 // Elements are legal.
4321 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4322 } else if (PTyLegalElementVT > PTyElementVT) {
4323 // Elements are promoted.
4324 if (MVT::isFloatingPoint(PTyLegalElementVT))
4325 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4326 else
4327 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4328 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4329 } else {
4330 // Elements are expanded.
4331 // The src value is expanded into multiple registers.
4332 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004333 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004334 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004335 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004336 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4337 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4338 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004339 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004340 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4341 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004342 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004343 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004344 if (MVT::isFloatingPoint(SrcVT))
4345 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4346 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004347 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004348 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004349 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004350 DestVT = TLI.getTypeToExpandTo(SrcVT);
4351 unsigned NumVals = TLI.getNumElements(SrcVT);
4352 if (NumVals == 1)
4353 return DAG.getCopyToReg(getRoot(), Reg,
4354 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4355 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004356 // The src value is expanded into multiple registers.
4357 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004358 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004359 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004360 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004361 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004362 return DAG.getCopyToReg(Op, Reg+1, Hi);
4363 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004364}
4365
Chris Lattner16f64df2005-01-17 17:15:02 +00004366void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004367LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004368 std::vector<SDOperand> &UnorderedChains) {
4369 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004370 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004371 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004372 SDOperand OldRoot = SDL.DAG.getRoot();
4373 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004374
Chris Lattner6871b232005-10-30 19:42:35 +00004375 unsigned a = 0;
4376 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4377 AI != E; ++AI, ++a)
4378 if (!AI->use_empty()) {
4379 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004380
Chris Lattner6871b232005-10-30 19:42:35 +00004381 // If this argument is live outside of the entry block, insert a copy from
4382 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004383 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4384 if (VMI != FuncInfo.ValueMap.end()) {
4385 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004386 UnorderedChains.push_back(Copy);
4387 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004388 }
Chris Lattner6871b232005-10-30 19:42:35 +00004389
Chris Lattner6871b232005-10-30 19:42:35 +00004390 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004391 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004392 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004393}
4394
Chris Lattner7a60d912005-01-07 07:47:53 +00004395void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4396 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004397 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004398 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004399
4400 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004401
Chris Lattner6871b232005-10-30 19:42:35 +00004402 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004403 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004404 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004405
4406 BB = FuncInfo.MBBMap[LLVMBB];
4407 SDL.setCurrentBasicBlock(BB);
4408
4409 // Lower all of the non-terminator instructions.
4410 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4411 I != E; ++I)
4412 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004413
4414 // Lower call part of invoke.
4415 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4416 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004417
Chris Lattner7a60d912005-01-07 07:47:53 +00004418 // Ensure that all instructions which are used outside of their defining
4419 // blocks are available as virtual registers.
4420 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004421 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004422 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004423 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004424 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004425 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004426 }
4427
4428 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4429 // ensure constants are generated when needed. Remember the virtual registers
4430 // that need to be added to the Machine PHI nodes as input. We cannot just
4431 // directly add them, because expansion might result in multiple MBB's for one
4432 // BB. As such, the start of the BB might correspond to a different MBB than
4433 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004434 //
Chris Lattner84a03502006-10-27 23:50:33 +00004435 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004436
4437 // Emit constants only once even if used by multiple PHI nodes.
4438 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004439
Chris Lattner84a03502006-10-27 23:50:33 +00004440 // Vector bool would be better, but vector<bool> is really slow.
4441 std::vector<unsigned char> SuccsHandled;
4442 if (TI->getNumSuccessors())
4443 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4444
Chris Lattner7a60d912005-01-07 07:47:53 +00004445 // Check successor nodes PHI nodes that expect a constant to be available from
4446 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004447 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4448 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004449 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004450 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004451
Chris Lattner84a03502006-10-27 23:50:33 +00004452 // If this terminator has multiple identical successors (common for
4453 // switches), only handle each succ once.
4454 unsigned SuccMBBNo = SuccMBB->getNumber();
4455 if (SuccsHandled[SuccMBBNo]) continue;
4456 SuccsHandled[SuccMBBNo] = true;
4457
4458 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004459 PHINode *PN;
4460
4461 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4462 // nodes and Machine PHI nodes, but the incoming operands have not been
4463 // emitted yet.
4464 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004465 (PN = dyn_cast<PHINode>(I)); ++I) {
4466 // Ignore dead phi's.
4467 if (PN->use_empty()) continue;
4468
4469 unsigned Reg;
4470 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004471
Chris Lattner84a03502006-10-27 23:50:33 +00004472 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4473 unsigned &RegOut = ConstantsOut[C];
4474 if (RegOut == 0) {
4475 RegOut = FuncInfo.CreateRegForValue(C);
4476 UnorderedChains.push_back(
4477 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004478 }
Chris Lattner84a03502006-10-27 23:50:33 +00004479 Reg = RegOut;
4480 } else {
4481 Reg = FuncInfo.ValueMap[PHIOp];
4482 if (Reg == 0) {
4483 assert(isa<AllocaInst>(PHIOp) &&
4484 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4485 "Didn't codegen value into a register!??");
4486 Reg = FuncInfo.CreateRegForValue(PHIOp);
4487 UnorderedChains.push_back(
4488 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004489 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004490 }
Chris Lattner84a03502006-10-27 23:50:33 +00004491
4492 // Remember that this register needs to added to the machine PHI node as
4493 // the input for this MBB.
4494 MVT::ValueType VT = TLI.getValueType(PN->getType());
4495 unsigned NumElements;
4496 if (VT != MVT::Vector)
4497 NumElements = TLI.getNumElements(VT);
4498 else {
4499 MVT::ValueType VT1,VT2;
4500 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004501 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004502 VT1, VT2);
4503 }
4504 for (unsigned i = 0, e = NumElements; i != e; ++i)
4505 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4506 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004507 }
4508 ConstantsOut.clear();
4509
Chris Lattner718b5c22005-01-13 17:59:43 +00004510 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004511 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004512 SDOperand Root = SDL.getRoot();
4513 if (Root.getOpcode() != ISD::EntryToken) {
4514 unsigned i = 0, e = UnorderedChains.size();
4515 for (; i != e; ++i) {
4516 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4517 if (UnorderedChains[i].Val->getOperand(0) == Root)
4518 break; // Don't add the root if we already indirectly depend on it.
4519 }
4520
4521 if (i == e)
4522 UnorderedChains.push_back(Root);
4523 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004524 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4525 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004526 }
4527
Chris Lattner7a60d912005-01-07 07:47:53 +00004528 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004529 if (Invoke) {
4530 // Just the branch part of invoke.
4531 SDL.visitInvoke(*Invoke, true);
4532 } else {
4533 SDL.visit(*LLVMBB->getTerminator());
4534 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004535
Nate Begemaned728c12006-03-27 01:32:24 +00004536 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004537 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004538 SwitchCases.clear();
4539 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004540 JTCases.clear();
4541 JTCases = SDL.JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +00004542
Chris Lattner4108bb02005-01-17 19:43:36 +00004543 // Make sure the root of the DAG is up-to-date.
4544 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004545}
4546
Nate Begemaned728c12006-03-27 01:32:24 +00004547void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004548 // Get alias analysis for load/store combining.
4549 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4550
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004551 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004552 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004553
Bill Wendling22e978a2006-12-07 20:04:42 +00004554 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004555 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004556
Chris Lattner7a60d912005-01-07 07:47:53 +00004557 // Second step, hack on the DAG until it only uses operations and types that
4558 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004559 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004560
Bill Wendling22e978a2006-12-07 20:04:42 +00004561 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004562 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004563
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004564 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004565 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004566
Evan Cheng739a6a42006-01-21 02:32:06 +00004567 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004568
Chris Lattner5ca31d92005-03-30 01:10:47 +00004569 // Third, instruction select all of the operations to machine code, adding the
4570 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004571 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004572
Bill Wendling22e978a2006-12-07 20:04:42 +00004573 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004574 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004575}
Chris Lattner7a60d912005-01-07 07:47:53 +00004576
Nate Begemaned728c12006-03-27 01:32:24 +00004577void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4578 FunctionLoweringInfo &FuncInfo) {
4579 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4580 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004581 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004582 CurDAG = &DAG;
4583
4584 // First step, lower LLVM code to some DAG. This DAG may use operations and
4585 // types that are not supported by the target.
4586 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4587
4588 // Second step, emit the lowered DAG as machine code.
4589 CodeGenAndEmitDAG(DAG);
4590 }
4591
Chris Lattner5ca31d92005-03-30 01:10:47 +00004592 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004593 // PHI nodes in successors.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004594 if (SwitchCases.empty() && JTCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004595 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4596 MachineInstr *PHI = PHINodesToUpdate[i].first;
4597 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4598 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004599 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004600 PHI->addMachineBasicBlockOperand(BB);
4601 }
4602 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004603 }
Nate Begemaned728c12006-03-27 01:32:24 +00004604
Nate Begeman866b4b42006-04-23 06:26:20 +00004605 // If the JumpTable record is filled in, then we need to emit a jump table.
4606 // Updating the PHI nodes is tricky in this case, since we need to determine
4607 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004608 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4609 // Lower header first, if it wasn't already lowered
4610 if (!JTCases[i].first.Emitted) {
4611 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4612 CurDAG = &HSDAG;
4613 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4614 // Set the current basic block to the mbb we wish to insert the code into
4615 BB = JTCases[i].first.HeaderBB;
4616 HSDL.setCurrentBasicBlock(BB);
4617 // Emit the code
4618 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4619 HSDAG.setRoot(HSDL.getRoot());
4620 CodeGenAndEmitDAG(HSDAG);
4621 }
4622
4623 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4624 CurDAG = &JSDAG;
4625 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004626 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004627 BB = JTCases[i].second.MBB;
4628 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004629 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004630 JSDL.visitJumpTable(JTCases[i].second);
4631 JSDAG.setRoot(JSDL.getRoot());
4632 CodeGenAndEmitDAG(JSDAG);
4633
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004634 // Update PHI Nodes
4635 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4636 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4637 MachineBasicBlock *PHIBB = PHI->getParent();
4638 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4639 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov70378262007-03-25 15:07:15 +00004640 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004641 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004642 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004643 }
4644 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004645 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004646 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004647 }
4648 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004649 }
4650
Chris Lattner76a7bc82006-10-22 23:00:53 +00004651 // If the switch block involved a branch to one of the actual successors, we
4652 // need to update PHI nodes in that block.
4653 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4654 MachineInstr *PHI = PHINodesToUpdate[i].first;
4655 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4656 "This is not a machine PHI node that we are updating!");
4657 if (BB->isSuccessor(PHI->getParent())) {
4658 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4659 PHI->addMachineBasicBlockOperand(BB);
4660 }
4661 }
4662
Nate Begemaned728c12006-03-27 01:32:24 +00004663 // If we generated any switch lowering information, build and codegen any
4664 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004665 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004666 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004667 CurDAG = &SDAG;
4668 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004669
Nate Begemaned728c12006-03-27 01:32:24 +00004670 // Set the current basic block to the mbb we wish to insert the code into
4671 BB = SwitchCases[i].ThisBB;
4672 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004673
Nate Begemaned728c12006-03-27 01:32:24 +00004674 // Emit the code
4675 SDL.visitSwitchCase(SwitchCases[i]);
4676 SDAG.setRoot(SDL.getRoot());
4677 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004678
4679 // Handle any PHI nodes in successors of this chunk, as if we were coming
4680 // from the original BB before switch expansion. Note that PHI nodes can
4681 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4682 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004683 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004684 for (MachineBasicBlock::iterator Phi = BB->begin();
4685 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4686 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4687 for (unsigned pn = 0; ; ++pn) {
4688 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4689 if (PHINodesToUpdate[pn].first == Phi) {
4690 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4691 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4692 break;
4693 }
4694 }
Nate Begemaned728c12006-03-27 01:32:24 +00004695 }
Chris Lattner707339a52006-09-07 01:59:34 +00004696
4697 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004698 if (BB == SwitchCases[i].FalseBB)
4699 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004700
4701 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004702 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004703 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004704 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004705 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004706 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004707}
Evan Cheng739a6a42006-01-21 02:32:06 +00004708
Jim Laskey95eda5b2006-08-01 14:21:23 +00004709
Evan Cheng739a6a42006-01-21 02:32:06 +00004710//===----------------------------------------------------------------------===//
4711/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4712/// target node in the graph.
4713void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4714 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004715
Jim Laskey29e635d2006-08-02 12:30:23 +00004716 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004717
4718 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004719 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004720 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004721 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004722
Jim Laskey03593f72006-08-01 18:29:48 +00004723 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004724 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004725 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004726}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004727
Chris Lattner47639db2006-03-06 00:22:00 +00004728
Jim Laskey03593f72006-08-01 18:29:48 +00004729HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4730 return new HazardRecognizer();
4731}
4732
Chris Lattner6df34962006-10-11 03:58:02 +00004733//===----------------------------------------------------------------------===//
4734// Helper functions used by the generated instruction selector.
4735//===----------------------------------------------------------------------===//
4736// Calls to these methods are generated by tblgen.
4737
4738/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4739/// the dag combiner simplified the 255, we still want to match. RHS is the
4740/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4741/// specified in the .td file (e.g. 255).
4742bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4743 int64_t DesiredMaskS) {
4744 uint64_t ActualMask = RHS->getValue();
4745 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4746
4747 // If the actual mask exactly matches, success!
4748 if (ActualMask == DesiredMask)
4749 return true;
4750
4751 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4752 if (ActualMask & ~DesiredMask)
4753 return false;
4754
4755 // Otherwise, the DAG Combiner may have proven that the value coming in is
4756 // either already zero or is not demanded. Check for known zero input bits.
4757 uint64_t NeededMask = DesiredMask & ~ActualMask;
4758 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4759 return true;
4760
4761 // TODO: check to see if missing bits are just not demanded.
4762
4763 // Otherwise, this pattern doesn't match.
4764 return false;
4765}
4766
4767/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4768/// the dag combiner simplified the 255, we still want to match. RHS is the
4769/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4770/// specified in the .td file (e.g. 255).
4771bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4772 int64_t DesiredMaskS) {
4773 uint64_t ActualMask = RHS->getValue();
4774 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4775
4776 // If the actual mask exactly matches, success!
4777 if (ActualMask == DesiredMask)
4778 return true;
4779
4780 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4781 if (ActualMask & ~DesiredMask)
4782 return false;
4783
4784 // Otherwise, the DAG Combiner may have proven that the value coming in is
4785 // either already zero or is not demanded. Check for known zero input bits.
4786 uint64_t NeededMask = DesiredMask & ~ActualMask;
4787
4788 uint64_t KnownZero, KnownOne;
4789 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4790
4791 // If all the missing bits in the or are already known to be set, match!
4792 if ((NeededMask & KnownOne) == NeededMask)
4793 return true;
4794
4795 // TODO: check to see if missing bits are just not demanded.
4796
4797 // Otherwise, this pattern doesn't match.
4798 return false;
4799}
4800
Jim Laskey03593f72006-08-01 18:29:48 +00004801
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004802/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4803/// by tblgen. Others should not call it.
4804void SelectionDAGISel::
4805SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4806 std::vector<SDOperand> InOps;
4807 std::swap(InOps, Ops);
4808
4809 Ops.push_back(InOps[0]); // input chain.
4810 Ops.push_back(InOps[1]); // input asm string.
4811
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004812 unsigned i = 2, e = InOps.size();
4813 if (InOps[e-1].getValueType() == MVT::Flag)
4814 --e; // Don't process a flag operand if it is here.
4815
4816 while (i != e) {
4817 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4818 if ((Flags & 7) != 4 /*MEM*/) {
4819 // Just skip over this operand, copying the operands verbatim.
4820 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4821 i += (Flags >> 3) + 1;
4822 } else {
4823 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4824 // Otherwise, this is a memory operand. Ask the target to select it.
4825 std::vector<SDOperand> SelOps;
4826 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004827 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004828 exit(1);
4829 }
4830
4831 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004832 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4833 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004834 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4835 i += 2;
4836 }
4837 }
4838
4839 // Add the flag input back if present.
4840 if (e != InOps.size())
4841 Ops.push_back(InOps.back());
4842}