blob: 3e39046620833f4b4846cdc9173c8980e9c5d499 [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 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000387
388 typedef std::vector<CaseRec> CaseRecVector;
Nate Begemaned728c12006-03-27 01:32:24 +0000389
390 /// The comparison function for sorting Case values.
391 struct CaseCmp {
392 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000393 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattner2fbff4d2007-02-13 20:09:07 +0000394 return cast<const ConstantInt>(C1.first)->getSExtValue() <
395 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000396 }
397 };
398
Chris Lattner7a60d912005-01-07 07:47:53 +0000399public:
400 // TLI - This is information that describes the available target features we
401 // need for lowering. This indicates when operations are unavailable,
402 // implemented with a libcall, etc.
403 TargetLowering &TLI;
404 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000405 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000406
Nate Begemaned728c12006-03-27 01:32:24 +0000407 /// SwitchCases - Vector of CaseBlock structures used to communicate
408 /// SwitchInst code generation information.
409 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000410 /// JTCases - Vector of JumpTable structures used to communicate
411 /// SwitchInst code generation information.
412 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000413
Chris Lattner7a60d912005-01-07 07:47:53 +0000414 /// FuncInfo - Information about the function as a whole.
415 ///
416 FunctionLoweringInfo &FuncInfo;
417
418 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000419 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000421 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000422 }
423
Chris Lattner4108bb02005-01-17 19:43:36 +0000424 /// getRoot - Return the current virtual root of the Selection DAG.
425 ///
426 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000427 if (PendingLoads.empty())
428 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000429
Chris Lattner4d9651c2005-01-17 22:19:26 +0000430 if (PendingLoads.size() == 1) {
431 SDOperand Root = PendingLoads[0];
432 DAG.setRoot(Root);
433 PendingLoads.clear();
434 return Root;
435 }
436
437 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000438 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
439 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000440 PendingLoads.clear();
441 DAG.setRoot(Root);
442 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000443 }
444
Chris Lattnered0110b2006-10-27 21:36:01 +0000445 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
446
Chris Lattner7a60d912005-01-07 07:47:53 +0000447 void visit(Instruction &I) { visit(I.getOpcode(), I); }
448
449 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000450 // Note: this doesn't use InstVisitor, because it has to work with
451 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000452 switch (Opcode) {
453 default: assert(0 && "Unknown instruction type encountered!");
454 abort();
455 // Build the switch statement using the Instruction.def file.
456#define HANDLE_INST(NUM, OPCODE, CLASS) \
457 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
458#include "llvm/Instruction.def"
459 }
460 }
461
462 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
463
Chris Lattner4024c002006-03-15 22:19:46 +0000464 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000465 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000466 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000467
468 SDOperand getIntPtrConstant(uint64_t Val) {
469 return DAG.getConstant(Val, TLI.getPointerTy());
470 }
471
Chris Lattner8471b152006-03-16 19:57:50 +0000472 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000473
Chris Lattner79084302007-02-04 01:31:47 +0000474 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000475 SDOperand &N = NodeMap[V];
476 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000477 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000478 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000479
Chris Lattner6f87d182006-02-22 22:37:12 +0000480 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
481 MVT::ValueType VT,
482 bool OutReg, bool InReg,
483 std::set<unsigned> &OutputRegs,
484 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000485
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
487 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
488 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000489 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000490 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000491 void LowerCallTo(Instruction &I,
492 const Type *CalledValueTy, unsigned CallingConv,
493 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000494
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 // Terminator instructions.
496 void visitRet(ReturnInst &I);
497 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000498 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 void visitUnreachable(UnreachableInst &I) { /* noop */ }
500
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000501 // Helpers for visitSwitch
502 void handleSmallSwitchRange(CaseRec& CR,
503 CaseRecVector& WorkList,
504 Value* SV,
505 MachineBasicBlock* Default);
506 void handleJTSwitchCase(CaseRec& CR,
507 CaseRecVector& WorkList,
508 Value* SV,
509 MachineBasicBlock* Default);
510 void handleBTSplitSwitchCase(CaseRec& CR,
511 CaseRecVector& WorkList,
512 Value* SV,
513 MachineBasicBlock* Default);
514 void handleBTSmallSwitchCase(CaseRec& CR,
515 CaseRecVector& WorkList,
516 Value* SV,
517 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000518 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000519 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000520 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
521 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000522
Chris Lattner7a60d912005-01-07 07:47:53 +0000523 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000524 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000525 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000526 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527
Reid Spencer2eadb532007-01-21 00:29:26 +0000528 void visitScalarBinary(User &I, unsigned OpCode);
529 void visitVectorBinary(User &I, unsigned OpCode);
530 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000531 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000532 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000533 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000534 visitVectorBinary(I, ISD::VADD);
535 else if (I.getType()->isFloatingPoint())
536 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000537 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000538 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000539 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000540 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000541 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000542 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000543 visitVectorBinary(I, ISD::VMUL);
544 else if (I.getType()->isFloatingPoint())
545 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000546 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000547 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000548 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000549 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
550 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
551 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
552 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
553 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
554 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
555 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
556 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
557 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
558 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000559 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
560 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000561 void visitICmp(User &I);
562 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000563 // Visit the conversion instructions
564 void visitTrunc(User &I);
565 void visitZExt(User &I);
566 void visitSExt(User &I);
567 void visitFPTrunc(User &I);
568 void visitFPExt(User &I);
569 void visitFPToUI(User &I);
570 void visitFPToSI(User &I);
571 void visitUIToFP(User &I);
572 void visitSIToFP(User &I);
573 void visitPtrToInt(User &I);
574 void visitIntToPtr(User &I);
575 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000576
Chris Lattner67271862006-03-29 00:11:43 +0000577 void visitExtractElement(User &I);
578 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000579 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000580
Chris Lattner7a60d912005-01-07 07:47:53 +0000581 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000582 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000583
584 void visitMalloc(MallocInst &I);
585 void visitFree(FreeInst &I);
586 void visitAlloca(AllocaInst &I);
587 void visitLoad(LoadInst &I);
588 void visitStore(StoreInst &I);
589 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
590 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000591 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000592 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000593 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000594
Chris Lattner7a60d912005-01-07 07:47:53 +0000595 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000596 void visitVAArg(VAArgInst &I);
597 void visitVAEnd(CallInst &I);
598 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000599
Chris Lattner875def92005-01-11 05:56:49 +0000600 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000601
602 void visitUserOp1(Instruction &I) {
603 assert(0 && "UserOp1 should not exist at instruction selection time!");
604 abort();
605 }
606 void visitUserOp2(Instruction &I) {
607 assert(0 && "UserOp2 should not exist at instruction selection time!");
608 abort();
609 }
610};
611} // end namespace llvm
612
Chris Lattner8471b152006-03-16 19:57:50 +0000613SDOperand SelectionDAGLowering::getValue(const Value *V) {
614 SDOperand &N = NodeMap[V];
615 if (N.Val) return N;
616
617 const Type *VTy = V->getType();
618 MVT::ValueType VT = TLI.getValueType(VTy);
619 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
621 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000622 SDOperand N1 = NodeMap[V];
623 assert(N1.Val && "visit didn't populate the ValueMap!");
624 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000625 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
626 return N = DAG.getGlobalAddress(GV, VT);
627 } else if (isa<ConstantPointerNull>(C)) {
628 return N = DAG.getConstant(0, TLI.getPointerTy());
629 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000630 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000631 return N = DAG.getNode(ISD::UNDEF, VT);
632
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000633 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000634 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000635 unsigned NumElements = PTy->getNumElements();
636 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
637
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000638 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000639 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
640
641 // Create a VConstant node with generic Vector type.
642 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
643 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000644 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
645 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000646 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
647 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000648 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000649 unsigned NumElements = PTy->getNumElements();
650 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000651
652 // Now that we know the number and type of the elements, push a
653 // Constant or ConstantFP node onto the ops list for each element of
654 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000655 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000656 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000657 for (unsigned i = 0; i != NumElements; ++i)
658 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000659 } else {
660 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
661 SDOperand Op;
662 if (MVT::isFloatingPoint(PVT))
663 Op = DAG.getConstantFP(0, PVT);
664 else
665 Op = DAG.getConstant(0, PVT);
666 Ops.assign(NumElements, Op);
667 }
668
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000669 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000670 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
671 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000672 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
673 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000674 } else {
675 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000676 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000677 }
678 }
679
680 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
681 std::map<const AllocaInst*, int>::iterator SI =
682 FuncInfo.StaticAllocaMap.find(AI);
683 if (SI != FuncInfo.StaticAllocaMap.end())
684 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
685 }
686
Chris Lattner8c504cf2007-02-25 18:40:32 +0000687 unsigned InReg = FuncInfo.ValueMap[V];
688 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000689
690 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000691 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000692 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000693 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000694 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000695 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
696 unsigned NumVals = TLI.getNumElements(VT);
697 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
698 if (NumVals == 1)
699 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
700 else {
701 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
702 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
703 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
704 }
705 } else {
706 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
707 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
708 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
709 N = MVT::isFloatingPoint(VT)
710 ? DAG.getNode(ISD::FP_ROUND, VT, N)
711 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000712 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000713 } else {
714 // Otherwise, if this is a vector, make it available as a generic vector
715 // here.
716 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000717 const VectorType *PTy = cast<VectorType>(VTy);
718 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000719 PTyLegalElementVT);
720
721 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000722 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000723 if (PTyElementVT == PTyLegalElementVT) {
724 // If the value types are legal, just VBUILD the CopyFromReg nodes.
725 for (unsigned i = 0; i != NE; ++i)
726 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727 PTyElementVT));
728 } else if (PTyElementVT < PTyLegalElementVT) {
729 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
730 for (unsigned i = 0; i != NE; ++i) {
731 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
732 PTyElementVT);
733 if (MVT::isFloatingPoint(PTyElementVT))
734 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
735 else
736 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
737 Ops.push_back(Op);
738 }
739 } else {
740 // If the register was expanded, use BUILD_PAIR.
741 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
742 for (unsigned i = 0; i != NE/2; ++i) {
743 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
744 PTyElementVT);
745 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
746 PTyElementVT);
747 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
748 }
749 }
750
751 Ops.push_back(DAG.getConstant(NE, MVT::i32));
752 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000753 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000754
755 // Finally, use a VBIT_CONVERT to make this available as the appropriate
756 // vector type.
757 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
758 DAG.getConstant(PTy->getNumElements(),
759 MVT::i32),
760 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000761 }
762
763 return N;
764}
765
766
Chris Lattner7a60d912005-01-07 07:47:53 +0000767void SelectionDAGLowering::visitRet(ReturnInst &I) {
768 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000769 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000770 return;
771 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000772 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000773 NewValues.push_back(getRoot());
774 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
775 SDOperand RetOp = getValue(I.getOperand(i));
776
777 // If this is an integer return value, we need to promote it ourselves to
778 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
779 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000780 // FIXME: C calling convention requires the return type to be promoted to
781 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000782 if (MVT::isInteger(RetOp.getValueType()) &&
783 RetOp.getValueType() < MVT::i64) {
784 MVT::ValueType TmpVT;
785 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
786 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
787 else
788 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000789 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000790 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000791 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
792 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000793 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
794 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000795 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000796 }
797 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000798 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000799 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000800 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
801 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000802}
803
Chris Lattnered0110b2006-10-27 21:36:01 +0000804/// ExportFromCurrentBlock - If this condition isn't known to be exported from
805/// the current basic block, add it to ValueMap now so that we'll get a
806/// CopyTo/FromReg.
807void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
808 // No need to export constants.
809 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
810
811 // Already exported?
812 if (FuncInfo.isExportedInst(V)) return;
813
814 unsigned Reg = FuncInfo.InitializeRegForValue(V);
815 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
816}
817
Chris Lattner84a03502006-10-27 23:50:33 +0000818bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
819 const BasicBlock *FromBB) {
820 // The operands of the setcc have to be in this block. We don't know
821 // how to export them from some other block.
822 if (Instruction *VI = dyn_cast<Instruction>(V)) {
823 // Can export from current BB.
824 if (VI->getParent() == FromBB)
825 return true;
826
827 // Is already exported, noop.
828 return FuncInfo.isExportedInst(V);
829 }
830
831 // If this is an argument, we can export it if the BB is the entry block or
832 // if it is already exported.
833 if (isa<Argument>(V)) {
834 if (FromBB == &FromBB->getParent()->getEntryBlock())
835 return true;
836
837 // Otherwise, can only export this if it is already exported.
838 return FuncInfo.isExportedInst(V);
839 }
840
841 // Otherwise, constants can always be exported.
842 return true;
843}
844
Chris Lattnere60ae822006-10-29 21:01:20 +0000845static bool InBlock(const Value *V, const BasicBlock *BB) {
846 if (const Instruction *I = dyn_cast<Instruction>(V))
847 return I->getParent() == BB;
848 return true;
849}
850
Chris Lattnered0110b2006-10-27 21:36:01 +0000851/// FindMergedConditions - If Cond is an expression like
852void SelectionDAGLowering::FindMergedConditions(Value *Cond,
853 MachineBasicBlock *TBB,
854 MachineBasicBlock *FBB,
855 MachineBasicBlock *CurBB,
856 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000857 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000858 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000859
Reid Spencer266e42b2006-12-23 06:05:41 +0000860 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
861 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000862 BOp->getParent() != CurBB->getBasicBlock() ||
863 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
864 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000865 const BasicBlock *BB = CurBB->getBasicBlock();
866
Reid Spencer266e42b2006-12-23 06:05:41 +0000867 // If the leaf of the tree is a comparison, merge the condition into
868 // the caseblock.
869 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
870 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000871 // how to export them from some other block. If this is the first block
872 // of the sequence, no exporting is needed.
873 (CurBB == CurMBB ||
874 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
875 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000876 BOp = cast<Instruction>(Cond);
877 ISD::CondCode Condition;
878 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
879 switch (IC->getPredicate()) {
880 default: assert(0 && "Unknown icmp predicate opcode!");
881 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
882 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
883 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
884 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
885 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
886 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
887 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
888 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
889 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
890 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
891 }
892 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
893 ISD::CondCode FPC, FOC;
894 switch (FC->getPredicate()) {
895 default: assert(0 && "Unknown fcmp predicate opcode!");
896 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
897 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
898 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
899 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
900 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
901 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
902 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
903 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
904 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
905 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
906 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
907 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
908 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
909 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
910 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
911 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
912 }
913 if (FiniteOnlyFPMath())
914 Condition = FOC;
915 else
916 Condition = FPC;
917 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000918 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000919 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000920 }
921
Chris Lattnered0110b2006-10-27 21:36:01 +0000922 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
923 BOp->getOperand(1), TBB, FBB, CurBB);
924 SwitchCases.push_back(CB);
925 return;
926 }
927
928 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000929 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000930 TBB, FBB, CurBB);
931 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000932 return;
933 }
934
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000935
936 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000937 MachineFunction::iterator BBI = CurBB;
938 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
939 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
940
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000941 if (Opc == Instruction::Or) {
942 // Codegen X | Y as:
943 // jmp_if_X TBB
944 // jmp TmpBB
945 // TmpBB:
946 // jmp_if_Y TBB
947 // jmp FBB
948 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000949
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000950 // Emit the LHS condition.
951 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
952
953 // Emit the RHS condition into TmpBB.
954 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
955 } else {
956 assert(Opc == Instruction::And && "Unknown merge op!");
957 // Codegen X & Y as:
958 // jmp_if_X TmpBB
959 // jmp FBB
960 // TmpBB:
961 // jmp_if_Y TBB
962 // jmp FBB
963 //
964 // This requires creation of TmpBB after CurBB.
965
966 // Emit the LHS condition.
967 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
968
969 // Emit the RHS condition into TmpBB.
970 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
971 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000972}
973
Chris Lattner427301f2006-10-31 22:37:42 +0000974/// If the set of cases should be emitted as a series of branches, return true.
975/// If we should emit this as a bunch of and/or'd together conditions, return
976/// false.
977static bool
978ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
979 if (Cases.size() != 2) return true;
980
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000981 // If this is two comparisons of the same values or'd or and'd together, they
982 // will get folded into a single comparison, so don't emit two blocks.
983 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
984 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
985 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
986 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
987 return false;
988 }
989
Chris Lattner427301f2006-10-31 22:37:42 +0000990 return true;
991}
992
Chris Lattner7a60d912005-01-07 07:47:53 +0000993void SelectionDAGLowering::visitBr(BranchInst &I) {
994 // Update machine-CFG edges.
995 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000996
997 // Figure out which block is immediately after the current one.
998 MachineBasicBlock *NextBlock = 0;
999 MachineFunction::iterator BBI = CurMBB;
1000 if (++BBI != CurMBB->getParent()->end())
1001 NextBlock = BBI;
1002
1003 if (I.isUnconditional()) {
1004 // If this is not a fall-through branch, emit the branch.
1005 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001006 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001007 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001008
Chris Lattner963ddad2006-10-24 17:57:59 +00001009 // Update machine-CFG edges.
1010 CurMBB->addSuccessor(Succ0MBB);
1011
1012 return;
1013 }
1014
1015 // If this condition is one of the special cases we handle, do special stuff
1016 // now.
1017 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001018 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001019
1020 // If this is a series of conditions that are or'd or and'd together, emit
1021 // this as a sequence of branches instead of setcc's with and/or operations.
1022 // For example, instead of something like:
1023 // cmp A, B
1024 // C = seteq
1025 // cmp D, E
1026 // F = setle
1027 // or C, F
1028 // jnz foo
1029 // Emit:
1030 // cmp A, B
1031 // je foo
1032 // cmp D, E
1033 // jle foo
1034 //
1035 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1036 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001037 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001038 BOp->getOpcode() == Instruction::Or)) {
1039 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001040 // If the compares in later blocks need to use values not currently
1041 // exported from this block, export them now. This block should always
1042 // be the first entry.
1043 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1044
Chris Lattner427301f2006-10-31 22:37:42 +00001045 // Allow some cases to be rejected.
1046 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001047 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1048 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1049 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1050 }
1051
1052 // Emit the branch for this block.
1053 visitSwitchCase(SwitchCases[0]);
1054 SwitchCases.erase(SwitchCases.begin());
1055 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001056 }
1057
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001058 // Okay, we decided not to do this, remove any inserted MBB's and clear
1059 // SwitchCases.
1060 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1061 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1062
Chris Lattner427301f2006-10-31 22:37:42 +00001063 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001064 }
1065 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001066
1067 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001068 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001069 Succ0MBB, Succ1MBB, CurMBB);
1070 // Use visitSwitchCase to actually insert the fast branch sequence for this
1071 // cond branch.
1072 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001073}
1074
Nate Begemaned728c12006-03-27 01:32:24 +00001075/// visitSwitchCase - Emits the necessary code to represent a single node in
1076/// the binary search tree resulting from lowering a switch instruction.
1077void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001078 SDOperand Cond;
1079 SDOperand CondLHS = getValue(CB.CmpLHS);
1080
Chris Lattnered0110b2006-10-27 21:36:01 +00001081 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1082 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001083 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001084 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001085 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001086 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1087 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1088 } else
1089 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001090
Nate Begemaned728c12006-03-27 01:32:24 +00001091 // Set NextBlock to be the MBB immediately after the current one, if any.
1092 // This is used to avoid emitting unnecessary branches to the next block.
1093 MachineBasicBlock *NextBlock = 0;
1094 MachineFunction::iterator BBI = CurMBB;
1095 if (++BBI != CurMBB->getParent()->end())
1096 NextBlock = BBI;
1097
1098 // If the lhs block is the next block, invert the condition so that we can
1099 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001100 if (CB.TrueBB == NextBlock) {
1101 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001102 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1103 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1104 }
1105 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001106 DAG.getBasicBlock(CB.TrueBB));
1107 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001108 DAG.setRoot(BrCond);
1109 else
1110 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001111 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001112 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001113 CurMBB->addSuccessor(CB.TrueBB);
1114 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001115}
1116
Anton Korobeynikov70378262007-03-25 15:07:15 +00001117/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001118void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001119 // Emit the code for the jump table
Anton Korobeynikov70378262007-03-25 15:07:15 +00001120 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001121 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001122 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1123 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1124 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1125 Table, Index));
1126 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001127}
1128
Anton Korobeynikov70378262007-03-25 15:07:15 +00001129/// visitJumpTableHeader - This function emits necessary code to produce index
1130/// in the JumpTable from switch case.
1131void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1132 SelectionDAGISel::JumpTableHeader &JTH) {
1133 // Subtract the lowest switch case value from the value being switched on
1134 // and conditional branch to default mbb if the result is greater than the
1135 // difference between smallest and largest cases.
1136 SDOperand SwitchOp = getValue(JTH.SValue);
1137 MVT::ValueType VT = SwitchOp.getValueType();
1138 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1139 DAG.getConstant(JTH.First, VT));
1140
1141 // The SDNode we just created, which holds the value being switched on
1142 // minus the the smallest case value, needs to be copied to a virtual
1143 // register so it can be used as an index into the jump table in a
1144 // subsequent basic block. This value may be smaller or larger than the
1145 // target's pointer type, and therefore require extension or truncating.
1146 if (VT > TLI.getPointerTy())
1147 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1148 else
1149 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1150
1151 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1152 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1153 JT.Reg = JumpTableReg;
1154
1155 // Emit the range check for the jump table, and branch to the default
1156 // block for the switch statement if the value being switched on exceeds
1157 // the largest case in the switch.
1158 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1159 DAG.getConstant(JTH.Last-JTH.First,VT),
1160 ISD::SETUGT);
1161
1162 // Set NextBlock to be the MBB immediately after the current one, if any.
1163 // This is used to avoid emitting unnecessary branches to the next block.
1164 MachineBasicBlock *NextBlock = 0;
1165 MachineFunction::iterator BBI = CurMBB;
1166 if (++BBI != CurMBB->getParent()->end())
1167 NextBlock = BBI;
1168
1169 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1170 DAG.getBasicBlock(JT.Default));
1171
1172 if (JT.MBB == NextBlock)
1173 DAG.setRoot(BrCond);
1174 else
1175 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1176 DAG.getBasicBlock(JT.MBB)));
1177}
1178
1179
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001180void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001181 assert(0 && "Should never be visited directly");
1182}
1183void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001184 // Retrieve successors.
1185 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1186 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1187
Jim Laskey14059d92007-02-25 21:43:59 +00001188 if (!AsTerminator) {
1189 // Mark landing pad so that it doesn't get deleted in branch folding.
1190 LandingPad->setIsLandingPad();
1191
1192 // Insert a label before the invoke call to mark the try range.
1193 // This can be used to detect deletion of the invoke via the
1194 // MachineModuleInfo.
1195 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1196 unsigned BeginLabel = MMI->NextLabelID();
1197 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1198 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001199
Jim Laskey14059d92007-02-25 21:43:59 +00001200 LowerCallTo(I, I.getCalledValue()->getType(),
1201 I.getCallingConv(),
1202 false,
1203 getValue(I.getOperand(0)),
1204 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001205
Jim Laskey14059d92007-02-25 21:43:59 +00001206 // Insert a label before the invoke call to mark the try range.
1207 // This can be used to detect deletion of the invoke via the
1208 // MachineModuleInfo.
1209 unsigned EndLabel = MMI->NextLabelID();
1210 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1211 DAG.getConstant(EndLabel, MVT::i32)));
1212
1213 // Inform MachineModuleInfo of range.
1214 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1215
1216 // Update successor info
1217 CurMBB->addSuccessor(Return);
1218 CurMBB->addSuccessor(LandingPad);
1219 } else {
1220 // Drop into normal successor.
1221 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1222 DAG.getBasicBlock(Return)));
1223 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001224}
1225
1226void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1227}
1228
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001229/// handleSmaaSwitchCaseRange - Emit a series of specific tests (suitable for
1230/// small case ranges).
1231void SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1232 CaseRecVector& WorkList,
1233 Value* SV,
1234 MachineBasicBlock* Default) {
1235 // Get the MachineFunction which holds the current MBB. This is used when
1236 // inserting any additional MBBs necessary to represent the switch.
1237 MachineFunction *CurMF = CurMBB->getParent();
1238
1239 // Figure out which block is immediately after the current one.
1240 MachineBasicBlock *NextBlock = 0;
1241 MachineFunction::iterator BBI = CR.CaseBB;
1242
1243 Case& BackCase = *(CR.Range.second-1);
1244
1245 if (++BBI != CurMBB->getParent()->end())
1246 NextBlock = BBI;
1247
1248 // TODO: If any two of the cases has the same destination, and if one value
1249 // is the same as the other, but has one bit unset that the other has set,
1250 // use bit manipulation to do two compares at once. For example:
1251 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1252
1253 // Rearrange the case blocks so that the last one falls through if possible.
1254 if (NextBlock && Default != NextBlock && BackCase.second != NextBlock) {
1255 // The last case block won't fall through into 'NextBlock' if we emit the
1256 // branches in this order. See if rearranging a case value would help.
1257 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1258 if (I->second == NextBlock) {
1259 std::swap(*I, BackCase);
1260 break;
1261 }
1262 }
1263 }
1264
1265 // Create a CaseBlock record representing a conditional branch to
1266 // the Case's target mbb if the value being switched on SV is equal
1267 // to C.
1268 MachineBasicBlock *CurBlock = CR.CaseBB;
1269 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1270 MachineBasicBlock *FallThrough;
1271 if (I != E-1) {
1272 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1273 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1274 } else {
1275 // If the last case doesn't match, go to the default block.
1276 FallThrough = Default;
1277 }
1278
1279 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, I->first,
1280 I->second, FallThrough, CurBlock);
1281
1282 // If emitting the first comparison, just call visitSwitchCase to emit the
1283 // code into the current block. Otherwise, push the CaseBlock onto the
1284 // vector to be later processed by SDISel, and insert the node's MBB
1285 // before the next MBB.
1286 if (CurBlock == CurMBB)
1287 visitSwitchCase(CB);
1288 else
1289 SwitchCases.push_back(CB);
1290
1291 CurBlock = FallThrough;
1292 }
1293}
1294
1295/// handleJTSwitchCase - Emit jumptable for current switch case range
1296void SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1297 CaseRecVector& WorkList,
1298 Value* SV,
1299 MachineBasicBlock* Default) {
1300 // Get the MachineFunction which holds the current MBB. This is used when
1301 // inserting any additional MBBs necessary to represent the switch.
1302 MachineFunction *CurMF = CurMBB->getParent();
1303
1304 // Figure out which block is immediately after the current one.
1305 MachineBasicBlock *NextBlock = 0;
1306 MachineFunction::iterator BBI = CR.CaseBB;
1307
1308 if (++BBI != CurMBB->getParent()->end())
1309 NextBlock = BBI;
1310
1311 Case& FrontCase = *CR.Range.first;
1312 Case& BackCase = *(CR.Range.second-1);
1313 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1314
1315 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1316 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1317
1318 // Create a new basic block to hold the code for loading the address
1319 // of the jump table, and jumping to it. Update successor information;
1320 // we will either branch to the default case for the switch, or the jump
1321 // table.
1322 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1323 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1324 CR.CaseBB->addSuccessor(Default);
1325 CR.CaseBB->addSuccessor(JumpTableBB);
1326
1327 // Build a vector of destination BBs, corresponding to each target
1328 // of the jump table. If the value of the jump table slot corresponds to
1329 // a case statement, push the case's BB onto the vector, otherwise, push
1330 // the default BB.
1331 std::vector<MachineBasicBlock*> DestBBs;
1332 int64_t TEI = First;
1333 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI)
1334 if (cast<ConstantInt>(I->first)->getSExtValue() == TEI) {
1335 DestBBs.push_back(I->second);
1336 ++I;
1337 } else {
1338 DestBBs.push_back(Default);
1339 }
1340
1341 // Update successor info. Add one edge to each unique successor.
1342 // Vector bool would be better, but vector<bool> is really slow.
1343 std::vector<unsigned char> SuccsHandled;
1344 SuccsHandled.resize(CR.CaseBB->getParent()->getNumBlockIDs());
1345
1346 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1347 E = DestBBs.end(); I != E; ++I) {
1348 if (!SuccsHandled[(*I)->getNumber()]) {
1349 SuccsHandled[(*I)->getNumber()] = true;
1350 JumpTableBB->addSuccessor(*I);
1351 }
1352 }
1353
1354 // Create a jump table index for this jump table, or return an existing
1355 // one.
1356 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1357
1358 // Set the jump table information so that we can codegen it as a second
1359 // MachineBasicBlock
1360 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1361 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1362 (CR.CaseBB == CurMBB));
1363 if (CR.CaseBB == CurMBB)
1364 visitJumpTableHeader(JT, JTH);
1365
1366 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1367}
1368
1369/// handleBTSmallSwitchCase - handle leaf in the binary comparison tree. Just
1370/// emit test.
1371void SelectionDAGLowering::handleBTSmallSwitchCase(CaseRec& CR,
1372 CaseRecVector& WorkList,
1373 Value* SV,
1374 MachineBasicBlock* Default) {
1375 Case& FrontCase = *CR.Range.first;
1376
1377 // Create a CaseBlock record representing a conditional branch to
1378 // the Case's target mbb if the value being switched on SV is equal
1379 // to C. Otherwise, branch to default.
1380 Constant *C = FrontCase.first;
1381 MachineBasicBlock *Target = FrontCase.second;
1382 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1383 CR.CaseBB);
1384
1385 // If the MBB representing the leaf node is the current MBB, then just
1386 // call visitSwitchCase to emit the code into the current block.
1387 // Otherwise, push the CaseBlock onto the vector to be later processed
1388 // by SDISel, and insert the node's MBB before the next MBB.
1389 if (CR.CaseBB == CurMBB)
1390 visitSwitchCase(CB);
1391 else
1392 SwitchCases.push_back(CB);
1393}
1394
1395/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1396/// 2 subtrees.
1397void SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1398 CaseRecVector& WorkList,
1399 Value* SV,
1400 MachineBasicBlock* Default) {
1401 // Get the MachineFunction which holds the current MBB. This is used when
1402 // inserting any additional MBBs necessary to represent the switch.
1403 MachineFunction *CurMF = CurMBB->getParent();
1404
1405 // Figure out which block is immediately after the current one.
1406 MachineBasicBlock *NextBlock = 0;
1407 MachineFunction::iterator BBI = CR.CaseBB;
1408
1409 if (++BBI != CurMBB->getParent()->end())
1410 NextBlock = BBI;
1411
1412 Case& FrontCase = *CR.Range.first;
1413 Case& BackCase = *(CR.Range.second-1);
1414 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1415
1416 // Size is the number of Cases represented by this range.
1417 unsigned Size = CR.Range.second - CR.Range.first;
1418
1419 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1420 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1421 double Density = 0;
1422 CaseItr Pivot;
1423
1424 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1425 // (heuristically) allow us to emit JumpTable's later.
1426 unsigned LSize = 1;
1427 unsigned RSize = Size-1;
1428 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1429 J!=E; ++I, ++J, ++LSize, --RSize) {
1430 uint64_t LEnd = cast<ConstantInt>(I->first)->getSExtValue();
1431 uint64_t RBegin = cast<ConstantInt>(J->first)->getSExtValue();
1432 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1433 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1434 if (Density < (LDensity + RDensity)) {
1435 Pivot = J;
1436 Density = LDensity + RDensity;
1437 }
1438 }
1439
1440 CaseRange LHSR(CR.Range.first, Pivot);
1441 CaseRange RHSR(Pivot, CR.Range.second);
1442 Constant *C = Pivot->first;
1443 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1444
1445 // We know that we branch to the LHS if the Value being switched on is
1446 // less than the Pivot value, C. We use this to optimize our binary
1447 // tree a bit, by recognizing that if SV is greater than or equal to the
1448 // LHS's Case Value, and that Case Value is exactly one less than the
1449 // Pivot's Value, then we can branch directly to the LHS's Target,
1450 // rather than creating a leaf node for it.
1451 if ((LHSR.second - LHSR.first) == 1 &&
1452 LHSR.first->first == CR.GE &&
1453 cast<ConstantInt>(C)->getZExtValue() ==
1454 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
1455 TrueBB = LHSR.first->second;
1456 } else {
1457 TrueBB = new MachineBasicBlock(LLVMBB);
1458 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1459 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1460 }
1461
1462 // Similar to the optimization above, if the Value being switched on is
1463 // known to be less than the Constant CR.LT, and the current Case Value
1464 // is CR.LT - 1, then we can branch directly to the target block for
1465 // the current Case Value, rather than emitting a RHS leaf node for it.
1466 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1467 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1468 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
1469 FalseBB = RHSR.first->second;
1470 } else {
1471 FalseBB = new MachineBasicBlock(LLVMBB);
1472 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1473 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1474 }
1475
1476 // Create a CaseBlock record representing a conditional branch to
1477 // the LHS node if the value being switched on SV is less than C.
1478 // Otherwise, branch to LHS.
1479 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1480 CR.CaseBB);
1481
1482 if (CR.CaseBB == CurMBB)
1483 visitSwitchCase(CB);
1484 else
1485 SwitchCases.push_back(CB);
1486}
1487
Anton Korobeynikov70378262007-03-25 15:07:15 +00001488void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
Nate Begemaned728c12006-03-27 01:32:24 +00001489 // Figure out which block is immediately after the current one.
1490 MachineBasicBlock *NextBlock = 0;
1491 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001492
Chris Lattner6d6fc262006-10-22 21:36:53 +00001493 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1494
Nate Begemaned728c12006-03-27 01:32:24 +00001495 // If there is only the default destination, branch to it if it is not the
1496 // next basic block. Otherwise, just fall through.
1497 if (I.getNumOperands() == 2) {
1498 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001499
Nate Begemaned728c12006-03-27 01:32:24 +00001500 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001501 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001502 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001503 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001504
Chris Lattner6d6fc262006-10-22 21:36:53 +00001505 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001506 return;
1507 }
1508
1509 // If there are any non-default case statements, create a vector of Cases
1510 // representing each one, and sort the vector so that we can efficiently
1511 // create a binary search tree from them.
1512 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001513
Nate Begemaned728c12006-03-27 01:32:24 +00001514 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1515 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1516 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1517 }
1518 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1519
1520 // Get the Value to be switched on and default basic blocks, which will be
1521 // inserted into CaseBlock records, representing basic blocks in the binary
1522 // search tree.
1523 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001524
Nate Begemaned728c12006-03-27 01:32:24 +00001525 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001526 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001527 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1528
1529 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001530 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001531 CaseRec CR = WorkList.back();
1532 WorkList.pop_back();
1533 Case& FrontCase = *CR.Range.first;
1534 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001535
1536 // Figure out which block is immediately after the current one.
1537 NextBlock = 0;
1538 BBI = CR.CaseBB;
1539
1540 if (++BBI != CurMBB->getParent()->end())
1541 NextBlock = BBI;
Nate Begemaned728c12006-03-27 01:32:24 +00001542
Anton Korobeynikov70378262007-03-25 15:07:15 +00001543 // Size is the number of Cases represented by this range.
Nate Begemaned728c12006-03-27 01:32:24 +00001544 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001545
1546 // If the range has few cases (two or less) emit a series of specific
1547 // tests.
1548 if (Size < 3) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001549 handleSmallSwitchRange(CR, WorkList, SV, Default);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001550 continue;
1551 }
1552
1553 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1554 // target supports indirect branches, then emit a jump table rather than
1555 // lowering the switch to a binary tree of conditional branches.
1556
1557 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1558 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1559 Size > 5) {
1560 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1561 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1562 double Density = (double)Size / (double)((Last - First) + 1ULL);
1563
1564 if (Density >= 0.3125) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001565 handleJTSwitchCase(CR, WorkList, SV, Default);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001566 continue;
1567 }
1568 }
1569
1570 // Emit binary tree. If Size is 1, then we are processing a leaf of the
1571 // binary search tree. Otherwise, we need to pick a pivot, and push left
1572 // and right ranges onto the worklist.
Anton Korobeynikov70378262007-03-25 15:07:15 +00001573
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001574 if (Size == 1)
1575 handleBTSmallSwitchCase(CR, WorkList, SV, Default);
1576 else
1577 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001578 }
1579}
1580
Anton Korobeynikov70378262007-03-25 15:07:15 +00001581
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001582void SelectionDAGLowering::visitSub(User &I) {
1583 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001584 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001585 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001586 visitVectorBinary(I, ISD::VSUB);
1587 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001588 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1589 if (CFP->isExactlyValue(-0.0)) {
1590 SDOperand Op2 = getValue(I.getOperand(1));
1591 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1592 return;
1593 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001594 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001595 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001596 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001597}
1598
Reid Spencer2eadb532007-01-21 00:29:26 +00001599void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001600 SDOperand Op1 = getValue(I.getOperand(0));
1601 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001602
1603 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001604}
1605
Reid Spencer2eadb532007-01-21 00:29:26 +00001606void
1607SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001608 assert(isa<VectorType>(I.getType()));
1609 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001610 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001611
Reid Spencer2eadb532007-01-21 00:29:26 +00001612 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1613 getValue(I.getOperand(0)),
1614 getValue(I.getOperand(1)),
1615 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1616 Typ));
1617}
1618
1619void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1620 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001621 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001622 visitVectorBinary(I, VectorOp);
1623 else
1624 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001625}
Chris Lattner96c26752005-01-19 22:31:21 +00001626
Nate Begeman127321b2005-11-18 07:42:56 +00001627void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1628 SDOperand Op1 = getValue(I.getOperand(0));
1629 SDOperand Op2 = getValue(I.getOperand(1));
1630
Reid Spencer2341c222007-02-02 02:16:23 +00001631 if (TLI.getShiftAmountTy() < Op2.getValueType())
1632 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1633 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1634 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001635
Chris Lattner7a60d912005-01-07 07:47:53 +00001636 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1637}
1638
Reid Spencerd9436b62006-11-20 01:22:35 +00001639void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001640 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1641 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1642 predicate = IC->getPredicate();
1643 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1644 predicate = ICmpInst::Predicate(IC->getPredicate());
1645 SDOperand Op1 = getValue(I.getOperand(0));
1646 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001647 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001648 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001649 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1650 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1651 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1652 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1653 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1654 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1655 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1656 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1657 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1658 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1659 default:
1660 assert(!"Invalid ICmp predicate value");
1661 Opcode = ISD::SETEQ;
1662 break;
1663 }
1664 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1665}
1666
1667void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001668 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1669 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1670 predicate = FC->getPredicate();
1671 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1672 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001673 SDOperand Op1 = getValue(I.getOperand(0));
1674 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001675 ISD::CondCode Condition, FOC, FPC;
1676 switch (predicate) {
1677 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1678 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1679 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1680 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1681 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1682 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1683 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1684 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1685 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1686 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1687 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1688 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1689 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1690 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1691 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1692 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1693 default:
1694 assert(!"Invalid FCmp predicate value");
1695 FOC = FPC = ISD::SETFALSE;
1696 break;
1697 }
1698 if (FiniteOnlyFPMath())
1699 Condition = FOC;
1700 else
1701 Condition = FPC;
1702 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001703}
1704
1705void SelectionDAGLowering::visitSelect(User &I) {
1706 SDOperand Cond = getValue(I.getOperand(0));
1707 SDOperand TrueVal = getValue(I.getOperand(1));
1708 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001709 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001710 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1711 TrueVal, FalseVal));
1712 } else {
1713 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1714 *(TrueVal.Val->op_end()-2),
1715 *(TrueVal.Val->op_end()-1)));
1716 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001717}
1718
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719
1720void SelectionDAGLowering::visitTrunc(User &I) {
1721 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1722 SDOperand N = getValue(I.getOperand(0));
1723 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1724 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1725}
1726
1727void SelectionDAGLowering::visitZExt(User &I) {
1728 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1729 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1730 SDOperand N = getValue(I.getOperand(0));
1731 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1732 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1733}
1734
1735void SelectionDAGLowering::visitSExt(User &I) {
1736 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1737 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1738 SDOperand N = getValue(I.getOperand(0));
1739 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1740 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1741}
1742
1743void SelectionDAGLowering::visitFPTrunc(User &I) {
1744 // FPTrunc is never a no-op cast, no need to check
1745 SDOperand N = getValue(I.getOperand(0));
1746 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1747 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1748}
1749
1750void SelectionDAGLowering::visitFPExt(User &I){
1751 // FPTrunc is never a no-op cast, no need to check
1752 SDOperand N = getValue(I.getOperand(0));
1753 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1754 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1755}
1756
1757void SelectionDAGLowering::visitFPToUI(User &I) {
1758 // FPToUI is never a no-op cast, no need to check
1759 SDOperand N = getValue(I.getOperand(0));
1760 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1761 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1762}
1763
1764void SelectionDAGLowering::visitFPToSI(User &I) {
1765 // FPToSI is never a no-op cast, no need to check
1766 SDOperand N = getValue(I.getOperand(0));
1767 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1768 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1769}
1770
1771void SelectionDAGLowering::visitUIToFP(User &I) {
1772 // UIToFP is never a no-op cast, no need to check
1773 SDOperand N = getValue(I.getOperand(0));
1774 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1775 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1776}
1777
1778void SelectionDAGLowering::visitSIToFP(User &I){
1779 // UIToFP is never a no-op cast, no need to check
1780 SDOperand N = getValue(I.getOperand(0));
1781 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1782 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1783}
1784
1785void SelectionDAGLowering::visitPtrToInt(User &I) {
1786 // What to do depends on the size of the integer and the size of the pointer.
1787 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001788 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001789 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001790 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001791 SDOperand Result;
1792 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1793 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1794 else
1795 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1796 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1797 setValue(&I, Result);
1798}
Chris Lattner7a60d912005-01-07 07:47:53 +00001799
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001800void SelectionDAGLowering::visitIntToPtr(User &I) {
1801 // What to do depends on the size of the integer and the size of the pointer.
1802 // We can either truncate, zero extend, or no-op, accordingly.
1803 SDOperand N = getValue(I.getOperand(0));
1804 MVT::ValueType SrcVT = N.getValueType();
1805 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1806 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1807 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1808 else
1809 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1810 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1811}
1812
1813void SelectionDAGLowering::visitBitCast(User &I) {
1814 SDOperand N = getValue(I.getOperand(0));
1815 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001816 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001817 // This is a cast to a vector from something else.
1818 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001819 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001820 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1821 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1822 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1823 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001824 return;
1825 }
1826 MVT::ValueType SrcVT = N.getValueType();
1827 if (SrcVT == MVT::Vector) {
1828 // This is a cast from a vctor to something else.
1829 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001830 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001831 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001832 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001833
1834 // BitCast assures us that source and destination are the same size so this
1835 // is either a BIT_CONVERT or a no-op.
1836 if (DestVT != N.getValueType())
1837 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1838 else
1839 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001840}
1841
Chris Lattner67271862006-03-29 00:11:43 +00001842void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001843 SDOperand InVec = getValue(I.getOperand(0));
1844 SDOperand InVal = getValue(I.getOperand(1));
1845 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1846 getValue(I.getOperand(2)));
1847
Chris Lattner29b23012006-03-19 01:17:20 +00001848 SDOperand Num = *(InVec.Val->op_end()-2);
1849 SDOperand Typ = *(InVec.Val->op_end()-1);
1850 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1851 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001852}
1853
Chris Lattner67271862006-03-29 00:11:43 +00001854void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001855 SDOperand InVec = getValue(I.getOperand(0));
1856 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1857 getValue(I.getOperand(1)));
1858 SDOperand Typ = *(InVec.Val->op_end()-1);
1859 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1860 TLI.getValueType(I.getType()), InVec, InIdx));
1861}
Chris Lattner32206f52006-03-18 01:44:44 +00001862
Chris Lattner098c01e2006-04-08 04:15:24 +00001863void SelectionDAGLowering::visitShuffleVector(User &I) {
1864 SDOperand V1 = getValue(I.getOperand(0));
1865 SDOperand V2 = getValue(I.getOperand(1));
1866 SDOperand Mask = getValue(I.getOperand(2));
1867
1868 SDOperand Num = *(V1.Val->op_end()-2);
1869 SDOperand Typ = *(V2.Val->op_end()-1);
1870 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1871 V1, V2, Mask, Num, Typ));
1872}
1873
1874
Chris Lattner7a60d912005-01-07 07:47:53 +00001875void SelectionDAGLowering::visitGetElementPtr(User &I) {
1876 SDOperand N = getValue(I.getOperand(0));
1877 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001878
1879 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1880 OI != E; ++OI) {
1881 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001882 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001883 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001884 if (Field) {
1885 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001886 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001887 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001888 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001889 }
1890 Ty = StTy->getElementType(Field);
1891 } else {
1892 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001893
Chris Lattner43535a12005-11-09 04:45:33 +00001894 // If this is a constant subscript, handle it quickly.
1895 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001896 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001897 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001898 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001899 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1900 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001901 }
Chris Lattner43535a12005-11-09 04:45:33 +00001902
1903 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001904 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001905 SDOperand IdxN = getValue(Idx);
1906
1907 // If the index is smaller or larger than intptr_t, truncate or extend
1908 // it.
1909 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001910 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001911 } else if (IdxN.getValueType() > N.getValueType())
1912 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1913
1914 // If this is a multiply by a power of two, turn it into a shl
1915 // immediately. This is a very common case.
1916 if (isPowerOf2_64(ElementSize)) {
1917 unsigned Amt = Log2_64(ElementSize);
1918 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001919 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001920 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1921 continue;
1922 }
1923
1924 SDOperand Scale = getIntPtrConstant(ElementSize);
1925 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1926 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001927 }
1928 }
1929 setValue(&I, N);
1930}
1931
1932void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1933 // If this is a fixed sized alloca in the entry block of the function,
1934 // allocate it statically on the stack.
1935 if (FuncInfo.StaticAllocaMap.count(&I))
1936 return; // getValue will auto-populate this.
1937
1938 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001939 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001940 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00001941 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00001942 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001943
1944 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001945 MVT::ValueType IntPtr = TLI.getPointerTy();
1946 if (IntPtr < AllocSize.getValueType())
1947 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1948 else if (IntPtr > AllocSize.getValueType())
1949 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001950
Chris Lattnereccb73d2005-01-22 23:04:37 +00001951 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001952 getIntPtrConstant(TySize));
1953
1954 // Handle alignment. If the requested alignment is less than or equal to the
1955 // stack alignment, ignore it and round the size of the allocation up to the
1956 // stack alignment size. If the size is greater than the stack alignment, we
1957 // note this in the DYNAMIC_STACKALLOC node.
1958 unsigned StackAlign =
1959 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1960 if (Align <= StackAlign) {
1961 Align = 0;
1962 // Add SA-1 to the size.
1963 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1964 getIntPtrConstant(StackAlign-1));
1965 // Mask out the low bits for alignment purposes.
1966 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1967 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1968 }
1969
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001970 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001971 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1972 MVT::Other);
1973 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00001974 setValue(&I, DSA);
1975 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001976
1977 // Inform the Frame Information that we have just allocated a variable-sized
1978 // object.
1979 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1980}
1981
Chris Lattner7a60d912005-01-07 07:47:53 +00001982void SelectionDAGLowering::visitLoad(LoadInst &I) {
1983 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001984
Chris Lattner4d9651c2005-01-17 22:19:26 +00001985 SDOperand Root;
1986 if (I.isVolatile())
1987 Root = getRoot();
1988 else {
1989 // Do not serialize non-volatile loads against each other.
1990 Root = DAG.getRoot();
1991 }
Chris Lattner4024c002006-03-15 22:19:46 +00001992
Evan Chenge71fe34d2006-10-09 20:57:25 +00001993 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001994 Root, I.isVolatile()));
1995}
1996
1997SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001998 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001999 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002000 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002001 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002002 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002003 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2004 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002005 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00002006 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002007 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002008
Chris Lattner4024c002006-03-15 22:19:46 +00002009 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002010 DAG.setRoot(L.getValue(1));
2011 else
2012 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002013
2014 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002015}
2016
2017
2018void SelectionDAGLowering::visitStore(StoreInst &I) {
2019 Value *SrcV = I.getOperand(0);
2020 SDOperand Src = getValue(SrcV);
2021 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002022 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00002023 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002024}
2025
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002026/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2027/// access memory and has no other side effects at all.
2028static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2029#define GET_NO_MEMORY_INTRINSICS
2030#include "llvm/Intrinsics.gen"
2031#undef GET_NO_MEMORY_INTRINSICS
2032 return false;
2033}
2034
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002035// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2036// have any side-effects or if it only reads memory.
2037static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2038#define GET_SIDE_EFFECT_INFO
2039#include "llvm/Intrinsics.gen"
2040#undef GET_SIDE_EFFECT_INFO
2041 return false;
2042}
2043
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002044/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2045/// node.
2046void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2047 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002048 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002049 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002050
2051 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002052 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002053 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2054 if (OnlyLoad) {
2055 // We don't need to serialize loads against other loads.
2056 Ops.push_back(DAG.getRoot());
2057 } else {
2058 Ops.push_back(getRoot());
2059 }
2060 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002061
2062 // Add the intrinsic ID as an integer operand.
2063 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2064
2065 // Add all operands of the call to the operand list.
2066 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2067 SDOperand Op = getValue(I.getOperand(i));
2068
Reid Spencer09575ba2007-02-15 03:39:18 +00002069 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002070 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002071 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002072 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2073
2074 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2075 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2076 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2077 }
2078
2079 assert(TLI.isTypeLegal(Op.getValueType()) &&
2080 "Intrinsic uses a non-legal type?");
2081 Ops.push_back(Op);
2082 }
2083
2084 std::vector<MVT::ValueType> VTs;
2085 if (I.getType() != Type::VoidTy) {
2086 MVT::ValueType VT = TLI.getValueType(I.getType());
2087 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002088 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002089 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2090
2091 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2092 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2093 }
2094
2095 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2096 VTs.push_back(VT);
2097 }
2098 if (HasChain)
2099 VTs.push_back(MVT::Other);
2100
Chris Lattnerbd887772006-08-14 23:53:35 +00002101 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2102
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002103 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002104 SDOperand Result;
2105 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002106 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2107 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002108 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002109 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2110 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002111 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002112 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2113 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002114
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002115 if (HasChain) {
2116 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2117 if (OnlyLoad)
2118 PendingLoads.push_back(Chain);
2119 else
2120 DAG.setRoot(Chain);
2121 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002122 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002123 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002124 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2125 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2126 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2127 DAG.getValueType(EVT));
2128 }
2129 setValue(&I, Result);
2130 }
2131}
2132
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002133/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2134/// we want to emit this as a call to a named external function, return the name
2135/// otherwise lower it and return null.
2136const char *
2137SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2138 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002139 default:
2140 // By default, turn this into a target intrinsic node.
2141 visitTargetIntrinsic(I, Intrinsic);
2142 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002143 case Intrinsic::vastart: visitVAStart(I); return 0;
2144 case Intrinsic::vaend: visitVAEnd(I); return 0;
2145 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002146 case Intrinsic::returnaddress:
2147 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2148 getValue(I.getOperand(1))));
2149 return 0;
2150 case Intrinsic::frameaddress:
2151 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2152 getValue(I.getOperand(1))));
2153 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002154 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002155 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002156 break;
2157 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002158 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002159 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002160 case Intrinsic::memcpy_i32:
2161 case Intrinsic::memcpy_i64:
2162 visitMemIntrinsic(I, ISD::MEMCPY);
2163 return 0;
2164 case Intrinsic::memset_i32:
2165 case Intrinsic::memset_i64:
2166 visitMemIntrinsic(I, ISD::MEMSET);
2167 return 0;
2168 case Intrinsic::memmove_i32:
2169 case Intrinsic::memmove_i64:
2170 visitMemIntrinsic(I, ISD::MEMMOVE);
2171 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002172
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002173 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002174 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002175 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002176 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002177 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002178
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002179 Ops[0] = getRoot();
2180 Ops[1] = getValue(SPI.getLineValue());
2181 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002182
Jim Laskeyc56315c2007-01-26 21:22:28 +00002183 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002184 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002185 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2186
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002187 Ops[3] = DAG.getString(CompileUnit->getFileName());
2188 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002189
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002190 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002191 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002192
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002193 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002194 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002195 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002196 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002197 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002198 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2199 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002200 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002201 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002202 }
2203
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002204 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002205 }
2206 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002207 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002208 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002209 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2210 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002211 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002212 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002213 }
2214
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002215 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002216 }
2217 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002218 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002219 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002220 if (MMI && FSI.getSubprogram() &&
2221 MMI->Verify(FSI.getSubprogram())) {
2222 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002223 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002224 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002225 }
2226
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002227 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002228 }
2229 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002230 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002231 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002232 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002233 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002234 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002235 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002236 }
2237
2238 return 0;
2239 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002240
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002241 case Intrinsic::eh_exception: {
2242 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2243
Jim Laskey504e9942007-02-22 15:38:06 +00002244 if (MMI) {
2245 // Add a label to mark the beginning of the landing pad. Deletion of the
2246 // landing pad can thus be detected via the MachineModuleInfo.
2247 unsigned LabelID = MMI->addLandingPad(CurMBB);
2248 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2249 DAG.getConstant(LabelID, MVT::i32)));
2250
2251 // Mark exception register as live in.
2252 unsigned Reg = TLI.getExceptionAddressRegister();
2253 if (Reg) CurMBB->addLiveIn(Reg);
2254
2255 // Insert the EXCEPTIONADDR instruction.
2256 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2257 SDOperand Ops[1];
2258 Ops[0] = DAG.getRoot();
2259 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2260 setValue(&I, Op);
2261 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002262 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002263 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002264 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002265 return 0;
2266 }
2267
Jim Laskeyd5453d72007-03-01 20:24:30 +00002268 case Intrinsic::eh_selector:
2269 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002270 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2271
Jim Laskey504e9942007-02-22 15:38:06 +00002272 if (MMI) {
2273 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002274 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2275 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2276 isa<Function>(CE->getOperand(0)) &&
2277 "Personality should be a function");
2278 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002279 if (Intrinsic == Intrinsic::eh_filter)
2280 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002281
Jim Laskey504e9942007-02-22 15:38:06 +00002282 // Gather all the type infos for this landing pad and pass them along to
2283 // MachineModuleInfo.
2284 std::vector<GlobalVariable *> TyInfo;
2285 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002286 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2287 if (CE && CE->getOpcode() == Instruction::BitCast &&
2288 isa<GlobalVariable>(CE->getOperand(0))) {
2289 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2290 } else {
2291 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2292 assert(CI && CI->getZExtValue() == 0 &&
2293 "TypeInfo must be a global variable typeinfo or NULL");
2294 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002295 }
Jim Laskey504e9942007-02-22 15:38:06 +00002296 }
2297 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2298
2299 // Mark exception selector register as live in.
2300 unsigned Reg = TLI.getExceptionSelectorRegister();
2301 if (Reg) CurMBB->addLiveIn(Reg);
2302
2303 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002304 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002305 SDOperand Ops[2];
2306 Ops[0] = getValue(I.getOperand(1));
2307 Ops[1] = getRoot();
2308 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2309 setValue(&I, Op);
2310 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002311 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002312 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002313 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002314
2315 return 0;
2316 }
2317
2318 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002319 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002320
Jim Laskey504e9942007-02-22 15:38:06 +00002321 if (MMI) {
2322 // Find the type id for the given typeinfo.
2323 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002324 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2325 if (CE && CE->getOpcode() == Instruction::BitCast &&
2326 isa<GlobalVariable>(CE->getOperand(0))) {
2327 GV = cast<GlobalVariable>(CE->getOperand(0));
2328 } else {
2329 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2330 assert(CI && CI->getZExtValue() == 0 &&
2331 "TypeInfo must be a global variable typeinfo or NULL");
2332 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002333 }
2334
2335 unsigned TypeID = MMI->getTypeIDFor(GV);
2336 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002337 } else {
2338 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002339 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002340
2341 return 0;
2342 }
2343
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002344 case Intrinsic::sqrt_f32:
2345 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002346 setValue(&I, DAG.getNode(ISD::FSQRT,
2347 getValue(I.getOperand(1)).getValueType(),
2348 getValue(I.getOperand(1))));
2349 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002350 case Intrinsic::powi_f32:
2351 case Intrinsic::powi_f64:
2352 setValue(&I, DAG.getNode(ISD::FPOWI,
2353 getValue(I.getOperand(1)).getValueType(),
2354 getValue(I.getOperand(1)),
2355 getValue(I.getOperand(2))));
2356 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002357 case Intrinsic::pcmarker: {
2358 SDOperand Tmp = getValue(I.getOperand(1));
2359 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2360 return 0;
2361 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002362 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002363 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002364 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2365 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2366 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002367 setValue(&I, Tmp);
2368 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002369 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002370 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002371 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002372 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002373 case Intrinsic::bswap_i64:
2374 setValue(&I, DAG.getNode(ISD::BSWAP,
2375 getValue(I.getOperand(1)).getValueType(),
2376 getValue(I.getOperand(1))));
2377 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002378 case Intrinsic::cttz_i8:
2379 case Intrinsic::cttz_i16:
2380 case Intrinsic::cttz_i32:
2381 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002382 setValue(&I, DAG.getNode(ISD::CTTZ,
2383 getValue(I.getOperand(1)).getValueType(),
2384 getValue(I.getOperand(1))));
2385 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002386 case Intrinsic::ctlz_i8:
2387 case Intrinsic::ctlz_i16:
2388 case Intrinsic::ctlz_i32:
2389 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002390 setValue(&I, DAG.getNode(ISD::CTLZ,
2391 getValue(I.getOperand(1)).getValueType(),
2392 getValue(I.getOperand(1))));
2393 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002394 case Intrinsic::ctpop_i8:
2395 case Intrinsic::ctpop_i16:
2396 case Intrinsic::ctpop_i32:
2397 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002398 setValue(&I, DAG.getNode(ISD::CTPOP,
2399 getValue(I.getOperand(1)).getValueType(),
2400 getValue(I.getOperand(1))));
2401 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002402 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002403 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002404 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2405 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002406 setValue(&I, Tmp);
2407 DAG.setRoot(Tmp.getValue(1));
2408 return 0;
2409 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002410 case Intrinsic::stackrestore: {
2411 SDOperand Tmp = getValue(I.getOperand(1));
2412 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002413 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002414 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002415 case Intrinsic::prefetch:
2416 // FIXME: Currently discarding prefetches.
2417 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002418 }
2419}
2420
2421
Jim Laskey31fef782007-02-23 21:45:01 +00002422void SelectionDAGLowering::LowerCallTo(Instruction &I,
2423 const Type *CalledValueTy,
2424 unsigned CallingConv,
2425 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002426 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002427 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002428 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2429
2430 TargetLowering::ArgListTy Args;
2431 TargetLowering::ArgListEntry Entry;
2432 Args.reserve(I.getNumOperands());
2433 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2434 Value *Arg = I.getOperand(i);
2435 SDOperand ArgNode = getValue(Arg);
2436 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00002437 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2438 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002439 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2440 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2441 Args.push_back(Entry);
2442 }
2443
2444 std::pair<SDOperand,SDOperand> Result =
2445 TLI.LowerCallTo(getRoot(), I.getType(),
2446 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002447 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002448 Callee, Args, DAG);
2449 if (I.getType() != Type::VoidTy)
2450 setValue(&I, Result.first);
2451 DAG.setRoot(Result.second);
2452}
2453
2454
Chris Lattner7a60d912005-01-07 07:47:53 +00002455void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002456 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002457 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002458 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002459 if (unsigned IID = F->getIntrinsicID()) {
2460 RenameFn = visitIntrinsicCall(I, IID);
2461 if (!RenameFn)
2462 return;
2463 } else { // Not an LLVM intrinsic.
2464 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002465 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2466 if (I.getNumOperands() == 3 && // Basic sanity checks.
2467 I.getOperand(1)->getType()->isFloatingPoint() &&
2468 I.getType() == I.getOperand(1)->getType() &&
2469 I.getType() == I.getOperand(2)->getType()) {
2470 SDOperand LHS = getValue(I.getOperand(1));
2471 SDOperand RHS = getValue(I.getOperand(2));
2472 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2473 LHS, RHS));
2474 return;
2475 }
2476 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002477 if (I.getNumOperands() == 2 && // Basic sanity checks.
2478 I.getOperand(1)->getType()->isFloatingPoint() &&
2479 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002480 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002481 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2482 return;
2483 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002484 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002485 if (I.getNumOperands() == 2 && // Basic sanity checks.
2486 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002487 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002488 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002489 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2490 return;
2491 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002492 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002493 if (I.getNumOperands() == 2 && // Basic sanity checks.
2494 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002495 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002496 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002497 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2498 return;
2499 }
2500 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002501 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002502 } else if (isa<InlineAsm>(I.getOperand(0))) {
2503 visitInlineAsm(I);
2504 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002505 }
Misha Brukman835702a2005-04-21 22:36:52 +00002506
Chris Lattner18d2b342005-01-08 22:48:57 +00002507 SDOperand Callee;
2508 if (!RenameFn)
2509 Callee = getValue(I.getOperand(0));
2510 else
2511 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002512
Jim Laskey31fef782007-02-23 21:45:01 +00002513 LowerCallTo(I, I.getCalledValue()->getType(),
2514 I.getCallingConv(),
2515 I.isTailCall(),
2516 Callee,
2517 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002518}
2519
Jim Laskey504e9942007-02-22 15:38:06 +00002520
Chris Lattner6f87d182006-02-22 22:37:12 +00002521SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002522 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002523 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2524 Chain = Val.getValue(1);
2525 Flag = Val.getValue(2);
2526
2527 // If the result was expanded, copy from the top part.
2528 if (Regs.size() > 1) {
2529 assert(Regs.size() == 2 &&
2530 "Cannot expand to more than 2 elts yet!");
2531 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002532 Chain = Hi.getValue(1);
2533 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002534 if (DAG.getTargetLoweringInfo().isLittleEndian())
2535 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2536 else
2537 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002538 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002539
Chris Lattner705948d2006-06-08 18:22:48 +00002540 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002541 // appropriate type.
2542 if (RegVT == ValueVT)
2543 return Val;
2544
Chris Lattner77f04792007-03-25 05:00:54 +00002545 if (MVT::isVector(RegVT)) {
2546 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2547 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2548 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2549 MVT::i32),
2550 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2551 }
2552
Chris Lattner705948d2006-06-08 18:22:48 +00002553 if (MVT::isInteger(RegVT)) {
2554 if (ValueVT < RegVT)
2555 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2556 else
2557 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002558 }
Chris Lattner77f04792007-03-25 05:00:54 +00002559
2560 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2561 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002562}
2563
Chris Lattner571d9642006-02-23 19:21:04 +00002564/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2565/// specified value into the registers specified by this object. This uses
2566/// Chain/Flag as the input and updates them for the output Chain/Flag.
2567void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002568 SDOperand &Chain, SDOperand &Flag,
2569 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002570 if (Regs.size() == 1) {
2571 // If there is a single register and the types differ, this must be
2572 // a promotion.
2573 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002574 if (MVT::isVector(RegVT)) {
2575 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2576 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2577 } else if (MVT::isInteger(RegVT)) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002578 if (RegVT < ValueVT)
2579 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2580 else
2581 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2582 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002583 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2584 }
2585 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2586 Flag = Chain.getValue(1);
2587 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002588 std::vector<unsigned> R(Regs);
2589 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2590 std::reverse(R.begin(), R.end());
2591
2592 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002593 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002594 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002595 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002596 Flag = Chain.getValue(1);
2597 }
2598 }
2599}
Chris Lattner6f87d182006-02-22 22:37:12 +00002600
Chris Lattner571d9642006-02-23 19:21:04 +00002601/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2602/// operand list. This adds the code marker and includes the number of
2603/// values added into it.
2604void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002605 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002606 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2607 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2608 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2609}
Chris Lattner6f87d182006-02-22 22:37:12 +00002610
2611/// isAllocatableRegister - If the specified register is safe to allocate,
2612/// i.e. it isn't a stack pointer or some other special register, return the
2613/// register class for the register. Otherwise, return null.
2614static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002615isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2616 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002617 MVT::ValueType FoundVT = MVT::Other;
2618 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002619 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2620 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002621 MVT::ValueType ThisVT = MVT::Other;
2622
Chris Lattnerb1124f32006-02-22 23:09:03 +00002623 const TargetRegisterClass *RC = *RCI;
2624 // If none of the the value types for this register class are valid, we
2625 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002626 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2627 I != E; ++I) {
2628 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002629 // If we have already found this register in a different register class,
2630 // choose the one with the largest VT specified. For example, on
2631 // PowerPC, we favor f64 register classes over f32.
2632 if (FoundVT == MVT::Other ||
2633 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2634 ThisVT = *I;
2635 break;
2636 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002637 }
2638 }
2639
Chris Lattnerbec582f2006-04-02 00:24:45 +00002640 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002641
Chris Lattner6f87d182006-02-22 22:37:12 +00002642 // NOTE: This isn't ideal. In particular, this might allocate the
2643 // frame pointer in functions that need it (due to them not being taken
2644 // out of allocation, because a variable sized allocation hasn't been seen
2645 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002646 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2647 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002648 if (*I == Reg) {
2649 // We found a matching register class. Keep looking at others in case
2650 // we find one with larger registers that this physreg is also in.
2651 FoundRC = RC;
2652 FoundVT = ThisVT;
2653 break;
2654 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002655 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002656 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002657}
2658
2659RegsForValue SelectionDAGLowering::
2660GetRegistersForValue(const std::string &ConstrCode,
2661 MVT::ValueType VT, bool isOutReg, bool isInReg,
2662 std::set<unsigned> &OutputRegs,
2663 std::set<unsigned> &InputRegs) {
2664 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2665 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2666 std::vector<unsigned> Regs;
2667
2668 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2669 MVT::ValueType RegVT;
2670 MVT::ValueType ValueVT = VT;
2671
Chris Lattner55402d42006-11-02 01:41:49 +00002672 // If this is a constraint for a specific physical register, like {r17},
2673 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002674 if (PhysReg.first) {
2675 if (VT == MVT::Other)
2676 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002677
2678 // Get the actual register value type. This is important, because the user
2679 // may have asked for (e.g.) the AX register in i32 type. We need to
2680 // remember that AX is actually i16 to get the right extension.
2681 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002682
2683 // This is a explicit reference to a physical register.
2684 Regs.push_back(PhysReg.first);
2685
2686 // If this is an expanded reference, add the rest of the regs to Regs.
2687 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002688 TargetRegisterClass::iterator I = PhysReg.second->begin();
2689 TargetRegisterClass::iterator E = PhysReg.second->end();
2690 for (; *I != PhysReg.first; ++I)
2691 assert(I != E && "Didn't find reg!");
2692
2693 // Already added the first reg.
2694 --NumRegs; ++I;
2695 for (; NumRegs; --NumRegs, ++I) {
2696 assert(I != E && "Ran out of registers to allocate!");
2697 Regs.push_back(*I);
2698 }
2699 }
2700 return RegsForValue(Regs, RegVT, ValueVT);
2701 }
2702
Chris Lattner55402d42006-11-02 01:41:49 +00002703 // Otherwise, if this was a reference to an LLVM register class, create vregs
2704 // for this reference.
2705 std::vector<unsigned> RegClassRegs;
2706 if (PhysReg.second) {
2707 // If this is an early clobber or tied register, our regalloc doesn't know
2708 // how to maintain the constraint. If it isn't, go ahead and create vreg
2709 // and let the regalloc do the right thing.
2710 if (!isOutReg || !isInReg) {
2711 if (VT == MVT::Other)
2712 ValueVT = *PhysReg.second->vt_begin();
2713 RegVT = *PhysReg.second->vt_begin();
2714
2715 // Create the appropriate number of virtual registers.
2716 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2717 for (; NumRegs; --NumRegs)
2718 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2719
2720 return RegsForValue(Regs, RegVT, ValueVT);
2721 }
2722
2723 // Otherwise, we can't allocate it. Let the code below figure out how to
2724 // maintain these constraints.
2725 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2726
2727 } else {
2728 // This is a reference to a register class that doesn't directly correspond
2729 // to an LLVM register class. Allocate NumRegs consecutive, available,
2730 // registers from the class.
2731 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2732 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002733
2734 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2735 MachineFunction &MF = *CurMBB->getParent();
2736 unsigned NumAllocated = 0;
2737 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2738 unsigned Reg = RegClassRegs[i];
2739 // See if this register is available.
2740 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2741 (isInReg && InputRegs.count(Reg))) { // Already used.
2742 // Make sure we find consecutive registers.
2743 NumAllocated = 0;
2744 continue;
2745 }
2746
2747 // Check to see if this register is allocatable (i.e. don't give out the
2748 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002749 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002750 if (!RC) {
2751 // Make sure we find consecutive registers.
2752 NumAllocated = 0;
2753 continue;
2754 }
2755
2756 // Okay, this register is good, we can use it.
2757 ++NumAllocated;
2758
2759 // If we allocated enough consecutive
2760 if (NumAllocated == NumRegs) {
2761 unsigned RegStart = (i-NumAllocated)+1;
2762 unsigned RegEnd = i+1;
2763 // Mark all of the allocated registers used.
2764 for (unsigned i = RegStart; i != RegEnd; ++i) {
2765 unsigned Reg = RegClassRegs[i];
2766 Regs.push_back(Reg);
2767 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2768 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2769 }
2770
2771 return RegsForValue(Regs, *RC->vt_begin(), VT);
2772 }
2773 }
2774
2775 // Otherwise, we couldn't allocate enough registers for this.
2776 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002777}
2778
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002779/// getConstraintGenerality - Return an integer indicating how general CT is.
2780static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2781 switch (CT) {
2782 default: assert(0 && "Unknown constraint type!");
2783 case TargetLowering::C_Other:
2784 case TargetLowering::C_Unknown:
2785 return 0;
2786 case TargetLowering::C_Register:
2787 return 1;
2788 case TargetLowering::C_RegisterClass:
2789 return 2;
2790 case TargetLowering::C_Memory:
2791 return 3;
2792 }
2793}
2794
2795static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2796 const TargetLowering &TLI) {
2797 assert(!C.empty() && "Must have at least one constraint");
2798 if (C.size() == 1) return C[0];
2799
2800 std::string *Current = &C[0];
2801 // If we have multiple constraints, try to pick the most general one ahead
2802 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00002803 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002804 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002805 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002806 if (getConstraintGenerality(ThisFlavor) >
2807 getConstraintGenerality(Flavor)) {
2808 // This constraint letter is more general than the previous one,
2809 // use it.
2810 Flavor = ThisFlavor;
2811 Current = &C[j];
2812 }
2813 }
2814 return *Current;
2815}
2816
Chris Lattner6f87d182006-02-22 22:37:12 +00002817
Chris Lattner476e67b2006-01-26 22:24:51 +00002818/// visitInlineAsm - Handle a call to an InlineAsm object.
2819///
2820void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2821 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2822
2823 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2824 MVT::Other);
2825
Chris Lattner3a5ed552006-02-01 01:28:23 +00002826 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002827 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002828
2829 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2830 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2831 /// if it is a def of that register.
2832 std::vector<SDOperand> AsmNodeOperands;
2833 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2834 AsmNodeOperands.push_back(AsmStr);
2835
2836 SDOperand Chain = getRoot();
2837 SDOperand Flag;
2838
Chris Lattner1558fc62006-02-01 18:59:47 +00002839 // We fully assign registers here at isel time. This is not optimal, but
2840 // should work. For register classes that correspond to LLVM classes, we
2841 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2842 // over the constraints, collecting fixed registers that we know we can't use.
2843 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002844 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002845 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002846 std::string ConstraintCode =
2847 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002848
Chris Lattner7ad77df2006-02-22 00:56:39 +00002849 MVT::ValueType OpVT;
2850
2851 // Compute the value type for each operand and add it to ConstraintVTs.
2852 switch (Constraints[i].Type) {
2853 case InlineAsm::isOutput:
2854 if (!Constraints[i].isIndirectOutput) {
2855 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2856 OpVT = TLI.getValueType(I.getType());
2857 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002858 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002859 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2860 OpNum++; // Consumes a call operand.
2861 }
2862 break;
2863 case InlineAsm::isInput:
2864 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2865 OpNum++; // Consumes a call operand.
2866 break;
2867 case InlineAsm::isClobber:
2868 OpVT = MVT::Other;
2869 break;
2870 }
2871
2872 ConstraintVTs.push_back(OpVT);
2873
Chris Lattner6f87d182006-02-22 22:37:12 +00002874 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2875 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002876
Chris Lattner6f87d182006-02-22 22:37:12 +00002877 // Build a list of regs that this operand uses. This always has a single
2878 // element for promoted/expanded operands.
2879 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2880 false, false,
2881 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002882
2883 switch (Constraints[i].Type) {
2884 case InlineAsm::isOutput:
2885 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002886 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002887 // If this is an early-clobber output, it cannot be assigned to the same
2888 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002889 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002890 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002891 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002892 case InlineAsm::isInput:
2893 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002894 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002895 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002896 case InlineAsm::isClobber:
2897 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002898 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2899 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002900 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002901 }
2902 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002903
Chris Lattner5c79f982006-02-21 23:12:12 +00002904 // Loop over all of the inputs, copying the operand values into the
2905 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002906 RegsForValue RetValRegs;
2907 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002908 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002909
Chris Lattner2e56e892006-01-31 02:03:41 +00002910 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002911 std::string ConstraintCode =
2912 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002913
Chris Lattner3a5ed552006-02-01 01:28:23 +00002914 switch (Constraints[i].Type) {
2915 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002916 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2917 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002918 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00002919
2920 if (CTy == TargetLowering::C_Memory) {
2921 // Memory output.
2922 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2923
2924 // Check that the operand (the address to store to) isn't a float.
2925 if (!MVT::isInteger(InOperandVal.getValueType()))
2926 assert(0 && "MATCH FAIL!");
2927
2928 if (!Constraints[i].isIndirectOutput)
2929 assert(0 && "MATCH FAIL!");
2930
2931 OpNum++; // Consumes a call operand.
2932
2933 // Extend/truncate to the right pointer type if needed.
2934 MVT::ValueType PtrType = TLI.getPointerTy();
2935 if (InOperandVal.getValueType() < PtrType)
2936 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2937 else if (InOperandVal.getValueType() > PtrType)
2938 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2939
2940 // Add information to the INLINEASM node to know about this output.
2941 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2942 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2943 AsmNodeOperands.push_back(InOperandVal);
2944 break;
2945 }
2946
2947 // Otherwise, this is a register output.
2948 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2949
Chris Lattner6f87d182006-02-22 22:37:12 +00002950 // If this is an early-clobber output, or if there is an input
2951 // constraint that matches this, we need to reserve the input register
2952 // so no other inputs allocate to it.
2953 bool UsesInputRegister = false;
2954 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2955 UsesInputRegister = true;
2956
2957 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002958 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002959 RegsForValue Regs =
2960 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2961 true, UsesInputRegister,
2962 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002963 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002964 cerr << "Couldn't allocate output reg for contraint '"
2965 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002966 exit(1);
2967 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002968
Chris Lattner3a5ed552006-02-01 01:28:23 +00002969 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002970 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002971 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002972 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002973 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002974 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002975 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2976 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002977 OpNum++; // Consumes a call operand.
2978 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002979
2980 // Add information to the INLINEASM node to know that this register is
2981 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002982 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002983 break;
2984 }
2985 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002986 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002987 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002988
Chris Lattner7f5880b2006-02-02 00:25:23 +00002989 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2990 // If this is required to match an output register we have already set,
2991 // just use its register.
2992 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002993
Chris Lattner571d9642006-02-23 19:21:04 +00002994 // Scan until we find the definition we already emitted of this operand.
2995 // When we find it, create a RegsForValue operand.
2996 unsigned CurOp = 2; // The first operand.
2997 for (; OperandNo; --OperandNo) {
2998 // Advance to the next operand.
2999 unsigned NumOps =
3000 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003001 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3002 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003003 "Skipped past definitions?");
3004 CurOp += (NumOps>>3)+1;
3005 }
3006
3007 unsigned NumOps =
3008 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003009 if ((NumOps & 7) == 2 /*REGDEF*/) {
3010 // Add NumOps>>3 registers to MatchedRegs.
3011 RegsForValue MatchedRegs;
3012 MatchedRegs.ValueVT = InOperandVal.getValueType();
3013 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3014 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3015 unsigned Reg =
3016 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3017 MatchedRegs.Regs.push_back(Reg);
3018 }
Chris Lattner571d9642006-02-23 19:21:04 +00003019
Chris Lattnere3eeb242007-02-01 01:21:12 +00003020 // Use the produced MatchedRegs object to
3021 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3022 TLI.getPointerTy());
3023 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3024 break;
3025 } else {
3026 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3027 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003028 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003029 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003030
3031 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3032 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00003033 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00003034
3035 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00003036 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3037 ConstraintCode[0], DAG);
3038 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003039 cerr << "Invalid operand for inline asm constraint '"
3040 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003041 exit(1);
3042 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003043
3044 // Add information to the INLINEASM node to know about this input.
3045 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3046 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3047 AsmNodeOperands.push_back(InOperandVal);
3048 break;
3049 } else if (CTy == TargetLowering::C_Memory) {
3050 // Memory input.
3051
Chris Lattnerce8aba02007-03-08 22:29:47 +00003052 // If the operand is a float, spill to a constant pool entry to get its
3053 // address.
3054 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3055 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3056
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003057 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00003058 cerr << "Match failed, cannot handle this yet!\n";
3059 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003060 exit(1);
3061 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003062
3063 // Extend/truncate to the right pointer type if needed.
3064 MVT::ValueType PtrType = TLI.getPointerTy();
3065 if (InOperandVal.getValueType() < PtrType)
3066 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3067 else if (InOperandVal.getValueType() > PtrType)
3068 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3069
3070 // Add information to the INLINEASM node to know about this input.
3071 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3072 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3073 AsmNodeOperands.push_back(InOperandVal);
3074 break;
3075 }
3076
3077 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3078
3079 // Copy the input into the appropriate registers.
3080 RegsForValue InRegs =
3081 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3082 false, true, OutputRegs, InputRegs);
3083 // FIXME: should be match fail.
3084 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3085
Evan Chengef9e07d2006-06-15 08:11:54 +00003086 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003087
3088 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003089 break;
3090 }
Chris Lattner571d9642006-02-23 19:21:04 +00003091 case InlineAsm::isClobber: {
3092 RegsForValue ClobberedRegs =
3093 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3094 OutputRegs, InputRegs);
3095 // Add the clobbered value to the operand list, so that the register
3096 // allocator is aware that the physreg got clobbered.
3097 if (!ClobberedRegs.Regs.empty())
3098 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003099 break;
3100 }
Chris Lattner571d9642006-02-23 19:21:04 +00003101 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003102 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003103
3104 // Finish up input operands.
3105 AsmNodeOperands[0] = Chain;
3106 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3107
Chris Lattnerbd887772006-08-14 23:53:35 +00003108 Chain = DAG.getNode(ISD::INLINEASM,
3109 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003110 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003111 Flag = Chain.getValue(1);
3112
Chris Lattner2e56e892006-01-31 02:03:41 +00003113 // If this asm returns a register value, copy the result from that register
3114 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003115 if (!RetValRegs.Regs.empty())
3116 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00003117
Chris Lattner2e56e892006-01-31 02:03:41 +00003118 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3119
3120 // Process indirect outputs, first output all of the flagged copies out of
3121 // physregs.
3122 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003123 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003124 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003125 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3126 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003127 }
3128
3129 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003130 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003131 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00003132 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003133 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003134 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003135 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003136 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3137 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003138 DAG.setRoot(Chain);
3139}
3140
3141
Chris Lattner7a60d912005-01-07 07:47:53 +00003142void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3143 SDOperand Src = getValue(I.getOperand(0));
3144
3145 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003146
3147 if (IntPtr < Src.getValueType())
3148 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3149 else if (IntPtr > Src.getValueType())
3150 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003151
3152 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003153 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003154 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3155 Src, getIntPtrConstant(ElementSize));
3156
Reid Spencere63b6512006-12-31 05:55:36 +00003157 TargetLowering::ArgListTy Args;
3158 TargetLowering::ArgListEntry Entry;
3159 Entry.Node = Src;
3160 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003161 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003162
3163 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003164 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003165 DAG.getExternalSymbol("malloc", IntPtr),
3166 Args, DAG);
3167 setValue(&I, Result.first); // Pointers always fit in registers
3168 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003169}
3170
3171void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003172 TargetLowering::ArgListTy Args;
3173 TargetLowering::ArgListEntry Entry;
3174 Entry.Node = getValue(I.getOperand(0));
3175 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003176 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003177 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003178 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003179 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003180 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3181 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003182}
3183
Chris Lattner13d7c252005-08-26 20:54:47 +00003184// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3185// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3186// instructions are special in various ways, which require special support to
3187// insert. The specified MachineInstr is created but not inserted into any
3188// basic blocks, and the scheduler passes ownership of it to this method.
3189MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3190 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003191 cerr << "If a target marks an instruction with "
3192 << "'usesCustomDAGSchedInserter', it must implement "
3193 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003194 abort();
3195 return 0;
3196}
3197
Chris Lattner58cfd792005-01-09 00:00:49 +00003198void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003199 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3200 getValue(I.getOperand(1)),
3201 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003202}
3203
3204void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003205 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3206 getValue(I.getOperand(0)),
3207 DAG.getSrcValue(I.getOperand(0)));
3208 setValue(&I, V);
3209 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003210}
3211
3212void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003213 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3214 getValue(I.getOperand(1)),
3215 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003216}
3217
3218void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003219 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3220 getValue(I.getOperand(1)),
3221 getValue(I.getOperand(2)),
3222 DAG.getSrcValue(I.getOperand(1)),
3223 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003224}
3225
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003226/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3227/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3228static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3229 unsigned &i, SelectionDAG &DAG,
3230 TargetLowering &TLI) {
3231 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3232 return SDOperand(Arg, i++);
3233
3234 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3235 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3236 if (NumVals == 1) {
3237 return DAG.getNode(ISD::BIT_CONVERT, VT,
3238 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3239 } else if (NumVals == 2) {
3240 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3241 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3242 if (!TLI.isLittleEndian())
3243 std::swap(Lo, Hi);
3244 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3245 } else {
3246 // Value scalarized into many values. Unimp for now.
3247 assert(0 && "Cannot expand i64 -> i16 yet!");
3248 }
3249 return SDOperand();
3250}
3251
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003252/// TargetLowering::LowerArguments - This is the default LowerArguments
3253/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003254/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3255/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003256std::vector<SDOperand>
3257TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003258 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003259 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3260 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003261 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003262 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3263 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3264
3265 // Add one result value for each formal argument.
3266 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003267 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003268 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3269 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003270 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003271 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003272 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003273 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003274
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003275 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3276 // that is zero extended!
3277 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003278 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003279 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003280 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003281 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003282 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003283 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003284 Flags |= ISD::ParamFlags::StructReturn;
3285 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003286
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003287 switch (getTypeAction(VT)) {
3288 default: assert(0 && "Unknown type action!");
3289 case Legal:
3290 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003291 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003292 break;
3293 case Promote:
3294 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003295 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003296 break;
3297 case Expand:
3298 if (VT != MVT::Vector) {
3299 // If this is a large integer, it needs to be broken up into small
3300 // integers. Figure out what the destination type is and how many small
3301 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003302 MVT::ValueType NVT = getTypeToExpandTo(VT);
3303 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003304 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003305 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003306 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003307 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003308 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3309 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003310 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3311 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003312 } else {
3313 // Otherwise, this is a vector type. We only support legal vectors
3314 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003315 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3316 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003317
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003318 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003319 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003320 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3321 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3322 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003323 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003324 } else {
3325 assert(0 && "Don't support illegal by-val vector arguments yet!");
3326 }
3327 }
3328 break;
3329 }
3330 }
Evan Cheng9618df12006-04-25 23:03:35 +00003331
Chris Lattner3d826992006-05-16 06:45:34 +00003332 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003333
3334 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003335 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3336 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003337 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003338
3339 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003340
3341 // Set up the return result vector.
3342 Ops.clear();
3343 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003344 unsigned Idx = 1;
3345 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3346 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003347 MVT::ValueType VT = getValueType(I->getType());
3348
3349 switch (getTypeAction(VT)) {
3350 default: assert(0 && "Unknown type action!");
3351 case Legal:
3352 Ops.push_back(SDOperand(Result, i++));
3353 break;
3354 case Promote: {
3355 SDOperand Op(Result, i++);
3356 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00003357 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3358 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3359 DAG.getValueType(VT));
3360 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3361 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3362 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003363 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3364 } else {
3365 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3366 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3367 }
3368 Ops.push_back(Op);
3369 break;
3370 }
3371 case Expand:
3372 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003373 // If this is a large integer or a floating point node that needs to be
3374 // expanded, it needs to be reassembled from small integers. Figure out
3375 // what the source elt type is and how many small integers it is.
3376 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003377 } else {
3378 // Otherwise, this is a vector type. We only support legal vectors
3379 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003380 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003381 unsigned NumElems = PTy->getNumElements();
3382 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003383
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003384 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003385 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003386 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003387 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003388 SDOperand N = SDOperand(Result, i++);
3389 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003390 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3391 DAG.getConstant(NumElems, MVT::i32),
3392 DAG.getValueType(getValueType(EltTy)));
3393 Ops.push_back(N);
3394 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003395 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003396 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003397 }
3398 }
3399 break;
3400 }
3401 }
3402 return Ops;
3403}
3404
Chris Lattneraaa23d92006-05-16 22:53:20 +00003405
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003406/// ExpandScalarCallArgs - Recursively expand call argument node by
3407/// bit_converting it or extract a pair of elements from the larger node.
3408static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003409 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003410 SmallVector<SDOperand, 32> &Ops,
3411 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003412 TargetLowering &TLI,
3413 bool isFirst = true) {
3414
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003415 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003416 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003417 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003418 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3419 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003420 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003421 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003422 return;
3423 }
3424
3425 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3426 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3427 if (NumVals == 1) {
3428 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003429 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003430 } else if (NumVals == 2) {
3431 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3432 DAG.getConstant(0, TLI.getPointerTy()));
3433 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3434 DAG.getConstant(1, TLI.getPointerTy()));
3435 if (!TLI.isLittleEndian())
3436 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003437 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3438 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003439 } else {
3440 // Value scalarized into many values. Unimp for now.
3441 assert(0 && "Cannot expand i64 -> i16 yet!");
3442 }
3443}
3444
Chris Lattneraaa23d92006-05-16 22:53:20 +00003445/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3446/// implementation, which just inserts an ISD::CALL node, which is later custom
3447/// lowered by the target to something concrete. FIXME: When all targets are
3448/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3449std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003450TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3451 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003452 unsigned CallingConv, bool isTailCall,
3453 SDOperand Callee,
3454 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003455 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003456 Ops.push_back(Chain); // Op#0 - Chain
3457 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3458 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3459 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3460 Ops.push_back(Callee);
3461
3462 // Handle all of the outgoing arguments.
3463 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003464 MVT::ValueType VT = getValueType(Args[i].Ty);
3465 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003466 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003467 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003468 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003469
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003470 if (Args[i].isSExt)
3471 Flags |= ISD::ParamFlags::SExt;
3472 if (Args[i].isZExt)
3473 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003474 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003475 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003476 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003477 Flags |= ISD::ParamFlags::StructReturn;
3478 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003479
Chris Lattneraaa23d92006-05-16 22:53:20 +00003480 switch (getTypeAction(VT)) {
3481 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003482 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003483 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003484 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003485 break;
3486 case Promote:
3487 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003488 unsigned ExtOp;
3489 if (Args[i].isSExt)
3490 ExtOp = ISD::SIGN_EXTEND;
3491 else if (Args[i].isZExt)
3492 ExtOp = ISD::ZERO_EXTEND;
3493 else
3494 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003495 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3496 } else {
3497 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3498 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3499 }
3500 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003501 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003502 break;
3503 case Expand:
3504 if (VT != MVT::Vector) {
3505 // If this is a large integer, it needs to be broken down into small
3506 // integers. Figure out what the source elt type is and how many small
3507 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003508 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003509 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003510 // Otherwise, this is a vector type. We only support legal vectors
3511 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003512 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003513 unsigned NumElems = PTy->getNumElements();
3514 const Type *EltTy = PTy->getElementType();
3515
3516 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003517 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003518 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003519 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003520 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003521 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3522 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003523 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003524 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003525 assert(0 && "Don't support illegal by-val vector call args yet!");
3526 abort();
3527 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003528 }
3529 break;
3530 }
3531 }
3532
3533 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003534 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003535
3536 if (RetTy != Type::VoidTy) {
3537 MVT::ValueType VT = getValueType(RetTy);
3538 switch (getTypeAction(VT)) {
3539 default: assert(0 && "Unknown type action!");
3540 case Legal:
3541 RetTys.push_back(VT);
3542 break;
3543 case Promote:
3544 RetTys.push_back(getTypeToTransformTo(VT));
3545 break;
3546 case Expand:
3547 if (VT != MVT::Vector) {
3548 // If this is a large integer, it needs to be reassembled from small
3549 // integers. Figure out what the source elt type is and how many small
3550 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003551 MVT::ValueType NVT = getTypeToExpandTo(VT);
3552 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003553 for (unsigned i = 0; i != NumVals; ++i)
3554 RetTys.push_back(NVT);
3555 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003556 // Otherwise, this is a vector type. We only support legal vectors
3557 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003558 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003559 unsigned NumElems = PTy->getNumElements();
3560 const Type *EltTy = PTy->getElementType();
3561
3562 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003563 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003564 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3565 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3566 RetTys.push_back(TVT);
3567 } else {
3568 assert(0 && "Don't support illegal by-val vector call results yet!");
3569 abort();
3570 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003571 }
3572 }
3573 }
3574
3575 RetTys.push_back(MVT::Other); // Always has a chain.
3576
3577 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003578 SDOperand Res = DAG.getNode(ISD::CALL,
3579 DAG.getVTList(&RetTys[0], RetTys.size()),
3580 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003581
3582 // This returns a pair of operands. The first element is the
3583 // return value for the function (if RetTy is not VoidTy). The second
3584 // element is the outgoing token chain.
3585 SDOperand ResVal;
3586 if (RetTys.size() != 1) {
3587 MVT::ValueType VT = getValueType(RetTy);
3588 if (RetTys.size() == 2) {
3589 ResVal = Res;
3590
3591 // If this value was promoted, truncate it down.
3592 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003593 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003594 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003595 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003596 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3597 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003598
3599 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003600 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003601 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003602 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003603 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3604 // "N x PTyElementVT" MVT::Vector type.
3605 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003606 DAG.getConstant(NumElems, MVT::i32),
3607 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003608 } else {
3609 abort();
3610 }
3611 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003612 unsigned AssertOp = ISD::AssertSext;
3613 if (!RetTyIsSigned)
3614 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003615 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3616 DAG.getValueType(VT));
3617 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3618 } else {
3619 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003620 if (getTypeAction(VT) == Expand)
3621 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3622 else
3623 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003624 }
3625 }
3626 } else if (RetTys.size() == 3) {
3627 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3628 Res.getValue(0), Res.getValue(1));
3629
3630 } else {
3631 assert(0 && "Case not handled yet!");
3632 }
3633 }
3634
3635 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3636}
3637
Chris Lattner29dcc712005-05-14 05:50:48 +00003638SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003639 assert(0 && "LowerOperation not implemented for this target!");
3640 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003641 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003642}
3643
Nate Begeman595ec732006-01-28 03:14:31 +00003644SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3645 SelectionDAG &DAG) {
3646 assert(0 && "CustomPromoteOperation not implemented for this target!");
3647 abort();
3648 return SDOperand();
3649}
3650
Evan Cheng6781b6e2006-02-15 21:59:04 +00003651/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003652/// operand.
3653static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003654 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003655 MVT::ValueType CurVT = VT;
3656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3657 uint64_t Val = C->getValue() & 255;
3658 unsigned Shift = 8;
3659 while (CurVT != MVT::i8) {
3660 Val = (Val << Shift) | Val;
3661 Shift <<= 1;
3662 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003663 }
3664 return DAG.getConstant(Val, VT);
3665 } else {
3666 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3667 unsigned Shift = 8;
3668 while (CurVT != MVT::i8) {
3669 Value =
3670 DAG.getNode(ISD::OR, VT,
3671 DAG.getNode(ISD::SHL, VT, Value,
3672 DAG.getConstant(Shift, MVT::i8)), Value);
3673 Shift <<= 1;
3674 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003675 }
3676
3677 return Value;
3678 }
3679}
3680
Evan Cheng6781b6e2006-02-15 21:59:04 +00003681/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3682/// used when a memcpy is turned into a memset when the source is a constant
3683/// string ptr.
3684static SDOperand getMemsetStringVal(MVT::ValueType VT,
3685 SelectionDAG &DAG, TargetLowering &TLI,
3686 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003687 uint64_t Val = 0;
3688 unsigned MSB = getSizeInBits(VT) / 8;
3689 if (TLI.isLittleEndian())
3690 Offset = Offset + MSB - 1;
3691 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003692 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003693 Offset += TLI.isLittleEndian() ? -1 : 1;
3694 }
3695 return DAG.getConstant(Val, VT);
3696}
3697
Evan Cheng81fcea82006-02-14 08:22:34 +00003698/// getMemBasePlusOffset - Returns base and offset node for the
3699static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3700 SelectionDAG &DAG, TargetLowering &TLI) {
3701 MVT::ValueType VT = Base.getValueType();
3702 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3703}
3704
Evan Chengdb2a7a72006-02-14 20:12:38 +00003705/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003706/// to replace the memset / memcpy is below the threshold. It also returns the
3707/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003708static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3709 unsigned Limit, uint64_t Size,
3710 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003711 MVT::ValueType VT;
3712
3713 if (TLI.allowsUnalignedMemoryAccesses()) {
3714 VT = MVT::i64;
3715 } else {
3716 switch (Align & 7) {
3717 case 0:
3718 VT = MVT::i64;
3719 break;
3720 case 4:
3721 VT = MVT::i32;
3722 break;
3723 case 2:
3724 VT = MVT::i16;
3725 break;
3726 default:
3727 VT = MVT::i8;
3728 break;
3729 }
3730 }
3731
Evan Chengd5026102006-02-14 09:11:59 +00003732 MVT::ValueType LVT = MVT::i64;
3733 while (!TLI.isTypeLegal(LVT))
3734 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3735 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003736
Evan Chengd5026102006-02-14 09:11:59 +00003737 if (VT > LVT)
3738 VT = LVT;
3739
Evan Cheng04514992006-02-14 23:05:54 +00003740 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003741 while (Size != 0) {
3742 unsigned VTSize = getSizeInBits(VT) / 8;
3743 while (VTSize > Size) {
3744 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003745 VTSize >>= 1;
3746 }
Evan Chengd5026102006-02-14 09:11:59 +00003747 assert(MVT::isInteger(VT));
3748
3749 if (++NumMemOps > Limit)
3750 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003751 MemOps.push_back(VT);
3752 Size -= VTSize;
3753 }
Evan Chengd5026102006-02-14 09:11:59 +00003754
3755 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003756}
3757
Chris Lattner875def92005-01-11 05:56:49 +00003758void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003759 SDOperand Op1 = getValue(I.getOperand(1));
3760 SDOperand Op2 = getValue(I.getOperand(2));
3761 SDOperand Op3 = getValue(I.getOperand(3));
3762 SDOperand Op4 = getValue(I.getOperand(4));
3763 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3764 if (Align == 0) Align = 1;
3765
3766 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3767 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003768
3769 // Expand memset / memcpy to a series of load / store ops
3770 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003771 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003772 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003773 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003774 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003775 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3776 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003777 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003778 unsigned Offset = 0;
3779 for (unsigned i = 0; i < NumMemOps; i++) {
3780 MVT::ValueType VT = MemOps[i];
3781 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003782 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003783 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003784 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003785 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003786 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003787 Offset += VTSize;
3788 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003789 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003790 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003791 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003792 case ISD::MEMCPY: {
3793 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3794 Size->getValue(), Align, TLI)) {
3795 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003796 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003797 GlobalAddressSDNode *G = NULL;
3798 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003799 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003800
3801 if (Op2.getOpcode() == ISD::GlobalAddress)
3802 G = cast<GlobalAddressSDNode>(Op2);
3803 else if (Op2.getOpcode() == ISD::ADD &&
3804 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3805 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3806 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003807 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003808 }
3809 if (G) {
3810 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003811 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003812 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003813 if (!Str.empty()) {
3814 CopyFromStr = true;
3815 SrcOff += SrcDelta;
3816 }
3817 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003818 }
3819
Evan Chenge2038bd2006-02-15 01:54:51 +00003820 for (unsigned i = 0; i < NumMemOps; i++) {
3821 MVT::ValueType VT = MemOps[i];
3822 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003823 SDOperand Value, Chain, Store;
3824
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003825 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003826 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3827 Chain = getRoot();
3828 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003829 DAG.getStore(Chain, Value,
3830 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003831 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003832 } else {
3833 Value = DAG.getLoad(VT, getRoot(),
3834 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003835 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003836 Chain = Value.getValue(1);
3837 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003838 DAG.getStore(Chain, Value,
3839 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003840 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003841 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003842 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003843 SrcOff += VTSize;
3844 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003845 }
3846 }
3847 break;
3848 }
3849 }
3850
3851 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003852 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3853 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003854 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003855 }
3856 }
3857
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003858 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003859}
3860
Chris Lattner875def92005-01-11 05:56:49 +00003861//===----------------------------------------------------------------------===//
3862// SelectionDAGISel code
3863//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003864
3865unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3866 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3867}
3868
Chris Lattnerc9950c12005-08-17 06:37:43 +00003869void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003870 // FIXME: we only modify the CFG to split critical edges. This
3871 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003872 AU.addRequired<AliasAnalysis>();
Evan Cheng009ea542007-03-16 08:46:27 +00003873 AU.addRequired<LoopInfo>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003874}
Chris Lattner7a60d912005-01-07 07:47:53 +00003875
Chris Lattner35397782005-12-05 07:10:48 +00003876
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003877/// OptimizeNoopCopyExpression - We have determined that the specified cast
3878/// instruction is a noop copy (e.g. it's casting from one pointer type to
3879/// another, int->uint, or int->sbyte on PPC.
3880///
3881/// Return true if any changes are made.
3882static bool OptimizeNoopCopyExpression(CastInst *CI) {
3883 BasicBlock *DefBB = CI->getParent();
3884
3885 /// InsertedCasts - Only insert a cast in each block once.
3886 std::map<BasicBlock*, CastInst*> InsertedCasts;
3887
3888 bool MadeChange = false;
3889 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3890 UI != E; ) {
3891 Use &TheUse = UI.getUse();
3892 Instruction *User = cast<Instruction>(*UI);
3893
3894 // Figure out which BB this cast is used in. For PHI's this is the
3895 // appropriate predecessor block.
3896 BasicBlock *UserBB = User->getParent();
3897 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3898 unsigned OpVal = UI.getOperandNo()/2;
3899 UserBB = PN->getIncomingBlock(OpVal);
3900 }
3901
3902 // Preincrement use iterator so we don't invalidate it.
3903 ++UI;
3904
3905 // If this user is in the same block as the cast, don't change the cast.
3906 if (UserBB == DefBB) continue;
3907
3908 // If we have already inserted a cast into this block, use it.
3909 CastInst *&InsertedCast = InsertedCasts[UserBB];
3910
3911 if (!InsertedCast) {
3912 BasicBlock::iterator InsertPt = UserBB->begin();
3913 while (isa<PHINode>(InsertPt)) ++InsertPt;
3914
3915 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003916 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3917 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003918 MadeChange = true;
3919 }
3920
3921 // Replace a use of the cast with a use of the new casat.
3922 TheUse = InsertedCast;
3923 }
3924
3925 // If we removed all uses, nuke the cast.
3926 if (CI->use_empty())
3927 CI->eraseFromParent();
3928
3929 return MadeChange;
3930}
3931
Chris Lattner35397782005-12-05 07:10:48 +00003932/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3933/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003934static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3935 Instruction *GEPI, Value *Ptr,
3936 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003937 if (V) return V; // Already computed.
3938
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003939 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003940 BasicBlock::iterator InsertPt;
3941 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003942 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003943 InsertPt = GEPI;
3944 ++InsertPt;
3945 } else {
3946 // Otherwise, insert at the top of BB, after any PHI nodes
3947 InsertPt = BB->begin();
3948 while (isa<PHINode>(InsertPt)) ++InsertPt;
3949 }
3950
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003951 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3952 // BB so that there is only one value live across basic blocks (the cast
3953 // operand).
3954 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3955 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003956 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3957 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003958
Chris Lattner35397782005-12-05 07:10:48 +00003959 // Add the offset, cast it to the right type.
3960 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003961 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3962 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3963 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003964}
3965
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003966/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3967/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3968/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3969/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3970/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3971/// the constant add into a load or store instruction. Additionally, if a user
3972/// is a pointer-pointer cast, we look through it to find its users.
3973static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3974 Constant *PtrOffset, BasicBlock *DefBB,
3975 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003976 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003977 while (!RepPtr->use_empty()) {
3978 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003979
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003980 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3981 // used for a Pointer-Pointer cast.
3982 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003983 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003984
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003985 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3986 // could invalidate an iterator.
3987 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3988 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003989 }
3990
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003991 // If this is a load of the pointer, or a store through the pointer, emit
3992 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003993 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003994 if (isa<LoadInst>(User) ||
3995 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3996 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3997 User->getParent(), GEPI,
3998 Ptr, PtrOffset);
3999 } else {
4000 // If this use is not foldable into the addressing mode, use a version
4001 // emitted in the GEP block.
4002 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
4003 Ptr, PtrOffset);
4004 }
4005
Chris Lattner21cd9902006-05-06 09:10:37 +00004006 if (GEPI->getType() != RepPtr->getType()) {
4007 BasicBlock::iterator IP = NewVal;
4008 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004009 // NewVal must be a GEP which must be pointer type, so BitCast
4010 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00004011 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004012 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004013 }
4014}
Chris Lattner35397782005-12-05 07:10:48 +00004015
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004016
Chris Lattner35397782005-12-05 07:10:48 +00004017/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
4018/// selection, we want to be a bit careful about some things. In particular, if
4019/// we have a GEP instruction that is used in a different block than it is
4020/// defined, the addressing expression of the GEP cannot be folded into loads or
4021/// stores that use it. In this case, decompose the GEP and move constant
4022/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004023static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00004024 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00004025 // If this GEP is only used inside the block it is defined in, there is no
4026 // need to rewrite it.
4027 bool isUsedOutsideDefBB = false;
4028 BasicBlock *DefBB = GEPI->getParent();
4029 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
4030 UI != E; ++UI) {
4031 if (cast<Instruction>(*UI)->getParent() != DefBB) {
4032 isUsedOutsideDefBB = true;
4033 break;
4034 }
4035 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004036 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00004037
4038 // If this GEP has no non-zero constant indices, there is nothing we can do,
4039 // ignore it.
4040 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004041 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00004042 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
4043 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004044 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004045 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00004046 hasConstantIndex = true;
4047 break;
4048 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004049 } else {
4050 hasVariableIndex = true;
4051 }
Chris Lattner35397782005-12-05 07:10:48 +00004052 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004053
4054 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
4055 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004056 /// The GEP operand must be a pointer, so must its result -> BitCast
4057 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004058 GEPI->getName(), GEPI);
4059 GEPI->replaceAllUsesWith(NC);
4060 GEPI->eraseFromParent();
4061 return true;
4062 }
4063
Chris Lattnerf1a54c02005-12-11 09:05:13 +00004064 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004065 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
4066 return false;
Chris Lattner35397782005-12-05 07:10:48 +00004067
4068 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
4069 // constant offset (which we now know is non-zero) and deal with it later.
4070 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00004071 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004072 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00004073 const Type *Ty = GEPI->getOperand(0)->getType();
4074
4075 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
4076 E = GEPI->op_end(); OI != E; ++OI) {
4077 Value *Idx = *OI;
4078 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004079 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00004080 if (Field)
Chris Lattnerc473d8e2007-02-10 19:55:17 +00004081 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner35397782005-12-05 07:10:48 +00004082 Ty = StTy->getElementType(Field);
4083 } else {
4084 Ty = cast<SequentialType>(Ty)->getElementType();
4085
4086 // Handle constant subscripts.
4087 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004088 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00004089 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00004090 continue;
4091 }
4092
4093 // Ptr = Ptr + Idx * ElementSize;
4094
4095 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00004096 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00004097
Owen Anderson20a631f2006-05-03 01:29:57 +00004098 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00004099 // Mask off bits that should not be set.
4100 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004101 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00004102
4103 // Multiply by the element size and add to the base.
4104 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
4105 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
4106 }
4107 }
4108
4109 // Make sure that the offset fits in uintptr_t.
4110 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004111 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00004112
4113 // Okay, we have now emitted all of the variable index parts to the BB that
4114 // the GEP is defined in. Loop over all of the using instructions, inserting
4115 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00004116 // instruction to use the newly computed value, making GEPI dead. When the
4117 // user is a load or store instruction address, we emit the add into the user
4118 // block, otherwise we use a canonical version right next to the gep (these
4119 // won't be foldable as addresses, so we might as well share the computation).
4120
Chris Lattner21cd9902006-05-06 09:10:37 +00004121 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004122 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00004123
4124 // Finally, the GEP is dead, remove it.
4125 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004126
4127 return true;
Chris Lattner35397782005-12-05 07:10:48 +00004128}
4129
Evan Cheng009ea542007-03-16 08:46:27 +00004130/// isLoopInvariantInst - Returns true if all operands of the instruction are
4131/// loop invariants in the specified loop.
4132static bool isLoopInvariantInst(Instruction *I, Loop *L) {
4133 // The instruction is loop invariant if all of its operands are loop-invariant
4134 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4135 if (!L->isLoopInvariant(I->getOperand(i)))
4136 return false;
4137 return true;
4138}
4139
4140/// SinkInvariantGEPIndex - If a GEP instruction has a variable index that has
4141/// been hoisted out of the loop by LICM pass, sink it back into the use BB
4142/// if it can be determined that the index computation can be folded into the
4143/// addressing mode of the load / store uses.
4144static bool SinkInvariantGEPIndex(BinaryOperator *BinOp, LoopInfo *loopInfo,
4145 const TargetLowering &TLI) {
Evan Cheng009ea542007-03-16 08:46:27 +00004146 // Only look at Add / Sub for now.
4147 if (BinOp->getOpcode() != Instruction::Add &&
4148 BinOp->getOpcode() != Instruction::Sub)
4149 return false;
4150
Evan Chengbe222352007-03-17 08:22:49 +00004151 // DestBBs - These are the blocks where a copy of BinOp will be inserted.
Evan Chenga2465df2007-03-17 08:53:30 +00004152 SmallSet<BasicBlock*, 8> DestBBs;
Evan Cheng009ea542007-03-16 08:46:27 +00004153 BasicBlock *DefBB = BinOp->getParent();
Evan Chengbe222352007-03-17 08:22:49 +00004154 bool MadeChange = false;
Evan Cheng009ea542007-03-16 08:46:27 +00004155 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
Evan Chengbe222352007-03-17 08:22:49 +00004156 UI != E; ++UI) {
Evan Cheng009ea542007-03-16 08:46:27 +00004157 Instruction *User = cast<Instruction>(*UI);
Evan Cheng009ea542007-03-16 08:46:27 +00004158 // Only look for GEP use in another block.
4159 if (User->getParent() == DefBB) continue;
4160
4161 if (isa<GetElementPtrInst>(User)) {
4162 BasicBlock *UserBB = User->getParent();
4163 Loop *L = loopInfo->getLoopFor(UserBB);
4164
4165 // Only sink if expression is a loop invariant in the use BB.
Evan Cheng0a9d0ca2007-03-16 17:50:20 +00004166 if (L && isLoopInvariantInst(BinOp, L) && !User->use_empty()) {
Evan Cheng009ea542007-03-16 08:46:27 +00004167 const Type *UseTy = NULL;
4168 // FIXME: We are assuming all the uses of the GEP will have the
4169 // same type.
4170 Instruction *GEPUser = cast<Instruction>(*User->use_begin());
4171 if (LoadInst *Load = dyn_cast<LoadInst>(GEPUser))
4172 UseTy = Load->getType();
4173 else if (StoreInst *Store = dyn_cast<StoreInst>(GEPUser))
4174 UseTy = Store->getOperand(0)->getType();
4175
4176 // Check if it is possible to fold the expression to address mode.
4177 if (UseTy &&
Evan Cheng550cf032007-03-20 19:32:11 +00004178 TLI.isLegalAddressExpression(BinOp->getOpcode(),
4179 BinOp->getOperand(0),
Evan Cheng009ea542007-03-16 08:46:27 +00004180 BinOp->getOperand(1), UseTy)) {
Evan Chengbe222352007-03-17 08:22:49 +00004181 DestBBs.insert(UserBB);
Evan Cheng009ea542007-03-16 08:46:27 +00004182 MadeChange = true;
4183 }
4184 }
4185 }
4186 }
4187
Evan Chengbe222352007-03-17 08:22:49 +00004188 // Nothing to do.
4189 if (!MadeChange)
4190 return false;
4191
4192 /// InsertedOps - Only insert a duplicate in each block once.
4193 std::map<BasicBlock*, BinaryOperator*> InsertedOps;
4194 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
4195 UI != E; ) {
4196 Instruction *User = cast<Instruction>(*UI);
4197 BasicBlock *UserBB = User->getParent();
4198
4199 // Preincrement use iterator so we don't invalidate it.
4200 ++UI;
4201
4202 // If any user in this BB wants it, replace all the uses in the BB.
4203 if (DestBBs.count(UserBB)) {
4204 // Sink it into user block.
4205 BinaryOperator *&InsertedOp = InsertedOps[UserBB];
4206 if (!InsertedOp) {
4207 BasicBlock::iterator InsertPt = UserBB->begin();
4208 while (isa<PHINode>(InsertPt)) ++InsertPt;
4209
4210 InsertedOp =
4211 BinaryOperator::create(BinOp->getOpcode(), BinOp->getOperand(0),
4212 BinOp->getOperand(1), "", InsertPt);
4213 }
4214
4215 User->replaceUsesOfWith(BinOp, InsertedOp);
4216 }
4217 }
4218
Evan Cheng009ea542007-03-16 08:46:27 +00004219 if (BinOp->use_empty())
4220 BinOp->eraseFromParent();
4221
Evan Chengbe222352007-03-17 08:22:49 +00004222 return true;
Evan Cheng009ea542007-03-16 08:46:27 +00004223}
4224
Chris Lattnerbba52192006-10-28 19:22:10 +00004225
4226/// SplitEdgeNicely - Split the critical edge from TI to it's specified
4227/// successor if it will improve codegen. We only do this if the successor has
4228/// phi nodes (otherwise critical edges are ok). If there is already another
4229/// predecessor of the succ that is empty (and thus has no phi nodes), use it
4230/// instead of introducing a new block.
4231static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
4232 BasicBlock *TIBB = TI->getParent();
4233 BasicBlock *Dest = TI->getSuccessor(SuccNum);
4234 assert(isa<PHINode>(Dest->begin()) &&
4235 "This should only be called if Dest has a PHI!");
4236
4237 /// TIPHIValues - This array is lazily computed to determine the values of
4238 /// PHIs in Dest that TI would provide.
4239 std::vector<Value*> TIPHIValues;
4240
4241 // Check to see if Dest has any blocks that can be used as a split edge for
4242 // this terminator.
4243 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
4244 BasicBlock *Pred = *PI;
4245 // To be usable, the pred has to end with an uncond branch to the dest.
4246 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
4247 if (!PredBr || !PredBr->isUnconditional() ||
4248 // Must be empty other than the branch.
4249 &Pred->front() != PredBr)
4250 continue;
4251
4252 // Finally, since we know that Dest has phi nodes in it, we have to make
4253 // sure that jumping to Pred will have the same affect as going to Dest in
4254 // terms of PHI values.
4255 PHINode *PN;
4256 unsigned PHINo = 0;
4257 bool FoundMatch = true;
4258 for (BasicBlock::iterator I = Dest->begin();
4259 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
4260 if (PHINo == TIPHIValues.size())
4261 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
4262
4263 // If the PHI entry doesn't work, we can't use this pred.
4264 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
4265 FoundMatch = false;
4266 break;
4267 }
4268 }
4269
4270 // If we found a workable predecessor, change TI to branch to Succ.
4271 if (FoundMatch) {
4272 Dest->removePredecessor(TIBB);
4273 TI->setSuccessor(SuccNum, Pred);
4274 return;
4275 }
4276 }
4277
4278 SplitCriticalEdge(TI, SuccNum, P, true);
4279}
4280
4281
Chris Lattner7a60d912005-01-07 07:47:53 +00004282bool SelectionDAGISel::runOnFunction(Function &Fn) {
4283 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4284 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004285 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004286
Evan Cheng009ea542007-03-16 08:46:27 +00004287 LoopInfo *loopInfo = &getAnalysis<LoopInfo>();
4288
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004289 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00004290 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004291 // In this pass we also look for GEP and cast instructions that are used
4292 // across basic blocks and rewrite them to improve basic-block-at-a-time
4293 // selection.
4294 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004295 bool MadeChange = true;
4296 while (MadeChange) {
4297 MadeChange = false;
Evan Chengde608342007-02-10 01:08:18 +00004298 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbba52192006-10-28 19:22:10 +00004299 // Split all critical edges where the dest block has a PHI.
Evan Chengde608342007-02-10 01:08:18 +00004300 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004301 if (BBTI->getNumSuccessors() > 1) {
4302 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00004303 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4304 isCriticalEdge(BBTI, i, true))
4305 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004306 }
4307
Chris Lattner35397782005-12-05 07:10:48 +00004308
Evan Chengde608342007-02-10 01:08:18 +00004309 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004310 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00004311
4312 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4313 // If we found an inline asm expession, and if the target knows how to
4314 // lower it to normal LLVM code, do so now.
4315 if (isa<InlineAsm>(CI->getCalledValue()))
4316 if (const TargetAsmInfo *TAI =
4317 TLI.getTargetMachine().getTargetAsmInfo()) {
4318 if (TAI->ExpandInlineAsm(CI))
Evan Chengde608342007-02-10 01:08:18 +00004319 BBI = FNI->begin();
Chris Lattner90f42382006-11-29 01:12:32 +00004320 }
4321 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004322 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004323 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00004324 // If the source of the cast is a constant, then this should have
4325 // already been constant folded. The only reason NOT to constant fold
4326 // it is if something (e.g. LSR) was careful to place the constant
4327 // evaluation in a block other than then one that uses it (e.g. to hoist
4328 // the address of globals out of a loop). If this is the case, we don't
4329 // want to forward-subst the cast.
4330 if (isa<Constant>(CI->getOperand(0)))
4331 continue;
4332
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004333 // If this is a noop copy, sink it into user blocks to reduce the number
4334 // of virtual registers that must be created and coallesced.
4335 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4336 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4337
4338 // This is an fp<->int conversion?
4339 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4340 continue;
4341
4342 // If this is an extension, it will be a zero or sign extension, which
4343 // isn't a noop.
4344 if (SrcVT < DstVT) continue;
4345
4346 // If these values will be promoted, find out what they will be promoted
4347 // to. This helps us consider truncates on PPC as noop copies when they
4348 // are.
4349 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4350 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4351 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4352 DstVT = TLI.getTypeToTransformTo(DstVT);
4353
4354 // If, after promotion, these are the same types, this is a noop copy.
4355 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004356 MadeChange |= OptimizeNoopCopyExpression(CI);
Evan Cheng009ea542007-03-16 08:46:27 +00004357 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I)) {
4358 MadeChange |= SinkInvariantGEPIndex(BinOp, loopInfo, TLI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004359 }
4360 }
Chris Lattner1a908c82005-08-18 17:35:14 +00004361 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004362 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00004363
Chris Lattner7a60d912005-01-07 07:47:53 +00004364 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4365
4366 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4367 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004368
Evan Cheng276b44b2007-02-10 02:43:39 +00004369 // Add function live-ins to entry block live-in set.
4370 BasicBlock *EntryBB = &Fn.getEntryBlock();
4371 BB = FuncInfo.MBBMap[EntryBB];
4372 if (!MF.livein_empty())
4373 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4374 E = MF.livein_end(); I != E; ++I)
4375 BB->addLiveIn(I->first);
4376
Chris Lattner7a60d912005-01-07 07:47:53 +00004377 return true;
4378}
4379
Chris Lattnered0110b2006-10-27 21:36:01 +00004380SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4381 unsigned Reg) {
4382 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004383 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004384 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004385 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004386
4387 // If this type is not legal, we must make sure to not create an invalid
4388 // register use.
4389 MVT::ValueType SrcVT = Op.getValueType();
4390 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004391 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004392 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004393 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004394 // Handle copies from generic vectors to registers.
4395 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004396 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004397 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004398
Chris Lattner5fe1f542006-03-31 02:06:56 +00004399 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4400 // MVT::Vector type.
4401 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4402 DAG.getConstant(NE, MVT::i32),
4403 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004404
Chris Lattner5fe1f542006-03-31 02:06:56 +00004405 // Loop over all of the elements of the resultant vector,
4406 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4407 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004408 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004409 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004410 for (unsigned i = 0; i != NE; ++i) {
4411 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004412 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004413 if (PTyElementVT == PTyLegalElementVT) {
4414 // Elements are legal.
4415 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4416 } else if (PTyLegalElementVT > PTyElementVT) {
4417 // Elements are promoted.
4418 if (MVT::isFloatingPoint(PTyLegalElementVT))
4419 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4420 else
4421 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4422 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4423 } else {
4424 // Elements are expanded.
4425 // The src value is expanded into multiple registers.
4426 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004427 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004428 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004429 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004430 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4431 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4432 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004433 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004434 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4435 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004436 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004437 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004438 if (MVT::isFloatingPoint(SrcVT))
4439 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4440 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004441 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004442 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004443 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004444 DestVT = TLI.getTypeToExpandTo(SrcVT);
4445 unsigned NumVals = TLI.getNumElements(SrcVT);
4446 if (NumVals == 1)
4447 return DAG.getCopyToReg(getRoot(), Reg,
4448 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4449 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004450 // The src value is expanded into multiple registers.
4451 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004452 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004453 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004454 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004455 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004456 return DAG.getCopyToReg(Op, Reg+1, Hi);
4457 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004458}
4459
Chris Lattner16f64df2005-01-17 17:15:02 +00004460void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004461LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004462 std::vector<SDOperand> &UnorderedChains) {
4463 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004464 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004465 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004466 SDOperand OldRoot = SDL.DAG.getRoot();
4467 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004468
Chris Lattner6871b232005-10-30 19:42:35 +00004469 unsigned a = 0;
4470 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4471 AI != E; ++AI, ++a)
4472 if (!AI->use_empty()) {
4473 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004474
Chris Lattner6871b232005-10-30 19:42:35 +00004475 // If this argument is live outside of the entry block, insert a copy from
4476 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004477 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4478 if (VMI != FuncInfo.ValueMap.end()) {
4479 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004480 UnorderedChains.push_back(Copy);
4481 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004482 }
Chris Lattner6871b232005-10-30 19:42:35 +00004483
Chris Lattner6871b232005-10-30 19:42:35 +00004484 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004485 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004486 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004487}
4488
Chris Lattner7a60d912005-01-07 07:47:53 +00004489void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4490 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004491 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004492 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004493
4494 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004495
Chris Lattner6871b232005-10-30 19:42:35 +00004496 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004497 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004498 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004499
4500 BB = FuncInfo.MBBMap[LLVMBB];
4501 SDL.setCurrentBasicBlock(BB);
4502
4503 // Lower all of the non-terminator instructions.
4504 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4505 I != E; ++I)
4506 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004507
4508 // Lower call part of invoke.
4509 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4510 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004511
Chris Lattner7a60d912005-01-07 07:47:53 +00004512 // Ensure that all instructions which are used outside of their defining
4513 // blocks are available as virtual registers.
4514 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004515 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004516 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004517 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004518 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004519 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004520 }
4521
4522 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4523 // ensure constants are generated when needed. Remember the virtual registers
4524 // that need to be added to the Machine PHI nodes as input. We cannot just
4525 // directly add them, because expansion might result in multiple MBB's for one
4526 // BB. As such, the start of the BB might correspond to a different MBB than
4527 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004528 //
Chris Lattner84a03502006-10-27 23:50:33 +00004529 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004530
4531 // Emit constants only once even if used by multiple PHI nodes.
4532 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004533
Chris Lattner84a03502006-10-27 23:50:33 +00004534 // Vector bool would be better, but vector<bool> is really slow.
4535 std::vector<unsigned char> SuccsHandled;
4536 if (TI->getNumSuccessors())
4537 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4538
Chris Lattner7a60d912005-01-07 07:47:53 +00004539 // Check successor nodes PHI nodes that expect a constant to be available from
4540 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004541 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4542 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004543 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004544 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004545
Chris Lattner84a03502006-10-27 23:50:33 +00004546 // If this terminator has multiple identical successors (common for
4547 // switches), only handle each succ once.
4548 unsigned SuccMBBNo = SuccMBB->getNumber();
4549 if (SuccsHandled[SuccMBBNo]) continue;
4550 SuccsHandled[SuccMBBNo] = true;
4551
4552 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004553 PHINode *PN;
4554
4555 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4556 // nodes and Machine PHI nodes, but the incoming operands have not been
4557 // emitted yet.
4558 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004559 (PN = dyn_cast<PHINode>(I)); ++I) {
4560 // Ignore dead phi's.
4561 if (PN->use_empty()) continue;
4562
4563 unsigned Reg;
4564 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004565
Chris Lattner84a03502006-10-27 23:50:33 +00004566 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4567 unsigned &RegOut = ConstantsOut[C];
4568 if (RegOut == 0) {
4569 RegOut = FuncInfo.CreateRegForValue(C);
4570 UnorderedChains.push_back(
4571 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004572 }
Chris Lattner84a03502006-10-27 23:50:33 +00004573 Reg = RegOut;
4574 } else {
4575 Reg = FuncInfo.ValueMap[PHIOp];
4576 if (Reg == 0) {
4577 assert(isa<AllocaInst>(PHIOp) &&
4578 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4579 "Didn't codegen value into a register!??");
4580 Reg = FuncInfo.CreateRegForValue(PHIOp);
4581 UnorderedChains.push_back(
4582 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004583 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004584 }
Chris Lattner84a03502006-10-27 23:50:33 +00004585
4586 // Remember that this register needs to added to the machine PHI node as
4587 // the input for this MBB.
4588 MVT::ValueType VT = TLI.getValueType(PN->getType());
4589 unsigned NumElements;
4590 if (VT != MVT::Vector)
4591 NumElements = TLI.getNumElements(VT);
4592 else {
4593 MVT::ValueType VT1,VT2;
4594 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004595 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004596 VT1, VT2);
4597 }
4598 for (unsigned i = 0, e = NumElements; i != e; ++i)
4599 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4600 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004601 }
4602 ConstantsOut.clear();
4603
Chris Lattner718b5c22005-01-13 17:59:43 +00004604 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004605 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004606 SDOperand Root = SDL.getRoot();
4607 if (Root.getOpcode() != ISD::EntryToken) {
4608 unsigned i = 0, e = UnorderedChains.size();
4609 for (; i != e; ++i) {
4610 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4611 if (UnorderedChains[i].Val->getOperand(0) == Root)
4612 break; // Don't add the root if we already indirectly depend on it.
4613 }
4614
4615 if (i == e)
4616 UnorderedChains.push_back(Root);
4617 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004618 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4619 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004620 }
4621
Chris Lattner7a60d912005-01-07 07:47:53 +00004622 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004623 if (Invoke) {
4624 // Just the branch part of invoke.
4625 SDL.visitInvoke(*Invoke, true);
4626 } else {
4627 SDL.visit(*LLVMBB->getTerminator());
4628 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004629
Nate Begemaned728c12006-03-27 01:32:24 +00004630 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004631 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004632 SwitchCases.clear();
4633 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004634 JTCases.clear();
4635 JTCases = SDL.JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +00004636
Chris Lattner4108bb02005-01-17 19:43:36 +00004637 // Make sure the root of the DAG is up-to-date.
4638 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004639}
4640
Nate Begemaned728c12006-03-27 01:32:24 +00004641void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004642 // Get alias analysis for load/store combining.
4643 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4644
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004645 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004646 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004647
Bill Wendling22e978a2006-12-07 20:04:42 +00004648 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004649 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004650
Chris Lattner7a60d912005-01-07 07:47:53 +00004651 // Second step, hack on the DAG until it only uses operations and types that
4652 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004653 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004654
Bill Wendling22e978a2006-12-07 20:04:42 +00004655 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004656 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004657
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004658 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004659 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004660
Evan Cheng739a6a42006-01-21 02:32:06 +00004661 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004662
Chris Lattner5ca31d92005-03-30 01:10:47 +00004663 // Third, instruction select all of the operations to machine code, adding the
4664 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004665 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004666
Bill Wendling22e978a2006-12-07 20:04:42 +00004667 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004668 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004669}
Chris Lattner7a60d912005-01-07 07:47:53 +00004670
Nate Begemaned728c12006-03-27 01:32:24 +00004671void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4672 FunctionLoweringInfo &FuncInfo) {
4673 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4674 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004675 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004676 CurDAG = &DAG;
4677
4678 // First step, lower LLVM code to some DAG. This DAG may use operations and
4679 // types that are not supported by the target.
4680 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4681
4682 // Second step, emit the lowered DAG as machine code.
4683 CodeGenAndEmitDAG(DAG);
4684 }
4685
Chris Lattner5ca31d92005-03-30 01:10:47 +00004686 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004687 // PHI nodes in successors.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004688 if (SwitchCases.empty() && JTCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004689 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4690 MachineInstr *PHI = PHINodesToUpdate[i].first;
4691 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4692 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004693 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004694 PHI->addMachineBasicBlockOperand(BB);
4695 }
4696 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004697 }
Nate Begemaned728c12006-03-27 01:32:24 +00004698
Nate Begeman866b4b42006-04-23 06:26:20 +00004699 // If the JumpTable record is filled in, then we need to emit a jump table.
4700 // Updating the PHI nodes is tricky in this case, since we need to determine
4701 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004702 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4703 // Lower header first, if it wasn't already lowered
4704 if (!JTCases[i].first.Emitted) {
4705 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4706 CurDAG = &HSDAG;
4707 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4708 // Set the current basic block to the mbb we wish to insert the code into
4709 BB = JTCases[i].first.HeaderBB;
4710 HSDL.setCurrentBasicBlock(BB);
4711 // Emit the code
4712 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4713 HSDAG.setRoot(HSDL.getRoot());
4714 CodeGenAndEmitDAG(HSDAG);
4715 }
4716
4717 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4718 CurDAG = &JSDAG;
4719 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004720 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004721 BB = JTCases[i].second.MBB;
4722 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004723 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004724 JSDL.visitJumpTable(JTCases[i].second);
4725 JSDAG.setRoot(JSDL.getRoot());
4726 CodeGenAndEmitDAG(JSDAG);
4727
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004728 // Update PHI Nodes
4729 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4730 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4731 MachineBasicBlock *PHIBB = PHI->getParent();
4732 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4733 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov70378262007-03-25 15:07:15 +00004734 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004735 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004736 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004737 }
4738 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004739 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004740 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004741 }
4742 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004743 }
4744
Chris Lattner76a7bc82006-10-22 23:00:53 +00004745 // If the switch block involved a branch to one of the actual successors, we
4746 // need to update PHI nodes in that block.
4747 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4748 MachineInstr *PHI = PHINodesToUpdate[i].first;
4749 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4750 "This is not a machine PHI node that we are updating!");
4751 if (BB->isSuccessor(PHI->getParent())) {
4752 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4753 PHI->addMachineBasicBlockOperand(BB);
4754 }
4755 }
4756
Nate Begemaned728c12006-03-27 01:32:24 +00004757 // If we generated any switch lowering information, build and codegen any
4758 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004759 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004760 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004761 CurDAG = &SDAG;
4762 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004763
Nate Begemaned728c12006-03-27 01:32:24 +00004764 // Set the current basic block to the mbb we wish to insert the code into
4765 BB = SwitchCases[i].ThisBB;
4766 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004767
Nate Begemaned728c12006-03-27 01:32:24 +00004768 // Emit the code
4769 SDL.visitSwitchCase(SwitchCases[i]);
4770 SDAG.setRoot(SDL.getRoot());
4771 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004772
4773 // Handle any PHI nodes in successors of this chunk, as if we were coming
4774 // from the original BB before switch expansion. Note that PHI nodes can
4775 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4776 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004777 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004778 for (MachineBasicBlock::iterator Phi = BB->begin();
4779 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4780 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4781 for (unsigned pn = 0; ; ++pn) {
4782 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4783 if (PHINodesToUpdate[pn].first == Phi) {
4784 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4785 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4786 break;
4787 }
4788 }
Nate Begemaned728c12006-03-27 01:32:24 +00004789 }
Chris Lattner707339a52006-09-07 01:59:34 +00004790
4791 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004792 if (BB == SwitchCases[i].FalseBB)
4793 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004794
4795 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004796 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004797 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004798 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004799 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004800 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004801}
Evan Cheng739a6a42006-01-21 02:32:06 +00004802
Jim Laskey95eda5b2006-08-01 14:21:23 +00004803
Evan Cheng739a6a42006-01-21 02:32:06 +00004804//===----------------------------------------------------------------------===//
4805/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4806/// target node in the graph.
4807void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4808 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004809
Jim Laskey29e635d2006-08-02 12:30:23 +00004810 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004811
4812 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004813 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004814 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004815 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004816
Jim Laskey03593f72006-08-01 18:29:48 +00004817 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004818 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004819 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004820}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004821
Chris Lattner47639db2006-03-06 00:22:00 +00004822
Jim Laskey03593f72006-08-01 18:29:48 +00004823HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4824 return new HazardRecognizer();
4825}
4826
Chris Lattner6df34962006-10-11 03:58:02 +00004827//===----------------------------------------------------------------------===//
4828// Helper functions used by the generated instruction selector.
4829//===----------------------------------------------------------------------===//
4830// Calls to these methods are generated by tblgen.
4831
4832/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4833/// the dag combiner simplified the 255, we still want to match. RHS is the
4834/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4835/// specified in the .td file (e.g. 255).
4836bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4837 int64_t DesiredMaskS) {
4838 uint64_t ActualMask = RHS->getValue();
4839 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4840
4841 // If the actual mask exactly matches, success!
4842 if (ActualMask == DesiredMask)
4843 return true;
4844
4845 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4846 if (ActualMask & ~DesiredMask)
4847 return false;
4848
4849 // Otherwise, the DAG Combiner may have proven that the value coming in is
4850 // either already zero or is not demanded. Check for known zero input bits.
4851 uint64_t NeededMask = DesiredMask & ~ActualMask;
4852 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4853 return true;
4854
4855 // TODO: check to see if missing bits are just not demanded.
4856
4857 // Otherwise, this pattern doesn't match.
4858 return false;
4859}
4860
4861/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4862/// the dag combiner simplified the 255, we still want to match. RHS is the
4863/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4864/// specified in the .td file (e.g. 255).
4865bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4866 int64_t DesiredMaskS) {
4867 uint64_t ActualMask = RHS->getValue();
4868 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4869
4870 // If the actual mask exactly matches, success!
4871 if (ActualMask == DesiredMask)
4872 return true;
4873
4874 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4875 if (ActualMask & ~DesiredMask)
4876 return false;
4877
4878 // Otherwise, the DAG Combiner may have proven that the value coming in is
4879 // either already zero or is not demanded. Check for known zero input bits.
4880 uint64_t NeededMask = DesiredMask & ~ActualMask;
4881
4882 uint64_t KnownZero, KnownOne;
4883 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4884
4885 // If all the missing bits in the or are already known to be set, match!
4886 if ((NeededMask & KnownOne) == NeededMask)
4887 return true;
4888
4889 // TODO: check to see if missing bits are just not demanded.
4890
4891 // Otherwise, this pattern doesn't match.
4892 return false;
4893}
4894
Jim Laskey03593f72006-08-01 18:29:48 +00004895
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004896/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4897/// by tblgen. Others should not call it.
4898void SelectionDAGISel::
4899SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4900 std::vector<SDOperand> InOps;
4901 std::swap(InOps, Ops);
4902
4903 Ops.push_back(InOps[0]); // input chain.
4904 Ops.push_back(InOps[1]); // input asm string.
4905
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004906 unsigned i = 2, e = InOps.size();
4907 if (InOps[e-1].getValueType() == MVT::Flag)
4908 --e; // Don't process a flag operand if it is here.
4909
4910 while (i != e) {
4911 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4912 if ((Flags & 7) != 4 /*MEM*/) {
4913 // Just skip over this operand, copying the operands verbatim.
4914 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4915 i += (Flags >> 3) + 1;
4916 } else {
4917 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4918 // Otherwise, this is a memory operand. Ask the target to select it.
4919 std::vector<SDOperand> SelOps;
4920 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004921 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004922 exit(1);
4923 }
4924
4925 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004926 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4927 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004928 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4929 i += 2;
4930 }
4931 }
4932
4933 // Add the flag input back if present.
4934 if (e != InOps.size())
4935 Ops.push_back(InOps.back());
4936}