blob: 12c5d8e18d7160a1b20d78523de680c51418370e [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
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 Cheng4ef10862006-01-23 07:01:07 +000074namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey9ff542f2006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner864635a2006-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 Lattner95255282006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-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 Lattner9f6637d2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-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 Chenga8441262006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-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 Lattner9f6637d2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000134 };
135}
Evan Cheng4ef10862006-01-23 07:01:07 +0000136
Chris Lattner1c08c712005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-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 Lattner1c08c712005-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 Lattnerf26bc8e2005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner1c08c712005-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.
174 std::map<const Value*, unsigned> ValueMap;
175
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 Lattner571e4342006-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 Brukmanedf128a2005-04-21 22:36:52 +0000190
Chris Lattner3c384492006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner1c08c712005-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 Begemanf15485a2006-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 Lattner1c08c712005-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 Begemanf15485a2006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-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 Lattnerbf209482005-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 Begemanf15485a2006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattnerbf209482005-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 Lattner1c08c712005-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 Cohen2aeaf4e2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-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 Spencerb83eb642006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner58092e32007-01-20 22:35:55 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000249
Reid Spencerb83eb642006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000254 }
255
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-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 Cohen2aeaf4e2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-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 Lattner8c494ab2006-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 =
284 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
285 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000286 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000292 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner3c384492006-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
306 // If this is a packed type, figure out what type it will decompose into
307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
309 const PackedType *PTy = cast<PackedType>(V->getType());
310 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 Lattner6cb70042006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-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 Cheng9f877882006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner1c08c712005-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
357 std::map<const Value*, SDOperand> NodeMap;
358
Chris Lattnerd3948112005-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 Begemanf15485a2006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner1c08c712005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000404
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000409
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 }
419
Chris Lattnera651cf62005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000425
Chris Lattnerd3948112005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000439 }
440
Chris Lattner571e4342006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner199862b2006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000469
470 const SDOperand &setValue(const Value *V, SDOperand NewN) {
471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
473 return N = NewN;
474 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000475
Chris Lattner864635a2006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000481
Chris Lattner571e4342006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
487
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemanf15485a2006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000497
Chris Lattner1c08c712005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Reid Spencer24d6da52007-01-21 00:29:26 +0000502 void visitScalarBinary(User &I, unsigned OpCode);
503 void visitVectorBinary(User &I, unsigned OpCode);
504 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000505 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000506 void visitAdd(User &I) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000507 if (isa<PackedType>(I.getType()))
508 visitVectorBinary(I, ISD::VADD);
509 else if (I.getType()->isFloatingPoint())
510 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000511 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000512 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000513 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000514 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000515 void visitMul(User &I) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000516 if (isa<PackedType>(I.getType()))
517 visitVectorBinary(I, ISD::VMUL);
518 else if (I.getType()->isFloatingPoint())
519 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000521 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000522 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000523 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
524 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
525 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
526 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
527 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
528 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
529 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
530 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
531 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
532 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000533 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
534 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000535 void visitICmp(User &I);
536 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000537 // Visit the conversion instructions
538 void visitTrunc(User &I);
539 void visitZExt(User &I);
540 void visitSExt(User &I);
541 void visitFPTrunc(User &I);
542 void visitFPExt(User &I);
543 void visitFPToUI(User &I);
544 void visitFPToSI(User &I);
545 void visitUIToFP(User &I);
546 void visitSIToFP(User &I);
547 void visitPtrToInt(User &I);
548 void visitIntToPtr(User &I);
549 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000550
Chris Lattner2bbd8102006-03-29 00:11:43 +0000551 void visitExtractElement(User &I);
552 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000553 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000554
Chris Lattner1c08c712005-01-07 07:47:53 +0000555 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000556 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557
558 void visitMalloc(MallocInst &I);
559 void visitFree(FreeInst &I);
560 void visitAlloca(AllocaInst &I);
561 void visitLoad(LoadInst &I);
562 void visitStore(StoreInst &I);
563 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
564 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000565 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000566 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000567 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000568
Chris Lattner1c08c712005-01-07 07:47:53 +0000569 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 void visitVAArg(VAArgInst &I);
571 void visitVAEnd(CallInst &I);
572 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000573 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000574
Chris Lattner7041ee32005-01-11 05:56:49 +0000575 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000576
577 void visitUserOp1(Instruction &I) {
578 assert(0 && "UserOp1 should not exist at instruction selection time!");
579 abort();
580 }
581 void visitUserOp2(Instruction &I) {
582 assert(0 && "UserOp2 should not exist at instruction selection time!");
583 abort();
584 }
585};
586} // end namespace llvm
587
Chris Lattner199862b2006-03-16 19:57:50 +0000588SDOperand SelectionDAGLowering::getValue(const Value *V) {
589 SDOperand &N = NodeMap[V];
590 if (N.Val) return N;
591
592 const Type *VTy = V->getType();
593 MVT::ValueType VT = TLI.getValueType(VTy);
594 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
595 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
596 visit(CE->getOpcode(), *CE);
597 assert(N.Val && "visit didn't populate the ValueMap!");
598 return N;
599 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
600 return N = DAG.getGlobalAddress(GV, VT);
601 } else if (isa<ConstantPointerNull>(C)) {
602 return N = DAG.getConstant(0, TLI.getPointerTy());
603 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000604 if (!isa<PackedType>(VTy))
605 return N = DAG.getNode(ISD::UNDEF, VT);
606
Chris Lattnerb2827b02006-03-19 00:52:58 +0000607 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000608 const PackedType *PTy = cast<PackedType>(VTy);
609 unsigned NumElements = PTy->getNumElements();
610 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
611
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000612 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000613 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
614
615 // Create a VConstant node with generic Vector type.
616 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
617 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000618 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
619 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000620 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
621 return N = DAG.getConstantFP(CFP->getValue(), VT);
622 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
623 unsigned NumElements = PTy->getNumElements();
624 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000625
626 // Now that we know the number and type of the elements, push a
627 // Constant or ConstantFP node onto the ops list for each element of
628 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000629 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000630 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000631 for (unsigned i = 0; i != NumElements; ++i)
632 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000633 } else {
634 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
635 SDOperand Op;
636 if (MVT::isFloatingPoint(PVT))
637 Op = DAG.getConstantFP(0, PVT);
638 else
639 Op = DAG.getConstant(0, PVT);
640 Ops.assign(NumElements, Op);
641 }
642
Chris Lattnerb2827b02006-03-19 00:52:58 +0000643 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000644 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
645 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000646 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000647 } else {
648 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000649 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000650 }
651 }
652
653 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
654 std::map<const AllocaInst*, int>::iterator SI =
655 FuncInfo.StaticAllocaMap.find(AI);
656 if (SI != FuncInfo.StaticAllocaMap.end())
657 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
658 }
659
660 std::map<const Value*, unsigned>::const_iterator VMI =
661 FuncInfo.ValueMap.find(V);
662 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
663
664 unsigned InReg = VMI->second;
665
666 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000667 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000668 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000669 // Source must be expanded. This input value is actually coming from the
670 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000671 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
672 unsigned NumVals = TLI.getNumElements(VT);
673 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
674 if (NumVals == 1)
675 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
676 else {
677 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
678 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
679 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
680 }
681 } else {
682 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
683 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
684 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
685 N = MVT::isFloatingPoint(VT)
686 ? DAG.getNode(ISD::FP_ROUND, VT, N)
687 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000688 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000689 } else {
690 // Otherwise, if this is a vector, make it available as a generic vector
691 // here.
692 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000693 const PackedType *PTy = cast<PackedType>(VTy);
694 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000695 PTyLegalElementVT);
696
697 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000698 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000699 if (PTyElementVT == PTyLegalElementVT) {
700 // If the value types are legal, just VBUILD the CopyFromReg nodes.
701 for (unsigned i = 0; i != NE; ++i)
702 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
703 PTyElementVT));
704 } else if (PTyElementVT < PTyLegalElementVT) {
705 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
706 for (unsigned i = 0; i != NE; ++i) {
707 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
708 PTyElementVT);
709 if (MVT::isFloatingPoint(PTyElementVT))
710 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
711 else
712 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
713 Ops.push_back(Op);
714 }
715 } else {
716 // If the register was expanded, use BUILD_PAIR.
717 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
718 for (unsigned i = 0; i != NE/2; ++i) {
719 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
720 PTyElementVT);
721 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
722 PTyElementVT);
723 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
724 }
725 }
726
727 Ops.push_back(DAG.getConstant(NE, MVT::i32));
728 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000729 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000730
731 // Finally, use a VBIT_CONVERT to make this available as the appropriate
732 // vector type.
733 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
734 DAG.getConstant(PTy->getNumElements(),
735 MVT::i32),
736 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000737 }
738
739 return N;
740}
741
742
Chris Lattner1c08c712005-01-07 07:47:53 +0000743void SelectionDAGLowering::visitRet(ReturnInst &I) {
744 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000745 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000746 return;
747 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000748 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000749 NewValues.push_back(getRoot());
750 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
751 SDOperand RetOp = getValue(I.getOperand(i));
752
753 // If this is an integer return value, we need to promote it ourselves to
754 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
755 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000756 // FIXME: C calling convention requires the return type to be promoted to
757 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000758 if (MVT::isInteger(RetOp.getValueType()) &&
759 RetOp.getValueType() < MVT::i64) {
760 MVT::ValueType TmpVT;
761 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
762 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
763 else
764 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000765 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000766 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000767 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
768 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000769 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
770 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000771 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000772 }
773 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000774 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000775 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000776 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
777 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000778}
779
Chris Lattner571e4342006-10-27 21:36:01 +0000780/// ExportFromCurrentBlock - If this condition isn't known to be exported from
781/// the current basic block, add it to ValueMap now so that we'll get a
782/// CopyTo/FromReg.
783void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
784 // No need to export constants.
785 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
786
787 // Already exported?
788 if (FuncInfo.isExportedInst(V)) return;
789
790 unsigned Reg = FuncInfo.InitializeRegForValue(V);
791 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
792}
793
Chris Lattner8c494ab2006-10-27 23:50:33 +0000794bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
795 const BasicBlock *FromBB) {
796 // The operands of the setcc have to be in this block. We don't know
797 // how to export them from some other block.
798 if (Instruction *VI = dyn_cast<Instruction>(V)) {
799 // Can export from current BB.
800 if (VI->getParent() == FromBB)
801 return true;
802
803 // Is already exported, noop.
804 return FuncInfo.isExportedInst(V);
805 }
806
807 // If this is an argument, we can export it if the BB is the entry block or
808 // if it is already exported.
809 if (isa<Argument>(V)) {
810 if (FromBB == &FromBB->getParent()->getEntryBlock())
811 return true;
812
813 // Otherwise, can only export this if it is already exported.
814 return FuncInfo.isExportedInst(V);
815 }
816
817 // Otherwise, constants can always be exported.
818 return true;
819}
820
Chris Lattner6a586c82006-10-29 21:01:20 +0000821static bool InBlock(const Value *V, const BasicBlock *BB) {
822 if (const Instruction *I = dyn_cast<Instruction>(V))
823 return I->getParent() == BB;
824 return true;
825}
826
Chris Lattner571e4342006-10-27 21:36:01 +0000827/// FindMergedConditions - If Cond is an expression like
828void SelectionDAGLowering::FindMergedConditions(Value *Cond,
829 MachineBasicBlock *TBB,
830 MachineBasicBlock *FBB,
831 MachineBasicBlock *CurBB,
832 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000833 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000834 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000835
Reid Spencere4d87aa2006-12-23 06:05:41 +0000836 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
837 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000838 BOp->getParent() != CurBB->getBasicBlock() ||
839 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
840 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000841 const BasicBlock *BB = CurBB->getBasicBlock();
842
Reid Spencere4d87aa2006-12-23 06:05:41 +0000843 // If the leaf of the tree is a comparison, merge the condition into
844 // the caseblock.
845 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
846 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000847 // how to export them from some other block. If this is the first block
848 // of the sequence, no exporting is needed.
849 (CurBB == CurMBB ||
850 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
851 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000852 BOp = cast<Instruction>(Cond);
853 ISD::CondCode Condition;
854 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
855 switch (IC->getPredicate()) {
856 default: assert(0 && "Unknown icmp predicate opcode!");
857 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
858 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
859 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
860 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
861 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
862 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
863 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
864 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
865 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
866 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
867 }
868 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
869 ISD::CondCode FPC, FOC;
870 switch (FC->getPredicate()) {
871 default: assert(0 && "Unknown fcmp predicate opcode!");
872 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
873 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
874 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
875 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
876 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
877 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
878 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
879 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
880 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
881 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
882 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
883 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
884 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
885 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
886 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
887 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
888 }
889 if (FiniteOnlyFPMath())
890 Condition = FOC;
891 else
892 Condition = FPC;
893 } else {
894 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000895 }
896
Chris Lattner571e4342006-10-27 21:36:01 +0000897 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
898 BOp->getOperand(1), TBB, FBB, CurBB);
899 SwitchCases.push_back(CB);
900 return;
901 }
902
903 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000904 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000905 TBB, FBB, CurBB);
906 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000907 return;
908 }
909
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000910
911 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000912 MachineFunction::iterator BBI = CurBB;
913 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
914 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
915
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000916 if (Opc == Instruction::Or) {
917 // Codegen X | Y as:
918 // jmp_if_X TBB
919 // jmp TmpBB
920 // TmpBB:
921 // jmp_if_Y TBB
922 // jmp FBB
923 //
Chris Lattner571e4342006-10-27 21:36:01 +0000924
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000925 // Emit the LHS condition.
926 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
927
928 // Emit the RHS condition into TmpBB.
929 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
930 } else {
931 assert(Opc == Instruction::And && "Unknown merge op!");
932 // Codegen X & Y as:
933 // jmp_if_X TmpBB
934 // jmp FBB
935 // TmpBB:
936 // jmp_if_Y TBB
937 // jmp FBB
938 //
939 // This requires creation of TmpBB after CurBB.
940
941 // Emit the LHS condition.
942 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
943
944 // Emit the RHS condition into TmpBB.
945 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
946 }
Chris Lattner571e4342006-10-27 21:36:01 +0000947}
948
Chris Lattnerdf19f272006-10-31 22:37:42 +0000949/// If the set of cases should be emitted as a series of branches, return true.
950/// If we should emit this as a bunch of and/or'd together conditions, return
951/// false.
952static bool
953ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
954 if (Cases.size() != 2) return true;
955
Chris Lattner0ccb5002006-10-31 23:06:00 +0000956 // If this is two comparisons of the same values or'd or and'd together, they
957 // will get folded into a single comparison, so don't emit two blocks.
958 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
959 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
960 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
961 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
962 return false;
963 }
964
Chris Lattnerdf19f272006-10-31 22:37:42 +0000965 return true;
966}
967
Chris Lattner1c08c712005-01-07 07:47:53 +0000968void SelectionDAGLowering::visitBr(BranchInst &I) {
969 // Update machine-CFG edges.
970 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000971
972 // Figure out which block is immediately after the current one.
973 MachineBasicBlock *NextBlock = 0;
974 MachineFunction::iterator BBI = CurMBB;
975 if (++BBI != CurMBB->getParent()->end())
976 NextBlock = BBI;
977
978 if (I.isUnconditional()) {
979 // If this is not a fall-through branch, emit the branch.
980 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000981 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000982 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000983
Chris Lattner57ab6592006-10-24 17:57:59 +0000984 // Update machine-CFG edges.
985 CurMBB->addSuccessor(Succ0MBB);
986
987 return;
988 }
989
990 // If this condition is one of the special cases we handle, do special stuff
991 // now.
992 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000993 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000994
995 // If this is a series of conditions that are or'd or and'd together, emit
996 // this as a sequence of branches instead of setcc's with and/or operations.
997 // For example, instead of something like:
998 // cmp A, B
999 // C = seteq
1000 // cmp D, E
1001 // F = setle
1002 // or C, F
1003 // jnz foo
1004 // Emit:
1005 // cmp A, B
1006 // je foo
1007 // cmp D, E
1008 // jle foo
1009 //
1010 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1011 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001012 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001013 BOp->getOpcode() == Instruction::Or)) {
1014 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001015 // If the compares in later blocks need to use values not currently
1016 // exported from this block, export them now. This block should always
1017 // be the first entry.
1018 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1019
Chris Lattnerdf19f272006-10-31 22:37:42 +00001020 // Allow some cases to be rejected.
1021 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001022 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1023 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1024 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1025 }
1026
1027 // Emit the branch for this block.
1028 visitSwitchCase(SwitchCases[0]);
1029 SwitchCases.erase(SwitchCases.begin());
1030 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001031 }
1032
Chris Lattner0ccb5002006-10-31 23:06:00 +00001033 // Okay, we decided not to do this, remove any inserted MBB's and clear
1034 // SwitchCases.
1035 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1036 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1037
Chris Lattnerdf19f272006-10-31 22:37:42 +00001038 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001039 }
1040 }
Chris Lattner24525952006-10-24 18:07:37 +00001041
1042 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001043 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001044 Succ0MBB, Succ1MBB, CurMBB);
1045 // Use visitSwitchCase to actually insert the fast branch sequence for this
1046 // cond branch.
1047 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001048}
1049
Nate Begemanf15485a2006-03-27 01:32:24 +00001050/// visitSwitchCase - Emits the necessary code to represent a single node in
1051/// the binary search tree resulting from lowering a switch instruction.
1052void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001053 SDOperand Cond;
1054 SDOperand CondLHS = getValue(CB.CmpLHS);
1055
Chris Lattner571e4342006-10-27 21:36:01 +00001056 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1057 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001058 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001059 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001060 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001061 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1062 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1063 } else
1064 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001065
1066 // Set NextBlock to be the MBB immediately after the current one, if any.
1067 // This is used to avoid emitting unnecessary branches to the next block.
1068 MachineBasicBlock *NextBlock = 0;
1069 MachineFunction::iterator BBI = CurMBB;
1070 if (++BBI != CurMBB->getParent()->end())
1071 NextBlock = BBI;
1072
1073 // If the lhs block is the next block, invert the condition so that we can
1074 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001075 if (CB.TrueBB == NextBlock) {
1076 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001077 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1078 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1079 }
1080 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001081 DAG.getBasicBlock(CB.TrueBB));
1082 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001083 DAG.setRoot(BrCond);
1084 else
1085 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001086 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001087 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001088 CurMBB->addSuccessor(CB.TrueBB);
1089 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001090}
1091
Nate Begeman37efe672006-04-22 18:53:45 +00001092void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001093 // Emit the code for the jump table
1094 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001095 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1096 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1097 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1098 Table, Index));
1099 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001100}
1101
Nate Begemanf15485a2006-03-27 01:32:24 +00001102void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1103 // Figure out which block is immediately after the current one.
1104 MachineBasicBlock *NextBlock = 0;
1105 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001106
Nate Begemanf15485a2006-03-27 01:32:24 +00001107 if (++BBI != CurMBB->getParent()->end())
1108 NextBlock = BBI;
1109
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001110 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1111
Nate Begemanf15485a2006-03-27 01:32:24 +00001112 // If there is only the default destination, branch to it if it is not the
1113 // next basic block. Otherwise, just fall through.
1114 if (I.getNumOperands() == 2) {
1115 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001116
Nate Begemanf15485a2006-03-27 01:32:24 +00001117 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001118 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001119 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001120 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001121
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001122 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001123 return;
1124 }
1125
1126 // If there are any non-default case statements, create a vector of Cases
1127 // representing each one, and sort the vector so that we can efficiently
1128 // create a binary search tree from them.
1129 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001130
Nate Begemanf15485a2006-03-27 01:32:24 +00001131 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1132 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1133 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1134 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001135
Nate Begemanf15485a2006-03-27 01:32:24 +00001136 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1137
1138 // Get the Value to be switched on and default basic blocks, which will be
1139 // inserted into CaseBlock records, representing basic blocks in the binary
1140 // search tree.
1141 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001142
1143 // Get the MachineFunction which holds the current MBB. This is used during
1144 // emission of jump tables, and when inserting any additional MBBs necessary
1145 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001146 MachineFunction *CurMF = CurMBB->getParent();
1147 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001148
1149 // If the switch has few cases (two or less) emit a series of specific
1150 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001151 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001152 // TODO: If any two of the cases has the same destination, and if one value
1153 // is the same as the other, but has one bit unset that the other has set,
1154 // use bit manipulation to do two compares at once. For example:
1155 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1156
Chris Lattnerb3543432006-10-23 18:38:22 +00001157 // Rearrange the case blocks so that the last one falls through if possible.
1158 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1159 // The last case block won't fall through into 'NextBlock' if we emit the
1160 // branches in this order. See if rearranging a case value would help.
1161 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1162 if (Cases[i].second == NextBlock) {
1163 std::swap(Cases[i], Cases.back());
1164 break;
1165 }
1166 }
1167 }
1168
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001169 // Create a CaseBlock record representing a conditional branch to
1170 // the Case's target mbb if the value being switched on SV is equal
1171 // to C.
1172 MachineBasicBlock *CurBlock = CurMBB;
1173 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1174 MachineBasicBlock *FallThrough;
1175 if (i != e-1) {
1176 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1177 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1178 } else {
1179 // If the last case doesn't match, go to the default block.
1180 FallThrough = Default;
1181 }
1182
1183 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1184 Cases[i].second, FallThrough, CurBlock);
1185
1186 // If emitting the first comparison, just call visitSwitchCase to emit the
1187 // code into the current block. Otherwise, push the CaseBlock onto the
1188 // vector to be later processed by SDISel, and insert the node's MBB
1189 // before the next MBB.
1190 if (CurBlock == CurMBB)
1191 visitSwitchCase(CB);
1192 else
1193 SwitchCases.push_back(CB);
1194
1195 CurBlock = FallThrough;
1196 }
1197 return;
1198 }
Nate Begeman37efe672006-04-22 18:53:45 +00001199
Nate Begeman17c275f2006-05-08 16:51:36 +00001200 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1201 // target supports indirect branches, then emit a jump table rather than
1202 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001203 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1204 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001205 Cases.size() > 5) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001206 uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1207 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001208 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1209
Nate Begeman17c275f2006-05-08 16:51:36 +00001210 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001211 // Create a new basic block to hold the code for loading the address
1212 // of the jump table, and jumping to it. Update successor information;
1213 // we will either branch to the default case for the switch, or the jump
1214 // table.
1215 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1216 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1217 CurMBB->addSuccessor(Default);
1218 CurMBB->addSuccessor(JumpTableBB);
1219
1220 // Subtract the lowest switch case value from the value being switched on
1221 // and conditional branch to default mbb if the result is greater than the
1222 // difference between smallest and largest cases.
1223 SDOperand SwitchOp = getValue(SV);
1224 MVT::ValueType VT = SwitchOp.getValueType();
1225 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1226 DAG.getConstant(First, VT));
1227
1228 // The SDNode we just created, which holds the value being switched on
1229 // minus the the smallest case value, needs to be copied to a virtual
1230 // register so it can be used as an index into the jump table in a
1231 // subsequent basic block. This value may be smaller or larger than the
1232 // target's pointer type, and therefore require extension or truncating.
1233 if (VT > TLI.getPointerTy())
1234 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1235 else
1236 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001237
Nate Begeman37efe672006-04-22 18:53:45 +00001238 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1239 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1240
1241 // Emit the range check for the jump table, and branch to the default
1242 // block for the switch statement if the value being switched on exceeds
1243 // the largest case in the switch.
1244 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1245 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1246 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1247 DAG.getBasicBlock(Default)));
1248
Nate Begemanf4360a42006-05-03 03:48:02 +00001249 // Build a vector of destination BBs, corresponding to each target
1250 // of the jump table. If the value of the jump table slot corresponds to
1251 // a case statement, push the case's BB onto the vector, otherwise, push
1252 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001253 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001254 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001255 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001256 if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001257 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001258 ++ii;
1259 } else {
1260 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001261 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001262
Chris Lattner8c494ab2006-10-27 23:50:33 +00001263 // Update successor info. Add one edge to each unique successor.
1264 // Vector bool would be better, but vector<bool> is really slow.
1265 std::vector<unsigned char> SuccsHandled;
1266 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1267
Chris Lattnerc66764c2006-09-10 06:36:57 +00001268 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001269 E = DestBBs.end(); I != E; ++I) {
1270 if (!SuccsHandled[(*I)->getNumber()]) {
1271 SuccsHandled[(*I)->getNumber()] = true;
1272 JumpTableBB->addSuccessor(*I);
1273 }
1274 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001275
1276 // Create a jump table index for this jump table, or return an existing
1277 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001278 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1279
1280 // Set the jump table information so that we can codegen it as a second
1281 // MachineBasicBlock
1282 JT.Reg = JumpTableReg;
1283 JT.JTI = JTI;
1284 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001285 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001286 return;
1287 }
1288 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001289
1290 // Push the initial CaseRec onto the worklist
1291 std::vector<CaseRec> CaseVec;
1292 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1293
1294 while (!CaseVec.empty()) {
1295 // Grab a record representing a case range to process off the worklist
1296 CaseRec CR = CaseVec.back();
1297 CaseVec.pop_back();
1298
1299 // Size is the number of Cases represented by this range. If Size is 1,
1300 // then we are processing a leaf of the binary search tree. Otherwise,
1301 // we need to pick a pivot, and push left and right ranges onto the
1302 // worklist.
1303 unsigned Size = CR.Range.second - CR.Range.first;
1304
1305 if (Size == 1) {
1306 // Create a CaseBlock record representing a conditional branch to
1307 // the Case's target mbb if the value being switched on SV is equal
1308 // to C. Otherwise, branch to default.
1309 Constant *C = CR.Range.first->first;
1310 MachineBasicBlock *Target = CR.Range.first->second;
1311 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1312 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001313
Nate Begemanf15485a2006-03-27 01:32:24 +00001314 // If the MBB representing the leaf node is the current MBB, then just
1315 // call visitSwitchCase to emit the code into the current block.
1316 // Otherwise, push the CaseBlock onto the vector to be later processed
1317 // by SDISel, and insert the node's MBB before the next MBB.
1318 if (CR.CaseBB == CurMBB)
1319 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001320 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001321 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001322 } else {
1323 // split case range at pivot
1324 CaseItr Pivot = CR.Range.first + (Size / 2);
1325 CaseRange LHSR(CR.Range.first, Pivot);
1326 CaseRange RHSR(Pivot, CR.Range.second);
1327 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001328 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001329
Nate Begemanf15485a2006-03-27 01:32:24 +00001330 // We know that we branch to the LHS if the Value being switched on is
1331 // less than the Pivot value, C. We use this to optimize our binary
1332 // tree a bit, by recognizing that if SV is greater than or equal to the
1333 // LHS's Case Value, and that Case Value is exactly one less than the
1334 // Pivot's Value, then we can branch directly to the LHS's Target,
1335 // rather than creating a leaf node for it.
1336 if ((LHSR.second - LHSR.first) == 1 &&
1337 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001338 cast<ConstantInt>(C)->getZExtValue() ==
1339 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001340 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001341 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001342 TrueBB = new MachineBasicBlock(LLVMBB);
1343 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1344 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001345 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001346
Nate Begemanf15485a2006-03-27 01:32:24 +00001347 // Similar to the optimization above, if the Value being switched on is
1348 // known to be less than the Constant CR.LT, and the current Case Value
1349 // is CR.LT - 1, then we can branch directly to the target block for
1350 // the current Case Value, rather than emitting a RHS leaf node for it.
1351 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001352 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1353 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001354 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001355 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001356 FalseBB = new MachineBasicBlock(LLVMBB);
1357 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1358 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001359 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001360
Nate Begemanf15485a2006-03-27 01:32:24 +00001361 // Create a CaseBlock record representing a conditional branch to
1362 // the LHS node if the value being switched on SV is less than C.
1363 // Otherwise, branch to LHS.
Reid Spencer8c57dfb2007-01-03 04:25:33 +00001364 ISD::CondCode CC = ISD::SETLT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001365 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001366
Nate Begemanf15485a2006-03-27 01:32:24 +00001367 if (CR.CaseBB == CurMBB)
1368 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001369 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001370 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001371 }
1372 }
1373}
1374
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001375void SelectionDAGLowering::visitSub(User &I) {
1376 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001377 const Type *Ty = I.getType();
1378 if (isa<PackedType>(Ty)) {
1379 visitVectorBinary(I, ISD::VSUB);
1380 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001381 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1382 if (CFP->isExactlyValue(-0.0)) {
1383 SDOperand Op2 = getValue(I.getOperand(1));
1384 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1385 return;
1386 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001387 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001388 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001389 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001390}
1391
Reid Spencer24d6da52007-01-21 00:29:26 +00001392void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001393 SDOperand Op1 = getValue(I.getOperand(0));
1394 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001395
1396 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001397}
1398
Reid Spencer24d6da52007-01-21 00:29:26 +00001399void
1400SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1401 assert(isa<PackedType>(I.getType()));
1402 const PackedType *Ty = cast<PackedType>(I.getType());
1403 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001404
Reid Spencer24d6da52007-01-21 00:29:26 +00001405 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1406 getValue(I.getOperand(0)),
1407 getValue(I.getOperand(1)),
1408 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1409 Typ));
1410}
1411
1412void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1413 unsigned VectorOp) {
1414 if (isa<PackedType>(I.getType()))
1415 visitVectorBinary(I, VectorOp);
1416 else
1417 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001418}
Chris Lattner2c49f272005-01-19 22:31:21 +00001419
Nate Begemane21ea612005-11-18 07:42:56 +00001420void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1421 SDOperand Op1 = getValue(I.getOperand(0));
1422 SDOperand Op2 = getValue(I.getOperand(1));
1423
1424 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1425
Chris Lattner1c08c712005-01-07 07:47:53 +00001426 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1427}
1428
Reid Spencer45fb3f32006-11-20 01:22:35 +00001429void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001430 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1431 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1432 predicate = IC->getPredicate();
1433 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1434 predicate = ICmpInst::Predicate(IC->getPredicate());
1435 SDOperand Op1 = getValue(I.getOperand(0));
1436 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001437 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001438 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001439 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1440 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1441 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1442 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1443 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1444 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1445 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1446 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1447 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1448 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1449 default:
1450 assert(!"Invalid ICmp predicate value");
1451 Opcode = ISD::SETEQ;
1452 break;
1453 }
1454 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1455}
1456
1457void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001458 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1459 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1460 predicate = FC->getPredicate();
1461 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1462 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001463 SDOperand Op1 = getValue(I.getOperand(0));
1464 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001465 ISD::CondCode Condition, FOC, FPC;
1466 switch (predicate) {
1467 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1468 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1469 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1470 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1471 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1472 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1473 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1474 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1475 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1476 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1477 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1478 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1479 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1480 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1481 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1482 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1483 default:
1484 assert(!"Invalid FCmp predicate value");
1485 FOC = FPC = ISD::SETFALSE;
1486 break;
1487 }
1488 if (FiniteOnlyFPMath())
1489 Condition = FOC;
1490 else
1491 Condition = FPC;
1492 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001493}
1494
1495void SelectionDAGLowering::visitSelect(User &I) {
1496 SDOperand Cond = getValue(I.getOperand(0));
1497 SDOperand TrueVal = getValue(I.getOperand(1));
1498 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001499 if (!isa<PackedType>(I.getType())) {
1500 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1501 TrueVal, FalseVal));
1502 } else {
1503 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1504 *(TrueVal.Val->op_end()-2),
1505 *(TrueVal.Val->op_end()-1)));
1506 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001507}
1508
Reid Spencer3da59db2006-11-27 01:05:10 +00001509
1510void SelectionDAGLowering::visitTrunc(User &I) {
1511 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1512 SDOperand N = getValue(I.getOperand(0));
1513 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1514 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1515}
1516
1517void SelectionDAGLowering::visitZExt(User &I) {
1518 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1519 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1520 SDOperand N = getValue(I.getOperand(0));
1521 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1522 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1523}
1524
1525void SelectionDAGLowering::visitSExt(User &I) {
1526 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1527 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1528 SDOperand N = getValue(I.getOperand(0));
1529 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1530 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1531}
1532
1533void SelectionDAGLowering::visitFPTrunc(User &I) {
1534 // FPTrunc is never a no-op cast, no need to check
1535 SDOperand N = getValue(I.getOperand(0));
1536 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1537 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1538}
1539
1540void SelectionDAGLowering::visitFPExt(User &I){
1541 // FPTrunc is never a no-op cast, no need to check
1542 SDOperand N = getValue(I.getOperand(0));
1543 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1544 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1545}
1546
1547void SelectionDAGLowering::visitFPToUI(User &I) {
1548 // FPToUI is never a no-op cast, no need to check
1549 SDOperand N = getValue(I.getOperand(0));
1550 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1551 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1552}
1553
1554void SelectionDAGLowering::visitFPToSI(User &I) {
1555 // FPToSI is never a no-op cast, no need to check
1556 SDOperand N = getValue(I.getOperand(0));
1557 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1558 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1559}
1560
1561void SelectionDAGLowering::visitUIToFP(User &I) {
1562 // UIToFP is never a no-op cast, no need to check
1563 SDOperand N = getValue(I.getOperand(0));
1564 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1565 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1566}
1567
1568void SelectionDAGLowering::visitSIToFP(User &I){
1569 // UIToFP is never a no-op cast, no need to check
1570 SDOperand N = getValue(I.getOperand(0));
1571 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1572 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1573}
1574
1575void SelectionDAGLowering::visitPtrToInt(User &I) {
1576 // What to do depends on the size of the integer and the size of the pointer.
1577 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001578 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001579 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001580 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001581 SDOperand Result;
1582 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1583 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1584 else
1585 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1586 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1587 setValue(&I, Result);
1588}
Chris Lattner1c08c712005-01-07 07:47:53 +00001589
Reid Spencer3da59db2006-11-27 01:05:10 +00001590void SelectionDAGLowering::visitIntToPtr(User &I) {
1591 // What to do depends on the size of the integer and the size of the pointer.
1592 // We can either truncate, zero extend, or no-op, accordingly.
1593 SDOperand N = getValue(I.getOperand(0));
1594 MVT::ValueType SrcVT = N.getValueType();
1595 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1597 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1598 else
1599 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1600 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1601}
1602
1603void SelectionDAGLowering::visitBitCast(User &I) {
1604 SDOperand N = getValue(I.getOperand(0));
1605 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001606 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001607 // This is a cast to a vector from something else.
1608 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001609 const PackedType *DestTy = cast<PackedType>(I.getType());
1610 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1611 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1612 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1613 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001614 return;
1615 }
1616 MVT::ValueType SrcVT = N.getValueType();
1617 if (SrcVT == MVT::Vector) {
1618 // This is a cast from a vctor to something else.
1619 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001620 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001621 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001622 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001623
1624 // BitCast assures us that source and destination are the same size so this
1625 // is either a BIT_CONVERT or a no-op.
1626 if (DestVT != N.getValueType())
1627 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1628 else
1629 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001630}
1631
Chris Lattner2bbd8102006-03-29 00:11:43 +00001632void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001633 SDOperand InVec = getValue(I.getOperand(0));
1634 SDOperand InVal = getValue(I.getOperand(1));
1635 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1636 getValue(I.getOperand(2)));
1637
Chris Lattner2332b9f2006-03-19 01:17:20 +00001638 SDOperand Num = *(InVec.Val->op_end()-2);
1639 SDOperand Typ = *(InVec.Val->op_end()-1);
1640 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1641 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001642}
1643
Chris Lattner2bbd8102006-03-29 00:11:43 +00001644void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001645 SDOperand InVec = getValue(I.getOperand(0));
1646 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1647 getValue(I.getOperand(1)));
1648 SDOperand Typ = *(InVec.Val->op_end()-1);
1649 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1650 TLI.getValueType(I.getType()), InVec, InIdx));
1651}
Chris Lattnerc7029802006-03-18 01:44:44 +00001652
Chris Lattner3e104b12006-04-08 04:15:24 +00001653void SelectionDAGLowering::visitShuffleVector(User &I) {
1654 SDOperand V1 = getValue(I.getOperand(0));
1655 SDOperand V2 = getValue(I.getOperand(1));
1656 SDOperand Mask = getValue(I.getOperand(2));
1657
1658 SDOperand Num = *(V1.Val->op_end()-2);
1659 SDOperand Typ = *(V2.Val->op_end()-1);
1660 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1661 V1, V2, Mask, Num, Typ));
1662}
1663
1664
Chris Lattner1c08c712005-01-07 07:47:53 +00001665void SelectionDAGLowering::visitGetElementPtr(User &I) {
1666 SDOperand N = getValue(I.getOperand(0));
1667 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001668
1669 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1670 OI != E; ++OI) {
1671 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001672 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001673 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001674 if (Field) {
1675 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001676 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001677 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001678 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001679 }
1680 Ty = StTy->getElementType(Field);
1681 } else {
1682 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001683
Chris Lattner7c0104b2005-11-09 04:45:33 +00001684 // If this is a constant subscript, handle it quickly.
1685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001686 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001687 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001688 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001689 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1690 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001691 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001692
1693 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001694 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001695 SDOperand IdxN = getValue(Idx);
1696
1697 // If the index is smaller or larger than intptr_t, truncate or extend
1698 // it.
1699 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001700 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001701 } else if (IdxN.getValueType() > N.getValueType())
1702 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1703
1704 // If this is a multiply by a power of two, turn it into a shl
1705 // immediately. This is a very common case.
1706 if (isPowerOf2_64(ElementSize)) {
1707 unsigned Amt = Log2_64(ElementSize);
1708 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001709 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001710 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1711 continue;
1712 }
1713
1714 SDOperand Scale = getIntPtrConstant(ElementSize);
1715 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1716 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001717 }
1718 }
1719 setValue(&I, N);
1720}
1721
1722void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1723 // If this is a fixed sized alloca in the entry block of the function,
1724 // allocate it statically on the stack.
1725 if (FuncInfo.StaticAllocaMap.count(&I))
1726 return; // getValue will auto-populate this.
1727
1728 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001729 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001730 unsigned Align =
1731 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1732 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001733
1734 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001735 MVT::ValueType IntPtr = TLI.getPointerTy();
1736 if (IntPtr < AllocSize.getValueType())
1737 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1738 else if (IntPtr > AllocSize.getValueType())
1739 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001740
Chris Lattner68cd65e2005-01-22 23:04:37 +00001741 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001742 getIntPtrConstant(TySize));
1743
1744 // Handle alignment. If the requested alignment is less than or equal to the
1745 // stack alignment, ignore it and round the size of the allocation up to the
1746 // stack alignment size. If the size is greater than the stack alignment, we
1747 // note this in the DYNAMIC_STACKALLOC node.
1748 unsigned StackAlign =
1749 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1750 if (Align <= StackAlign) {
1751 Align = 0;
1752 // Add SA-1 to the size.
1753 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1754 getIntPtrConstant(StackAlign-1));
1755 // Mask out the low bits for alignment purposes.
1756 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1757 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1758 }
1759
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001760 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001761 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1762 MVT::Other);
1763 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001764 DAG.setRoot(setValue(&I, DSA).getValue(1));
1765
1766 // Inform the Frame Information that we have just allocated a variable-sized
1767 // object.
1768 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1769}
1770
Chris Lattner1c08c712005-01-07 07:47:53 +00001771void SelectionDAGLowering::visitLoad(LoadInst &I) {
1772 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001773
Chris Lattnerd3948112005-01-17 22:19:26 +00001774 SDOperand Root;
1775 if (I.isVolatile())
1776 Root = getRoot();
1777 else {
1778 // Do not serialize non-volatile loads against each other.
1779 Root = DAG.getRoot();
1780 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001781
Evan Cheng466685d2006-10-09 20:57:25 +00001782 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001783 Root, I.isVolatile()));
1784}
1785
1786SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001787 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001788 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001789 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001790 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001791 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001792 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1793 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001794 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001795 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001796 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001797
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001798 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001799 DAG.setRoot(L.getValue(1));
1800 else
1801 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001802
1803 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001804}
1805
1806
1807void SelectionDAGLowering::visitStore(StoreInst &I) {
1808 Value *SrcV = I.getOperand(0);
1809 SDOperand Src = getValue(SrcV);
1810 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001811 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001812 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001813}
1814
Chris Lattner0eade312006-03-24 02:22:33 +00001815/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1816/// access memory and has no other side effects at all.
1817static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1818#define GET_NO_MEMORY_INTRINSICS
1819#include "llvm/Intrinsics.gen"
1820#undef GET_NO_MEMORY_INTRINSICS
1821 return false;
1822}
1823
Chris Lattnere58a7802006-04-02 03:41:14 +00001824// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1825// have any side-effects or if it only reads memory.
1826static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1827#define GET_SIDE_EFFECT_INFO
1828#include "llvm/Intrinsics.gen"
1829#undef GET_SIDE_EFFECT_INFO
1830 return false;
1831}
1832
Chris Lattner0eade312006-03-24 02:22:33 +00001833/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1834/// node.
1835void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1836 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001837 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001838 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001839
1840 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001841 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001842 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1843 if (OnlyLoad) {
1844 // We don't need to serialize loads against other loads.
1845 Ops.push_back(DAG.getRoot());
1846 } else {
1847 Ops.push_back(getRoot());
1848 }
1849 }
Chris Lattner0eade312006-03-24 02:22:33 +00001850
1851 // Add the intrinsic ID as an integer operand.
1852 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1853
1854 // Add all operands of the call to the operand list.
1855 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1856 SDOperand Op = getValue(I.getOperand(i));
1857
1858 // If this is a vector type, force it to the right packed type.
1859 if (Op.getValueType() == MVT::Vector) {
1860 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1861 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1862
1863 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1864 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1865 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1866 }
1867
1868 assert(TLI.isTypeLegal(Op.getValueType()) &&
1869 "Intrinsic uses a non-legal type?");
1870 Ops.push_back(Op);
1871 }
1872
1873 std::vector<MVT::ValueType> VTs;
1874 if (I.getType() != Type::VoidTy) {
1875 MVT::ValueType VT = TLI.getValueType(I.getType());
1876 if (VT == MVT::Vector) {
1877 const PackedType *DestTy = cast<PackedType>(I.getType());
1878 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1879
1880 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1881 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1882 }
1883
1884 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1885 VTs.push_back(VT);
1886 }
1887 if (HasChain)
1888 VTs.push_back(MVT::Other);
1889
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001890 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1891
Chris Lattner0eade312006-03-24 02:22:33 +00001892 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001893 SDOperand Result;
1894 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001895 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1896 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001897 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001898 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1899 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001900 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001901 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1902 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001903
Chris Lattnere58a7802006-04-02 03:41:14 +00001904 if (HasChain) {
1905 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1906 if (OnlyLoad)
1907 PendingLoads.push_back(Chain);
1908 else
1909 DAG.setRoot(Chain);
1910 }
Chris Lattner0eade312006-03-24 02:22:33 +00001911 if (I.getType() != Type::VoidTy) {
1912 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1913 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1914 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1915 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1916 DAG.getValueType(EVT));
1917 }
1918 setValue(&I, Result);
1919 }
1920}
1921
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001922/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1923/// we want to emit this as a call to a named external function, return the name
1924/// otherwise lower it and return null.
1925const char *
1926SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1927 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001928 default:
1929 // By default, turn this into a target intrinsic node.
1930 visitTargetIntrinsic(I, Intrinsic);
1931 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001932 case Intrinsic::vastart: visitVAStart(I); return 0;
1933 case Intrinsic::vaend: visitVAEnd(I); return 0;
1934 case Intrinsic::vacopy: visitVACopy(I); return 0;
1935 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1936 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1937 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001938 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001939 break;
1940 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001941 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001942 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001943 case Intrinsic::memcpy_i32:
1944 case Intrinsic::memcpy_i64:
1945 visitMemIntrinsic(I, ISD::MEMCPY);
1946 return 0;
1947 case Intrinsic::memset_i32:
1948 case Intrinsic::memset_i64:
1949 visitMemIntrinsic(I, ISD::MEMSET);
1950 return 0;
1951 case Intrinsic::memmove_i32:
1952 case Intrinsic::memmove_i64:
1953 visitMemIntrinsic(I, ISD::MEMMOVE);
1954 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001955
Chris Lattner86cb6432005-12-13 17:40:33 +00001956 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001957 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001958 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001959 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001960 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001961
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001962 Ops[0] = getRoot();
1963 Ops[1] = getValue(SPI.getLineValue());
1964 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001965
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001966 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001967 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001968 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1969
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001970 Ops[3] = DAG.getString(CompileUnit->getFileName());
1971 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001972
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001973 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001974 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001975
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001976 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001977 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001978 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001979 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001980 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001981 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
1982 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00001983 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001984 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001985 }
1986
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001987 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001988 }
1989 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001990 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001991 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001992 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
1993 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00001994 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001995 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001996 }
1997
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001998 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001999 }
2000 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002001 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002002 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002003 if (MMI && FSI.getSubprogram() &&
2004 MMI->Verify(FSI.getSubprogram())) {
2005 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002006 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002007 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002008 }
2009
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002010 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002011 }
2012 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002013 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002014 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002015 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002016 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002017 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002018 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002019 }
2020
2021 return 0;
2022 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002023
Reid Spencer0b118202006-01-16 21:12:35 +00002024 case Intrinsic::sqrt_f32:
2025 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002026 setValue(&I, DAG.getNode(ISD::FSQRT,
2027 getValue(I.getOperand(1)).getValueType(),
2028 getValue(I.getOperand(1))));
2029 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002030 case Intrinsic::powi_f32:
2031 case Intrinsic::powi_f64:
2032 setValue(&I, DAG.getNode(ISD::FPOWI,
2033 getValue(I.getOperand(1)).getValueType(),
2034 getValue(I.getOperand(1)),
2035 getValue(I.getOperand(2))));
2036 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002037 case Intrinsic::pcmarker: {
2038 SDOperand Tmp = getValue(I.getOperand(1));
2039 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2040 return 0;
2041 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002042 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002043 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002044 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2045 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2046 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002047 setValue(&I, Tmp);
2048 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002049 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002050 }
Nate Begemand88fc032006-01-14 03:14:10 +00002051 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002052 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002053 case Intrinsic::bswap_i64:
2054 setValue(&I, DAG.getNode(ISD::BSWAP,
2055 getValue(I.getOperand(1)).getValueType(),
2056 getValue(I.getOperand(1))));
2057 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002058 case Intrinsic::cttz_i8:
2059 case Intrinsic::cttz_i16:
2060 case Intrinsic::cttz_i32:
2061 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002062 setValue(&I, DAG.getNode(ISD::CTTZ,
2063 getValue(I.getOperand(1)).getValueType(),
2064 getValue(I.getOperand(1))));
2065 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002066 case Intrinsic::ctlz_i8:
2067 case Intrinsic::ctlz_i16:
2068 case Intrinsic::ctlz_i32:
2069 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002070 setValue(&I, DAG.getNode(ISD::CTLZ,
2071 getValue(I.getOperand(1)).getValueType(),
2072 getValue(I.getOperand(1))));
2073 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002074 case Intrinsic::ctpop_i8:
2075 case Intrinsic::ctpop_i16:
2076 case Intrinsic::ctpop_i32:
2077 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002078 setValue(&I, DAG.getNode(ISD::CTPOP,
2079 getValue(I.getOperand(1)).getValueType(),
2080 getValue(I.getOperand(1))));
2081 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002082 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002083 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002084 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2085 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002086 setValue(&I, Tmp);
2087 DAG.setRoot(Tmp.getValue(1));
2088 return 0;
2089 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002090 case Intrinsic::stackrestore: {
2091 SDOperand Tmp = getValue(I.getOperand(1));
2092 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002093 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002094 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002095 case Intrinsic::prefetch:
2096 // FIXME: Currently discarding prefetches.
2097 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002098 }
2099}
2100
2101
Chris Lattner1c08c712005-01-07 07:47:53 +00002102void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002103 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002104 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002105 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002106 if (unsigned IID = F->getIntrinsicID()) {
2107 RenameFn = visitIntrinsicCall(I, IID);
2108 if (!RenameFn)
2109 return;
2110 } else { // Not an LLVM intrinsic.
2111 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002112 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2113 if (I.getNumOperands() == 3 && // Basic sanity checks.
2114 I.getOperand(1)->getType()->isFloatingPoint() &&
2115 I.getType() == I.getOperand(1)->getType() &&
2116 I.getType() == I.getOperand(2)->getType()) {
2117 SDOperand LHS = getValue(I.getOperand(1));
2118 SDOperand RHS = getValue(I.getOperand(2));
2119 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2120 LHS, RHS));
2121 return;
2122 }
2123 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002124 if (I.getNumOperands() == 2 && // Basic sanity checks.
2125 I.getOperand(1)->getType()->isFloatingPoint() &&
2126 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002127 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002128 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2129 return;
2130 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002131 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002132 if (I.getNumOperands() == 2 && // Basic sanity checks.
2133 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002134 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002135 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002136 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2137 return;
2138 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002139 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002140 if (I.getNumOperands() == 2 && // Basic sanity checks.
2141 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002142 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002143 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002144 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2145 return;
2146 }
2147 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002148 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002149 } else if (isa<InlineAsm>(I.getOperand(0))) {
2150 visitInlineAsm(I);
2151 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002152 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002153
Reid Spencer47857812006-12-31 05:55:36 +00002154 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2155 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2156
Chris Lattner64e14b12005-01-08 22:48:57 +00002157 SDOperand Callee;
2158 if (!RenameFn)
2159 Callee = getValue(I.getOperand(0));
2160 else
2161 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencer47857812006-12-31 05:55:36 +00002162 TargetLowering::ArgListTy Args;
2163 TargetLowering::ArgListEntry Entry;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002164 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002165 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2166 Value *Arg = I.getOperand(i);
2167 SDOperand ArgNode = getValue(Arg);
Reid Spencer47857812006-12-31 05:55:36 +00002168 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2169 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2170 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002171 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002172
Chris Lattnercf5734d2005-01-08 19:26:18 +00002173 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002174 TLI.LowerCallTo(getRoot(), I.getType(),
2175 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2176 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2177 Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002178 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002179 setValue(&I, Result.first);
2180 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002181}
2182
Chris Lattner864635a2006-02-22 22:37:12 +00002183SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002184 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002185 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2186 Chain = Val.getValue(1);
2187 Flag = Val.getValue(2);
2188
2189 // If the result was expanded, copy from the top part.
2190 if (Regs.size() > 1) {
2191 assert(Regs.size() == 2 &&
2192 "Cannot expand to more than 2 elts yet!");
2193 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002194 Chain = Hi.getValue(1);
2195 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002196 if (DAG.getTargetLoweringInfo().isLittleEndian())
2197 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2198 else
2199 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002200 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002201
Chris Lattnercf752aa2006-06-08 18:22:48 +00002202 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002203 // appropriate type.
2204 if (RegVT == ValueVT)
2205 return Val;
2206
Chris Lattnercf752aa2006-06-08 18:22:48 +00002207 if (MVT::isInteger(RegVT)) {
2208 if (ValueVT < RegVT)
2209 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2210 else
2211 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2212 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002213 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002214 }
Chris Lattner864635a2006-02-22 22:37:12 +00002215}
2216
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002217/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2218/// specified value into the registers specified by this object. This uses
2219/// Chain/Flag as the input and updates them for the output Chain/Flag.
2220void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002221 SDOperand &Chain, SDOperand &Flag,
2222 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002223 if (Regs.size() == 1) {
2224 // If there is a single register and the types differ, this must be
2225 // a promotion.
2226 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002227 if (MVT::isInteger(RegVT)) {
2228 if (RegVT < ValueVT)
2229 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2230 else
2231 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2232 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002233 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2234 }
2235 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2236 Flag = Chain.getValue(1);
2237 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002238 std::vector<unsigned> R(Regs);
2239 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2240 std::reverse(R.begin(), R.end());
2241
2242 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002243 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002244 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002245 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002246 Flag = Chain.getValue(1);
2247 }
2248 }
2249}
Chris Lattner864635a2006-02-22 22:37:12 +00002250
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002251/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2252/// operand list. This adds the code marker and includes the number of
2253/// values added into it.
2254void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002255 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002256 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2257 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2258 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2259}
Chris Lattner864635a2006-02-22 22:37:12 +00002260
2261/// isAllocatableRegister - If the specified register is safe to allocate,
2262/// i.e. it isn't a stack pointer or some other special register, return the
2263/// register class for the register. Otherwise, return null.
2264static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002265isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2266 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002267 MVT::ValueType FoundVT = MVT::Other;
2268 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002269 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2270 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002271 MVT::ValueType ThisVT = MVT::Other;
2272
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002273 const TargetRegisterClass *RC = *RCI;
2274 // If none of the the value types for this register class are valid, we
2275 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002276 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2277 I != E; ++I) {
2278 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002279 // If we have already found this register in a different register class,
2280 // choose the one with the largest VT specified. For example, on
2281 // PowerPC, we favor f64 register classes over f32.
2282 if (FoundVT == MVT::Other ||
2283 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2284 ThisVT = *I;
2285 break;
2286 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002287 }
2288 }
2289
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002290 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002291
Chris Lattner864635a2006-02-22 22:37:12 +00002292 // NOTE: This isn't ideal. In particular, this might allocate the
2293 // frame pointer in functions that need it (due to them not being taken
2294 // out of allocation, because a variable sized allocation hasn't been seen
2295 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002296 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2297 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002298 if (*I == Reg) {
2299 // We found a matching register class. Keep looking at others in case
2300 // we find one with larger registers that this physreg is also in.
2301 FoundRC = RC;
2302 FoundVT = ThisVT;
2303 break;
2304 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002305 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002306 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002307}
2308
2309RegsForValue SelectionDAGLowering::
2310GetRegistersForValue(const std::string &ConstrCode,
2311 MVT::ValueType VT, bool isOutReg, bool isInReg,
2312 std::set<unsigned> &OutputRegs,
2313 std::set<unsigned> &InputRegs) {
2314 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2315 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2316 std::vector<unsigned> Regs;
2317
2318 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2319 MVT::ValueType RegVT;
2320 MVT::ValueType ValueVT = VT;
2321
Chris Lattner2a821602006-11-02 01:41:49 +00002322 // If this is a constraint for a specific physical register, like {r17},
2323 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002324 if (PhysReg.first) {
2325 if (VT == MVT::Other)
2326 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002327
2328 // Get the actual register value type. This is important, because the user
2329 // may have asked for (e.g.) the AX register in i32 type. We need to
2330 // remember that AX is actually i16 to get the right extension.
2331 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002332
2333 // This is a explicit reference to a physical register.
2334 Regs.push_back(PhysReg.first);
2335
2336 // If this is an expanded reference, add the rest of the regs to Regs.
2337 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002338 TargetRegisterClass::iterator I = PhysReg.second->begin();
2339 TargetRegisterClass::iterator E = PhysReg.second->end();
2340 for (; *I != PhysReg.first; ++I)
2341 assert(I != E && "Didn't find reg!");
2342
2343 // Already added the first reg.
2344 --NumRegs; ++I;
2345 for (; NumRegs; --NumRegs, ++I) {
2346 assert(I != E && "Ran out of registers to allocate!");
2347 Regs.push_back(*I);
2348 }
2349 }
2350 return RegsForValue(Regs, RegVT, ValueVT);
2351 }
2352
Chris Lattner2a821602006-11-02 01:41:49 +00002353 // Otherwise, if this was a reference to an LLVM register class, create vregs
2354 // for this reference.
2355 std::vector<unsigned> RegClassRegs;
2356 if (PhysReg.second) {
2357 // If this is an early clobber or tied register, our regalloc doesn't know
2358 // how to maintain the constraint. If it isn't, go ahead and create vreg
2359 // and let the regalloc do the right thing.
2360 if (!isOutReg || !isInReg) {
2361 if (VT == MVT::Other)
2362 ValueVT = *PhysReg.second->vt_begin();
2363 RegVT = *PhysReg.second->vt_begin();
2364
2365 // Create the appropriate number of virtual registers.
2366 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2367 for (; NumRegs; --NumRegs)
2368 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2369
2370 return RegsForValue(Regs, RegVT, ValueVT);
2371 }
2372
2373 // Otherwise, we can't allocate it. Let the code below figure out how to
2374 // maintain these constraints.
2375 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2376
2377 } else {
2378 // This is a reference to a register class that doesn't directly correspond
2379 // to an LLVM register class. Allocate NumRegs consecutive, available,
2380 // registers from the class.
2381 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2382 }
Chris Lattner864635a2006-02-22 22:37:12 +00002383
2384 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2385 MachineFunction &MF = *CurMBB->getParent();
2386 unsigned NumAllocated = 0;
2387 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2388 unsigned Reg = RegClassRegs[i];
2389 // See if this register is available.
2390 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2391 (isInReg && InputRegs.count(Reg))) { // Already used.
2392 // Make sure we find consecutive registers.
2393 NumAllocated = 0;
2394 continue;
2395 }
2396
2397 // Check to see if this register is allocatable (i.e. don't give out the
2398 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002399 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002400 if (!RC) {
2401 // Make sure we find consecutive registers.
2402 NumAllocated = 0;
2403 continue;
2404 }
2405
2406 // Okay, this register is good, we can use it.
2407 ++NumAllocated;
2408
2409 // If we allocated enough consecutive
2410 if (NumAllocated == NumRegs) {
2411 unsigned RegStart = (i-NumAllocated)+1;
2412 unsigned RegEnd = i+1;
2413 // Mark all of the allocated registers used.
2414 for (unsigned i = RegStart; i != RegEnd; ++i) {
2415 unsigned Reg = RegClassRegs[i];
2416 Regs.push_back(Reg);
2417 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2418 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2419 }
2420
2421 return RegsForValue(Regs, *RC->vt_begin(), VT);
2422 }
2423 }
2424
2425 // Otherwise, we couldn't allocate enough registers for this.
2426 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002427}
2428
Chris Lattner864635a2006-02-22 22:37:12 +00002429
Chris Lattnerce7518c2006-01-26 22:24:51 +00002430/// visitInlineAsm - Handle a call to an InlineAsm object.
2431///
2432void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2433 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2434
2435 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2436 MVT::Other);
2437
Chris Lattner2cc2f662006-02-01 01:28:23 +00002438 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002439 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002440
2441 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2442 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2443 /// if it is a def of that register.
2444 std::vector<SDOperand> AsmNodeOperands;
2445 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2446 AsmNodeOperands.push_back(AsmStr);
2447
2448 SDOperand Chain = getRoot();
2449 SDOperand Flag;
2450
Chris Lattner4e4b5762006-02-01 18:59:47 +00002451 // We fully assign registers here at isel time. This is not optimal, but
2452 // should work. For register classes that correspond to LLVM classes, we
2453 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2454 // over the constraints, collecting fixed registers that we know we can't use.
2455 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002456 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002457 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2458 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2459 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002460
Chris Lattner1efa40f2006-02-22 00:56:39 +00002461 MVT::ValueType OpVT;
2462
2463 // Compute the value type for each operand and add it to ConstraintVTs.
2464 switch (Constraints[i].Type) {
2465 case InlineAsm::isOutput:
2466 if (!Constraints[i].isIndirectOutput) {
2467 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2468 OpVT = TLI.getValueType(I.getType());
2469 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002470 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002471 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2472 OpNum++; // Consumes a call operand.
2473 }
2474 break;
2475 case InlineAsm::isInput:
2476 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2477 OpNum++; // Consumes a call operand.
2478 break;
2479 case InlineAsm::isClobber:
2480 OpVT = MVT::Other;
2481 break;
2482 }
2483
2484 ConstraintVTs.push_back(OpVT);
2485
Chris Lattner864635a2006-02-22 22:37:12 +00002486 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2487 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002488
Chris Lattner864635a2006-02-22 22:37:12 +00002489 // Build a list of regs that this operand uses. This always has a single
2490 // element for promoted/expanded operands.
2491 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2492 false, false,
2493 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002494
2495 switch (Constraints[i].Type) {
2496 case InlineAsm::isOutput:
2497 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002498 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002499 // If this is an early-clobber output, it cannot be assigned to the same
2500 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002501 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002502 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002503 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002504 case InlineAsm::isInput:
2505 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002506 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002507 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002508 case InlineAsm::isClobber:
2509 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002510 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2511 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002512 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002513 }
2514 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002515
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002516 // Loop over all of the inputs, copying the operand values into the
2517 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002518 RegsForValue RetValRegs;
2519 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002520 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002521
Chris Lattner6656dd12006-01-31 02:03:41 +00002522 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002523 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2524 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002525
Chris Lattner2cc2f662006-02-01 01:28:23 +00002526 switch (Constraints[i].Type) {
2527 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002528 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2529 if (ConstraintCode.size() == 1) // not a physreg name.
2530 CTy = TLI.getConstraintType(ConstraintCode[0]);
2531
2532 if (CTy == TargetLowering::C_Memory) {
2533 // Memory output.
2534 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2535
2536 // Check that the operand (the address to store to) isn't a float.
2537 if (!MVT::isInteger(InOperandVal.getValueType()))
2538 assert(0 && "MATCH FAIL!");
2539
2540 if (!Constraints[i].isIndirectOutput)
2541 assert(0 && "MATCH FAIL!");
2542
2543 OpNum++; // Consumes a call operand.
2544
2545 // Extend/truncate to the right pointer type if needed.
2546 MVT::ValueType PtrType = TLI.getPointerTy();
2547 if (InOperandVal.getValueType() < PtrType)
2548 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2549 else if (InOperandVal.getValueType() > PtrType)
2550 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2551
2552 // Add information to the INLINEASM node to know about this output.
2553 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2554 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2555 AsmNodeOperands.push_back(InOperandVal);
2556 break;
2557 }
2558
2559 // Otherwise, this is a register output.
2560 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2561
Chris Lattner864635a2006-02-22 22:37:12 +00002562 // If this is an early-clobber output, or if there is an input
2563 // constraint that matches this, we need to reserve the input register
2564 // so no other inputs allocate to it.
2565 bool UsesInputRegister = false;
2566 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2567 UsesInputRegister = true;
2568
2569 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002570 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002571 RegsForValue Regs =
2572 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2573 true, UsesInputRegister,
2574 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002575 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002576 cerr << "Couldn't allocate output reg for contraint '"
2577 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002578 exit(1);
2579 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002580
Chris Lattner2cc2f662006-02-01 01:28:23 +00002581 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002582 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002583 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002584 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002585 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002586 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002587 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2588 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002589 OpNum++; // Consumes a call operand.
2590 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002591
2592 // Add information to the INLINEASM node to know that this register is
2593 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002594 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002595 break;
2596 }
2597 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002598 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002599 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002600
Chris Lattner2223aea2006-02-02 00:25:23 +00002601 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2602 // If this is required to match an output register we have already set,
2603 // just use its register.
2604 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002605
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002606 // Scan until we find the definition we already emitted of this operand.
2607 // When we find it, create a RegsForValue operand.
2608 unsigned CurOp = 2; // The first operand.
2609 for (; OperandNo; --OperandNo) {
2610 // Advance to the next operand.
2611 unsigned NumOps =
2612 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002613 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2614 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002615 "Skipped past definitions?");
2616 CurOp += (NumOps>>3)+1;
2617 }
2618
2619 unsigned NumOps =
2620 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2621 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2622 "Skipped past definitions?");
2623
2624 // Add NumOps>>3 registers to MatchedRegs.
2625 RegsForValue MatchedRegs;
2626 MatchedRegs.ValueVT = InOperandVal.getValueType();
2627 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2628 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2629 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2630 MatchedRegs.Regs.push_back(Reg);
2631 }
2632
2633 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002634 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2635 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002636 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002637 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002638 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002639
2640 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2641 if (ConstraintCode.size() == 1) // not a physreg name.
2642 CTy = TLI.getConstraintType(ConstraintCode[0]);
2643
2644 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002645 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2646 ConstraintCode[0], DAG);
2647 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002648 cerr << "Invalid operand for inline asm constraint '"
2649 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002650 exit(1);
2651 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002652
2653 // Add information to the INLINEASM node to know about this input.
2654 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2655 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2656 AsmNodeOperands.push_back(InOperandVal);
2657 break;
2658 } else if (CTy == TargetLowering::C_Memory) {
2659 // Memory input.
2660
2661 // Check that the operand isn't a float.
2662 if (!MVT::isInteger(InOperandVal.getValueType()))
2663 assert(0 && "MATCH FAIL!");
2664
2665 // Extend/truncate to the right pointer type if needed.
2666 MVT::ValueType PtrType = TLI.getPointerTy();
2667 if (InOperandVal.getValueType() < PtrType)
2668 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2669 else if (InOperandVal.getValueType() > PtrType)
2670 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2671
2672 // Add information to the INLINEASM node to know about this input.
2673 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2674 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2675 AsmNodeOperands.push_back(InOperandVal);
2676 break;
2677 }
2678
2679 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2680
2681 // Copy the input into the appropriate registers.
2682 RegsForValue InRegs =
2683 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2684 false, true, OutputRegs, InputRegs);
2685 // FIXME: should be match fail.
2686 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2687
Evan Chenga8441262006-06-15 08:11:54 +00002688 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002689
2690 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002691 break;
2692 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002693 case InlineAsm::isClobber: {
2694 RegsForValue ClobberedRegs =
2695 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2696 OutputRegs, InputRegs);
2697 // Add the clobbered value to the operand list, so that the register
2698 // allocator is aware that the physreg got clobbered.
2699 if (!ClobberedRegs.Regs.empty())
2700 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002701 break;
2702 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002703 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002704 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002705
2706 // Finish up input operands.
2707 AsmNodeOperands[0] = Chain;
2708 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2709
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002710 Chain = DAG.getNode(ISD::INLINEASM,
2711 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002712 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002713 Flag = Chain.getValue(1);
2714
Chris Lattner6656dd12006-01-31 02:03:41 +00002715 // If this asm returns a register value, copy the result from that register
2716 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002717 if (!RetValRegs.Regs.empty())
2718 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002719
Chris Lattner6656dd12006-01-31 02:03:41 +00002720 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2721
2722 // Process indirect outputs, first output all of the flagged copies out of
2723 // physregs.
2724 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002725 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002726 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002727 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2728 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002729 }
2730
2731 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002732 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002733 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002734 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002735 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002736 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002737 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002738 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2739 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002740 DAG.setRoot(Chain);
2741}
2742
2743
Chris Lattner1c08c712005-01-07 07:47:53 +00002744void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2745 SDOperand Src = getValue(I.getOperand(0));
2746
2747 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002748
2749 if (IntPtr < Src.getValueType())
2750 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2751 else if (IntPtr > Src.getValueType())
2752 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002753
2754 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002755 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002756 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2757 Src, getIntPtrConstant(ElementSize));
2758
Reid Spencer47857812006-12-31 05:55:36 +00002759 TargetLowering::ArgListTy Args;
2760 TargetLowering::ArgListEntry Entry;
2761 Entry.Node = Src;
2762 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2763 Entry.isSigned = false;
2764 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002765
2766 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002767 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002768 DAG.getExternalSymbol("malloc", IntPtr),
2769 Args, DAG);
2770 setValue(&I, Result.first); // Pointers always fit in registers
2771 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002772}
2773
2774void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002775 TargetLowering::ArgListTy Args;
2776 TargetLowering::ArgListEntry Entry;
2777 Entry.Node = getValue(I.getOperand(0));
2778 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2779 Entry.isSigned = false;
2780 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002781 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002782 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002783 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002784 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2785 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002786}
2787
Chris Lattner025c39b2005-08-26 20:54:47 +00002788// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2789// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2790// instructions are special in various ways, which require special support to
2791// insert. The specified MachineInstr is created but not inserted into any
2792// basic blocks, and the scheduler passes ownership of it to this method.
2793MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2794 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002795 cerr << "If a target marks an instruction with "
2796 << "'usesCustomDAGSchedInserter', it must implement "
2797 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002798 abort();
2799 return 0;
2800}
2801
Chris Lattner39ae3622005-01-09 00:00:49 +00002802void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002803 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2804 getValue(I.getOperand(1)),
2805 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002806}
2807
2808void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002809 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2810 getValue(I.getOperand(0)),
2811 DAG.getSrcValue(I.getOperand(0)));
2812 setValue(&I, V);
2813 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002814}
2815
2816void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002817 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2818 getValue(I.getOperand(1)),
2819 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002820}
2821
2822void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002823 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2824 getValue(I.getOperand(1)),
2825 getValue(I.getOperand(2)),
2826 DAG.getSrcValue(I.getOperand(1)),
2827 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002828}
2829
Evan Chengb15974a2006-12-12 07:27:38 +00002830/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2831/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2832static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2833 unsigned &i, SelectionDAG &DAG,
2834 TargetLowering &TLI) {
2835 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2836 return SDOperand(Arg, i++);
2837
2838 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2839 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2840 if (NumVals == 1) {
2841 return DAG.getNode(ISD::BIT_CONVERT, VT,
2842 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2843 } else if (NumVals == 2) {
2844 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2845 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2846 if (!TLI.isLittleEndian())
2847 std::swap(Lo, Hi);
2848 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2849 } else {
2850 // Value scalarized into many values. Unimp for now.
2851 assert(0 && "Cannot expand i64 -> i16 yet!");
2852 }
2853 return SDOperand();
2854}
2855
Chris Lattnerfdfded52006-04-12 16:20:43 +00002856/// TargetLowering::LowerArguments - This is the default LowerArguments
2857/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002858/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2859/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002860std::vector<SDOperand>
2861TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2862 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2863 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002864 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002865 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2866 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2867
2868 // Add one result value for each formal argument.
2869 std::vector<MVT::ValueType> RetVals;
2870 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2871 MVT::ValueType VT = getValueType(I->getType());
2872
2873 switch (getTypeAction(VT)) {
2874 default: assert(0 && "Unknown type action!");
2875 case Legal:
2876 RetVals.push_back(VT);
2877 break;
2878 case Promote:
2879 RetVals.push_back(getTypeToTransformTo(VT));
2880 break;
2881 case Expand:
2882 if (VT != MVT::Vector) {
2883 // If this is a large integer, it needs to be broken up into small
2884 // integers. Figure out what the destination type is and how many small
2885 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00002886 MVT::ValueType NVT = getTypeToExpandTo(VT);
2887 unsigned NumVals = getNumElements(VT);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002888 for (unsigned i = 0; i != NumVals; ++i)
2889 RetVals.push_back(NVT);
2890 } else {
2891 // Otherwise, this is a vector type. We only support legal vectors
2892 // right now.
2893 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2894 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002895
Chris Lattnerfdfded52006-04-12 16:20:43 +00002896 // Figure out if there is a Packed type corresponding to this Vector
2897 // type. If so, convert to the packed type.
2898 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2899 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2900 RetVals.push_back(TVT);
2901 } else {
2902 assert(0 && "Don't support illegal by-val vector arguments yet!");
2903 }
2904 }
2905 break;
2906 }
2907 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002908
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002909 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002910
2911 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002912 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2913 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002914 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002915
2916 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002917
2918 // Set up the return result vector.
2919 Ops.clear();
Reid Spencer47857812006-12-31 05:55:36 +00002920 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002921 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00002922 unsigned Idx = 1;
2923 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2924 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002925 MVT::ValueType VT = getValueType(I->getType());
2926
2927 switch (getTypeAction(VT)) {
2928 default: assert(0 && "Unknown type action!");
2929 case Legal:
2930 Ops.push_back(SDOperand(Result, i++));
2931 break;
2932 case Promote: {
2933 SDOperand Op(Result, i++);
2934 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00002935 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
2936 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
2937 DAG.getValueType(VT));
2938 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
2939 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
2940 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002941 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2942 } else {
2943 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2944 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2945 }
2946 Ops.push_back(Op);
2947 break;
2948 }
2949 case Expand:
2950 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00002951 // If this is a large integer or a floating point node that needs to be
2952 // expanded, it needs to be reassembled from small integers. Figure out
2953 // what the source elt type is and how many small integers it is.
2954 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002955 } else {
2956 // Otherwise, this is a vector type. We only support legal vectors
2957 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002958 const PackedType *PTy = cast<PackedType>(I->getType());
2959 unsigned NumElems = PTy->getNumElements();
2960 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002961
Chris Lattnerfdfded52006-04-12 16:20:43 +00002962 // Figure out if there is a Packed type corresponding to this Vector
2963 // type. If so, convert to the packed type.
2964 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002965 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002966 SDOperand N = SDOperand(Result, i++);
2967 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002968 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2969 DAG.getConstant(NumElems, MVT::i32),
2970 DAG.getValueType(getValueType(EltTy)));
2971 Ops.push_back(N);
2972 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002973 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002974 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002975 }
2976 }
2977 break;
2978 }
2979 }
2980 return Ops;
2981}
2982
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002983
Evan Chengb15974a2006-12-12 07:27:38 +00002984/// ExpandScalarCallArgs - Recursively expand call argument node by
2985/// bit_converting it or extract a pair of elements from the larger node.
2986static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
2987 bool isSigned,
2988 SmallVector<SDOperand, 32> &Ops,
2989 SelectionDAG &DAG,
2990 TargetLowering &TLI) {
2991 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
2992 Ops.push_back(Arg);
2993 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2994 return;
2995 }
2996
2997 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2998 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2999 if (NumVals == 1) {
3000 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3001 ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
3002 } else if (NumVals == 2) {
3003 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3004 DAG.getConstant(0, TLI.getPointerTy()));
3005 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3006 DAG.getConstant(1, TLI.getPointerTy()));
3007 if (!TLI.isLittleEndian())
3008 std::swap(Lo, Hi);
3009 ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
3010 ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
3011 } else {
3012 // Value scalarized into many values. Unimp for now.
3013 assert(0 && "Cannot expand i64 -> i16 yet!");
3014 }
3015}
3016
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003017/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3018/// implementation, which just inserts an ISD::CALL node, which is later custom
3019/// lowered by the target to something concrete. FIXME: When all targets are
3020/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3021std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003022TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3023 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003024 unsigned CallingConv, bool isTailCall,
3025 SDOperand Callee,
3026 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003027 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003028 Ops.push_back(Chain); // Op#0 - Chain
3029 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3030 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3031 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3032 Ops.push_back(Callee);
3033
3034 // Handle all of the outgoing arguments.
3035 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003036 MVT::ValueType VT = getValueType(Args[i].Ty);
3037 SDOperand Op = Args[i].Node;
3038 bool isSigned = Args[i].isSigned;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003039 switch (getTypeAction(VT)) {
3040 default: assert(0 && "Unknown type action!");
3041 case Legal:
3042 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003043 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003044 break;
3045 case Promote:
3046 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003047 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003048 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3049 } else {
3050 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3051 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3052 }
3053 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003054 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003055 break;
3056 case Expand:
3057 if (VT != MVT::Vector) {
3058 // If this is a large integer, it needs to be broken down into small
3059 // integers. Figure out what the source elt type is and how many small
3060 // integers it is.
Evan Chengb15974a2006-12-12 07:27:38 +00003061 ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003062 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003063 // Otherwise, this is a vector type. We only support legal vectors
3064 // right now.
Reid Spencer47857812006-12-31 05:55:36 +00003065 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003066 unsigned NumElems = PTy->getNumElements();
3067 const Type *EltTy = PTy->getElementType();
3068
3069 // Figure out if there is a Packed type corresponding to this Vector
3070 // type. If so, convert to the packed type.
3071 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003072 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3073 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3074 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3075 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003076 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003077 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003078 assert(0 && "Don't support illegal by-val vector call args yet!");
3079 abort();
3080 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003081 }
3082 break;
3083 }
3084 }
3085
3086 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003087 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003088
3089 if (RetTy != Type::VoidTy) {
3090 MVT::ValueType VT = getValueType(RetTy);
3091 switch (getTypeAction(VT)) {
3092 default: assert(0 && "Unknown type action!");
3093 case Legal:
3094 RetTys.push_back(VT);
3095 break;
3096 case Promote:
3097 RetTys.push_back(getTypeToTransformTo(VT));
3098 break;
3099 case Expand:
3100 if (VT != MVT::Vector) {
3101 // If this is a large integer, it needs to be reassembled from small
3102 // integers. Figure out what the source elt type is and how many small
3103 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003104 MVT::ValueType NVT = getTypeToExpandTo(VT);
3105 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003106 for (unsigned i = 0; i != NumVals; ++i)
3107 RetTys.push_back(NVT);
3108 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003109 // Otherwise, this is a vector type. We only support legal vectors
3110 // right now.
3111 const PackedType *PTy = cast<PackedType>(RetTy);
3112 unsigned NumElems = PTy->getNumElements();
3113 const Type *EltTy = PTy->getElementType();
3114
3115 // Figure out if there is a Packed type corresponding to this Vector
3116 // type. If so, convert to the packed type.
3117 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3118 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3119 RetTys.push_back(TVT);
3120 } else {
3121 assert(0 && "Don't support illegal by-val vector call results yet!");
3122 abort();
3123 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003124 }
3125 }
3126 }
3127
3128 RetTys.push_back(MVT::Other); // Always has a chain.
3129
3130 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003131 SDOperand Res = DAG.getNode(ISD::CALL,
3132 DAG.getVTList(&RetTys[0], RetTys.size()),
3133 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003134
3135 // This returns a pair of operands. The first element is the
3136 // return value for the function (if RetTy is not VoidTy). The second
3137 // element is the outgoing token chain.
3138 SDOperand ResVal;
3139 if (RetTys.size() != 1) {
3140 MVT::ValueType VT = getValueType(RetTy);
3141 if (RetTys.size() == 2) {
3142 ResVal = Res;
3143
3144 // If this value was promoted, truncate it down.
3145 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003146 if (VT == MVT::Vector) {
3147 // Insert a VBITCONVERT to convert from the packed result type to the
3148 // MVT::Vector type.
3149 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3150 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3151
3152 // Figure out if there is a Packed type corresponding to this Vector
3153 // type. If so, convert to the packed type.
3154 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3155 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003156 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3157 // "N x PTyElementVT" MVT::Vector type.
3158 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003159 DAG.getConstant(NumElems, MVT::i32),
3160 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003161 } else {
3162 abort();
3163 }
3164 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003165 unsigned AssertOp = ISD::AssertSext;
3166 if (!RetTyIsSigned)
3167 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003168 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3169 DAG.getValueType(VT));
3170 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3171 } else {
3172 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003173 if (getTypeAction(VT) == Expand)
3174 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3175 else
3176 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003177 }
3178 }
3179 } else if (RetTys.size() == 3) {
3180 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3181 Res.getValue(0), Res.getValue(1));
3182
3183 } else {
3184 assert(0 && "Case not handled yet!");
3185 }
3186 }
3187
3188 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3189}
3190
3191
3192
Chris Lattner39ae3622005-01-09 00:00:49 +00003193// It is always conservatively correct for llvm.returnaddress and
3194// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003195//
3196// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3197// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00003198std::pair<SDOperand, SDOperand>
3199TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3200 unsigned Depth, SelectionDAG &DAG) {
3201 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00003202}
3203
Chris Lattner50381b62005-05-14 05:50:48 +00003204SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003205 assert(0 && "LowerOperation not implemented for this target!");
3206 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003207 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003208}
3209
Nate Begeman0aed7842006-01-28 03:14:31 +00003210SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3211 SelectionDAG &DAG) {
3212 assert(0 && "CustomPromoteOperation not implemented for this target!");
3213 abort();
3214 return SDOperand();
3215}
3216
Chris Lattner39ae3622005-01-09 00:00:49 +00003217void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003218 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003219 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003220 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003221 setValue(&I, Result.first);
3222 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003223}
3224
Evan Cheng74d0aa92006-02-15 21:59:04 +00003225/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003226/// operand.
3227static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003228 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003229 MVT::ValueType CurVT = VT;
3230 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3231 uint64_t Val = C->getValue() & 255;
3232 unsigned Shift = 8;
3233 while (CurVT != MVT::i8) {
3234 Val = (Val << Shift) | Val;
3235 Shift <<= 1;
3236 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003237 }
3238 return DAG.getConstant(Val, VT);
3239 } else {
3240 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3241 unsigned Shift = 8;
3242 while (CurVT != MVT::i8) {
3243 Value =
3244 DAG.getNode(ISD::OR, VT,
3245 DAG.getNode(ISD::SHL, VT, Value,
3246 DAG.getConstant(Shift, MVT::i8)), Value);
3247 Shift <<= 1;
3248 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003249 }
3250
3251 return Value;
3252 }
3253}
3254
Evan Cheng74d0aa92006-02-15 21:59:04 +00003255/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3256/// used when a memcpy is turned into a memset when the source is a constant
3257/// string ptr.
3258static SDOperand getMemsetStringVal(MVT::ValueType VT,
3259 SelectionDAG &DAG, TargetLowering &TLI,
3260 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003261 uint64_t Val = 0;
3262 unsigned MSB = getSizeInBits(VT) / 8;
3263 if (TLI.isLittleEndian())
3264 Offset = Offset + MSB - 1;
3265 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003266 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003267 Offset += TLI.isLittleEndian() ? -1 : 1;
3268 }
3269 return DAG.getConstant(Val, VT);
3270}
3271
Evan Cheng1db92f92006-02-14 08:22:34 +00003272/// getMemBasePlusOffset - Returns base and offset node for the
3273static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3274 SelectionDAG &DAG, TargetLowering &TLI) {
3275 MVT::ValueType VT = Base.getValueType();
3276 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3277}
3278
Evan Chengc4f8eee2006-02-14 20:12:38 +00003279/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003280/// to replace the memset / memcpy is below the threshold. It also returns the
3281/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003282static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3283 unsigned Limit, uint64_t Size,
3284 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003285 MVT::ValueType VT;
3286
3287 if (TLI.allowsUnalignedMemoryAccesses()) {
3288 VT = MVT::i64;
3289 } else {
3290 switch (Align & 7) {
3291 case 0:
3292 VT = MVT::i64;
3293 break;
3294 case 4:
3295 VT = MVT::i32;
3296 break;
3297 case 2:
3298 VT = MVT::i16;
3299 break;
3300 default:
3301 VT = MVT::i8;
3302 break;
3303 }
3304 }
3305
Evan Cheng80e89d72006-02-14 09:11:59 +00003306 MVT::ValueType LVT = MVT::i64;
3307 while (!TLI.isTypeLegal(LVT))
3308 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3309 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003310
Evan Cheng80e89d72006-02-14 09:11:59 +00003311 if (VT > LVT)
3312 VT = LVT;
3313
Evan Chengdea72452006-02-14 23:05:54 +00003314 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003315 while (Size != 0) {
3316 unsigned VTSize = getSizeInBits(VT) / 8;
3317 while (VTSize > Size) {
3318 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003319 VTSize >>= 1;
3320 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003321 assert(MVT::isInteger(VT));
3322
3323 if (++NumMemOps > Limit)
3324 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003325 MemOps.push_back(VT);
3326 Size -= VTSize;
3327 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003328
3329 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003330}
3331
Chris Lattner7041ee32005-01-11 05:56:49 +00003332void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003333 SDOperand Op1 = getValue(I.getOperand(1));
3334 SDOperand Op2 = getValue(I.getOperand(2));
3335 SDOperand Op3 = getValue(I.getOperand(3));
3336 SDOperand Op4 = getValue(I.getOperand(4));
3337 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3338 if (Align == 0) Align = 1;
3339
3340 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3341 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003342
3343 // Expand memset / memcpy to a series of load / store ops
3344 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003345 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003346 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003347 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003348 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003349 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3350 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003351 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003352 unsigned Offset = 0;
3353 for (unsigned i = 0; i < NumMemOps; i++) {
3354 MVT::ValueType VT = MemOps[i];
3355 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003356 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003357 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003358 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003359 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003360 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003361 Offset += VTSize;
3362 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003363 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003364 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003365 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003366 case ISD::MEMCPY: {
3367 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3368 Size->getValue(), Align, TLI)) {
3369 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003370 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003371 GlobalAddressSDNode *G = NULL;
3372 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003373 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003374
3375 if (Op2.getOpcode() == ISD::GlobalAddress)
3376 G = cast<GlobalAddressSDNode>(Op2);
3377 else if (Op2.getOpcode() == ISD::ADD &&
3378 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3379 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3380 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003381 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003382 }
3383 if (G) {
3384 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003385 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003386 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003387 if (!Str.empty()) {
3388 CopyFromStr = true;
3389 SrcOff += SrcDelta;
3390 }
3391 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003392 }
3393
Evan Chengc080d6f2006-02-15 01:54:51 +00003394 for (unsigned i = 0; i < NumMemOps; i++) {
3395 MVT::ValueType VT = MemOps[i];
3396 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003397 SDOperand Value, Chain, Store;
3398
Evan Chengcffbb512006-02-16 23:11:42 +00003399 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003400 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3401 Chain = getRoot();
3402 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003403 DAG.getStore(Chain, Value,
3404 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003405 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003406 } else {
3407 Value = DAG.getLoad(VT, getRoot(),
3408 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003409 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003410 Chain = Value.getValue(1);
3411 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003412 DAG.getStore(Chain, Value,
3413 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003414 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003415 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003416 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003417 SrcOff += VTSize;
3418 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003419 }
3420 }
3421 break;
3422 }
3423 }
3424
3425 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003426 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3427 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003428 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003429 }
3430 }
3431
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003432 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003433}
3434
Chris Lattner7041ee32005-01-11 05:56:49 +00003435//===----------------------------------------------------------------------===//
3436// SelectionDAGISel code
3437//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003438
3439unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3440 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3441}
3442
Chris Lattner495a0b52005-08-17 06:37:43 +00003443void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003444 // FIXME: we only modify the CFG to split critical edges. This
3445 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003446 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003447}
Chris Lattner1c08c712005-01-07 07:47:53 +00003448
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003449
Chris Lattner90323642006-05-05 21:17:49 +00003450/// OptimizeNoopCopyExpression - We have determined that the specified cast
3451/// instruction is a noop copy (e.g. it's casting from one pointer type to
3452/// another, int->uint, or int->sbyte on PPC.
3453///
3454/// Return true if any changes are made.
3455static bool OptimizeNoopCopyExpression(CastInst *CI) {
3456 BasicBlock *DefBB = CI->getParent();
3457
3458 /// InsertedCasts - Only insert a cast in each block once.
3459 std::map<BasicBlock*, CastInst*> InsertedCasts;
3460
3461 bool MadeChange = false;
3462 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3463 UI != E; ) {
3464 Use &TheUse = UI.getUse();
3465 Instruction *User = cast<Instruction>(*UI);
3466
3467 // Figure out which BB this cast is used in. For PHI's this is the
3468 // appropriate predecessor block.
3469 BasicBlock *UserBB = User->getParent();
3470 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3471 unsigned OpVal = UI.getOperandNo()/2;
3472 UserBB = PN->getIncomingBlock(OpVal);
3473 }
3474
3475 // Preincrement use iterator so we don't invalidate it.
3476 ++UI;
3477
3478 // If this user is in the same block as the cast, don't change the cast.
3479 if (UserBB == DefBB) continue;
3480
3481 // If we have already inserted a cast into this block, use it.
3482 CastInst *&InsertedCast = InsertedCasts[UserBB];
3483
3484 if (!InsertedCast) {
3485 BasicBlock::iterator InsertPt = UserBB->begin();
3486 while (isa<PHINode>(InsertPt)) ++InsertPt;
3487
3488 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003489 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3490 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003491 MadeChange = true;
3492 }
3493
3494 // Replace a use of the cast with a use of the new casat.
3495 TheUse = InsertedCast;
3496 }
3497
3498 // If we removed all uses, nuke the cast.
3499 if (CI->use_empty())
3500 CI->eraseFromParent();
3501
3502 return MadeChange;
3503}
3504
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003505/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3506/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003507static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3508 Instruction *GEPI, Value *Ptr,
3509 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003510 if (V) return V; // Already computed.
3511
Reid Spencer3da59db2006-11-27 01:05:10 +00003512 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003513 BasicBlock::iterator InsertPt;
3514 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003515 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003516 InsertPt = GEPI;
3517 ++InsertPt;
3518 } else {
3519 // Otherwise, insert at the top of BB, after any PHI nodes
3520 InsertPt = BB->begin();
3521 while (isa<PHINode>(InsertPt)) ++InsertPt;
3522 }
3523
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003524 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3525 // BB so that there is only one value live across basic blocks (the cast
3526 // operand).
3527 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3528 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003529 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3530 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003531
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003532 // Add the offset, cast it to the right type.
3533 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003534 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3535 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3536 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003537}
3538
Chris Lattner90323642006-05-05 21:17:49 +00003539/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3540/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3541/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3542/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3543/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3544/// the constant add into a load or store instruction. Additionally, if a user
3545/// is a pointer-pointer cast, we look through it to find its users.
3546static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3547 Constant *PtrOffset, BasicBlock *DefBB,
3548 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003549 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003550 while (!RepPtr->use_empty()) {
3551 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003552
Reid Spencer3da59db2006-11-27 01:05:10 +00003553 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3554 // used for a Pointer-Pointer cast.
3555 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003556 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003557
Chris Lattner90323642006-05-05 21:17:49 +00003558 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3559 // could invalidate an iterator.
3560 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3561 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003562 }
3563
Chris Lattner90323642006-05-05 21:17:49 +00003564 // If this is a load of the pointer, or a store through the pointer, emit
3565 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003566 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003567 if (isa<LoadInst>(User) ||
3568 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3569 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3570 User->getParent(), GEPI,
3571 Ptr, PtrOffset);
3572 } else {
3573 // If this use is not foldable into the addressing mode, use a version
3574 // emitted in the GEP block.
3575 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3576 Ptr, PtrOffset);
3577 }
3578
Chris Lattnerf0df8822006-05-06 09:10:37 +00003579 if (GEPI->getType() != RepPtr->getType()) {
3580 BasicBlock::iterator IP = NewVal;
3581 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003582 // NewVal must be a GEP which must be pointer type, so BitCast
3583 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003584 }
Chris Lattner90323642006-05-05 21:17:49 +00003585 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003586 }
3587}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003588
Chris Lattner90323642006-05-05 21:17:49 +00003589
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003590/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3591/// selection, we want to be a bit careful about some things. In particular, if
3592/// we have a GEP instruction that is used in a different block than it is
3593/// defined, the addressing expression of the GEP cannot be folded into loads or
3594/// stores that use it. In this case, decompose the GEP and move constant
3595/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003596static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003597 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003598 // If this GEP is only used inside the block it is defined in, there is no
3599 // need to rewrite it.
3600 bool isUsedOutsideDefBB = false;
3601 BasicBlock *DefBB = GEPI->getParent();
3602 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3603 UI != E; ++UI) {
3604 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3605 isUsedOutsideDefBB = true;
3606 break;
3607 }
3608 }
Chris Lattner90323642006-05-05 21:17:49 +00003609 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003610
3611 // If this GEP has no non-zero constant indices, there is nothing we can do,
3612 // ignore it.
3613 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003614 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003615 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3616 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003617 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003618 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003619 hasConstantIndex = true;
3620 break;
3621 }
Chris Lattner90323642006-05-05 21:17:49 +00003622 } else {
3623 hasVariableIndex = true;
3624 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003625 }
Chris Lattner90323642006-05-05 21:17:49 +00003626
3627 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3628 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003629 /// The GEP operand must be a pointer, so must its result -> BitCast
3630 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003631 GEPI->getName(), GEPI);
3632 GEPI->replaceAllUsesWith(NC);
3633 GEPI->eraseFromParent();
3634 return true;
3635 }
3636
Chris Lattner3802c252005-12-11 09:05:13 +00003637 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003638 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3639 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003640
3641 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3642 // constant offset (which we now know is non-zero) and deal with it later.
3643 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003644 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003645 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003646 const Type *Ty = GEPI->getOperand(0)->getType();
3647
3648 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3649 E = GEPI->op_end(); OI != E; ++OI) {
3650 Value *Idx = *OI;
3651 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003652 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003653 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003654 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003655 Ty = StTy->getElementType(Field);
3656 } else {
3657 Ty = cast<SequentialType>(Ty)->getElementType();
3658
3659 // Handle constant subscripts.
3660 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003661 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003662 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003663 continue;
3664 }
3665
3666 // Ptr = Ptr + Idx * ElementSize;
3667
3668 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003669 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003670
Owen Andersona69571c2006-05-03 01:29:57 +00003671 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003672 // Mask off bits that should not be set.
3673 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003674 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003675
3676 // Multiply by the element size and add to the base.
3677 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3678 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3679 }
3680 }
3681
3682 // Make sure that the offset fits in uintptr_t.
3683 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003684 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003685
3686 // Okay, we have now emitted all of the variable index parts to the BB that
3687 // the GEP is defined in. Loop over all of the using instructions, inserting
3688 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003689 // instruction to use the newly computed value, making GEPI dead. When the
3690 // user is a load or store instruction address, we emit the add into the user
3691 // block, otherwise we use a canonical version right next to the gep (these
3692 // won't be foldable as addresses, so we might as well share the computation).
3693
Chris Lattnerf0df8822006-05-06 09:10:37 +00003694 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003695 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003696
3697 // Finally, the GEP is dead, remove it.
3698 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003699
3700 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003701}
3702
Chris Lattnerbad7f482006-10-28 19:22:10 +00003703
3704/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3705/// successor if it will improve codegen. We only do this if the successor has
3706/// phi nodes (otherwise critical edges are ok). If there is already another
3707/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3708/// instead of introducing a new block.
3709static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3710 BasicBlock *TIBB = TI->getParent();
3711 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3712 assert(isa<PHINode>(Dest->begin()) &&
3713 "This should only be called if Dest has a PHI!");
3714
3715 /// TIPHIValues - This array is lazily computed to determine the values of
3716 /// PHIs in Dest that TI would provide.
3717 std::vector<Value*> TIPHIValues;
3718
3719 // Check to see if Dest has any blocks that can be used as a split edge for
3720 // this terminator.
3721 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3722 BasicBlock *Pred = *PI;
3723 // To be usable, the pred has to end with an uncond branch to the dest.
3724 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3725 if (!PredBr || !PredBr->isUnconditional() ||
3726 // Must be empty other than the branch.
3727 &Pred->front() != PredBr)
3728 continue;
3729
3730 // Finally, since we know that Dest has phi nodes in it, we have to make
3731 // sure that jumping to Pred will have the same affect as going to Dest in
3732 // terms of PHI values.
3733 PHINode *PN;
3734 unsigned PHINo = 0;
3735 bool FoundMatch = true;
3736 for (BasicBlock::iterator I = Dest->begin();
3737 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3738 if (PHINo == TIPHIValues.size())
3739 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3740
3741 // If the PHI entry doesn't work, we can't use this pred.
3742 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3743 FoundMatch = false;
3744 break;
3745 }
3746 }
3747
3748 // If we found a workable predecessor, change TI to branch to Succ.
3749 if (FoundMatch) {
3750 Dest->removePredecessor(TIBB);
3751 TI->setSuccessor(SuccNum, Pred);
3752 return;
3753 }
3754 }
3755
3756 SplitCriticalEdge(TI, SuccNum, P, true);
3757}
3758
3759
Chris Lattner1c08c712005-01-07 07:47:53 +00003760bool SelectionDAGISel::runOnFunction(Function &Fn) {
3761 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3762 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003763 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003764
Chris Lattner47e32e62006-10-28 17:04:37 +00003765 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003766 //
Chris Lattner7e598092006-05-05 01:04:50 +00003767 // In this pass we also look for GEP and cast instructions that are used
3768 // across basic blocks and rewrite them to improve basic-block-at-a-time
3769 // selection.
3770 //
Chris Lattner90323642006-05-05 21:17:49 +00003771 bool MadeChange = true;
3772 while (MadeChange) {
3773 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003774 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003775 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003776 TerminatorInst *BBTI = BB->getTerminator();
3777 if (BBTI->getNumSuccessors() > 1) {
3778 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003779 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3780 isCriticalEdge(BBTI, i, true))
3781 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003782 }
3783
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003784
Chris Lattner57f9a432006-09-28 06:17:10 +00003785 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003786 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003787
3788 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3789 // If we found an inline asm expession, and if the target knows how to
3790 // lower it to normal LLVM code, do so now.
3791 if (isa<InlineAsm>(CI->getCalledValue()))
3792 if (const TargetAsmInfo *TAI =
3793 TLI.getTargetMachine().getTargetAsmInfo()) {
3794 if (TAI->ExpandInlineAsm(CI))
3795 BBI = BB->begin();
3796 }
3797 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003798 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003799 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003800 // If the source of the cast is a constant, then this should have
3801 // already been constant folded. The only reason NOT to constant fold
3802 // it is if something (e.g. LSR) was careful to place the constant
3803 // evaluation in a block other than then one that uses it (e.g. to hoist
3804 // the address of globals out of a loop). If this is the case, we don't
3805 // want to forward-subst the cast.
3806 if (isa<Constant>(CI->getOperand(0)))
3807 continue;
3808
Chris Lattner7e598092006-05-05 01:04:50 +00003809 // If this is a noop copy, sink it into user blocks to reduce the number
3810 // of virtual registers that must be created and coallesced.
3811 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3812 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3813
3814 // This is an fp<->int conversion?
3815 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3816 continue;
3817
3818 // If this is an extension, it will be a zero or sign extension, which
3819 // isn't a noop.
3820 if (SrcVT < DstVT) continue;
3821
3822 // If these values will be promoted, find out what they will be promoted
3823 // to. This helps us consider truncates on PPC as noop copies when they
3824 // are.
3825 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3826 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3827 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3828 DstVT = TLI.getTypeToTransformTo(DstVT);
3829
3830 // If, after promotion, these are the same types, this is a noop copy.
3831 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003832 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003833 }
3834 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003835 }
Chris Lattner90323642006-05-05 21:17:49 +00003836 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003837
Chris Lattner1c08c712005-01-07 07:47:53 +00003838 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3839
3840 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3841 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003842
Chris Lattner1c08c712005-01-07 07:47:53 +00003843 return true;
3844}
3845
Chris Lattner571e4342006-10-27 21:36:01 +00003846SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3847 unsigned Reg) {
3848 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003849 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003850 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003851 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003852
3853 // If this type is not legal, we must make sure to not create an invalid
3854 // register use.
3855 MVT::ValueType SrcVT = Op.getValueType();
3856 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003857 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003858 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003859 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003860 // Handle copies from generic vectors to registers.
3861 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3862 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3863 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003864
Chris Lattner70c2a612006-03-31 02:06:56 +00003865 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3866 // MVT::Vector type.
3867 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3868 DAG.getConstant(NE, MVT::i32),
3869 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003870
Chris Lattner70c2a612006-03-31 02:06:56 +00003871 // Loop over all of the elements of the resultant vector,
3872 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3873 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003874 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003875 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003876 for (unsigned i = 0; i != NE; ++i) {
3877 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003878 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003879 if (PTyElementVT == PTyLegalElementVT) {
3880 // Elements are legal.
3881 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3882 } else if (PTyLegalElementVT > PTyElementVT) {
3883 // Elements are promoted.
3884 if (MVT::isFloatingPoint(PTyLegalElementVT))
3885 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3886 else
3887 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3888 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3889 } else {
3890 // Elements are expanded.
3891 // The src value is expanded into multiple registers.
3892 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003893 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003894 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003895 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003896 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3897 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3898 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003899 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003900 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3901 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00003902 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003903 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003904 if (MVT::isFloatingPoint(SrcVT))
3905 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3906 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003907 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003908 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003909 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00003910 DestVT = TLI.getTypeToExpandTo(SrcVT);
3911 unsigned NumVals = TLI.getNumElements(SrcVT);
3912 if (NumVals == 1)
3913 return DAG.getCopyToReg(getRoot(), Reg,
3914 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3915 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003916 // The src value is expanded into multiple registers.
3917 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003918 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003919 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003920 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003921 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003922 return DAG.getCopyToReg(Op, Reg+1, Hi);
3923 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003924}
3925
Chris Lattner068a81e2005-01-17 17:15:02 +00003926void SelectionDAGISel::
3927LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3928 std::vector<SDOperand> &UnorderedChains) {
3929 // If this is the entry block, emit arguments.
3930 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003931 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003932 SDOperand OldRoot = SDL.DAG.getRoot();
3933 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003934
Chris Lattnerbf209482005-10-30 19:42:35 +00003935 unsigned a = 0;
3936 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3937 AI != E; ++AI, ++a)
3938 if (!AI->use_empty()) {
3939 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003940
Chris Lattnerbf209482005-10-30 19:42:35 +00003941 // If this argument is live outside of the entry block, insert a copy from
3942 // whereever we got it to the vreg that other BB's will reference it as.
3943 if (FuncInfo.ValueMap.count(AI)) {
3944 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003945 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003946 UnorderedChains.push_back(Copy);
3947 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003948 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003949
Chris Lattnerbf209482005-10-30 19:42:35 +00003950 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003951 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003952 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003953}
3954
Chris Lattner1c08c712005-01-07 07:47:53 +00003955void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3956 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003957 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003958 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003959
3960 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003961
Chris Lattnerbf209482005-10-30 19:42:35 +00003962 // Lower any arguments needed in this block if this is the entry block.
3963 if (LLVMBB == &LLVMBB->getParent()->front())
3964 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003965
3966 BB = FuncInfo.MBBMap[LLVMBB];
3967 SDL.setCurrentBasicBlock(BB);
3968
3969 // Lower all of the non-terminator instructions.
3970 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3971 I != E; ++I)
3972 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003973
Chris Lattner1c08c712005-01-07 07:47:53 +00003974 // Ensure that all instructions which are used outside of their defining
3975 // blocks are available as virtual registers.
3976 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003977 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003978 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003979 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003980 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003981 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003982 }
3983
3984 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3985 // ensure constants are generated when needed. Remember the virtual registers
3986 // that need to be added to the Machine PHI nodes as input. We cannot just
3987 // directly add them, because expansion might result in multiple MBB's for one
3988 // BB. As such, the start of the BB might correspond to a different MBB than
3989 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003990 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00003991 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00003992
3993 // Emit constants only once even if used by multiple PHI nodes.
3994 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003995
Chris Lattner8c494ab2006-10-27 23:50:33 +00003996 // Vector bool would be better, but vector<bool> is really slow.
3997 std::vector<unsigned char> SuccsHandled;
3998 if (TI->getNumSuccessors())
3999 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4000
Chris Lattner1c08c712005-01-07 07:47:53 +00004001 // Check successor nodes PHI nodes that expect a constant to be available from
4002 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004003 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4004 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004005 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004006 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004007
Chris Lattner8c494ab2006-10-27 23:50:33 +00004008 // If this terminator has multiple identical successors (common for
4009 // switches), only handle each succ once.
4010 unsigned SuccMBBNo = SuccMBB->getNumber();
4011 if (SuccsHandled[SuccMBBNo]) continue;
4012 SuccsHandled[SuccMBBNo] = true;
4013
4014 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004015 PHINode *PN;
4016
4017 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4018 // nodes and Machine PHI nodes, but the incoming operands have not been
4019 // emitted yet.
4020 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004021 (PN = dyn_cast<PHINode>(I)); ++I) {
4022 // Ignore dead phi's.
4023 if (PN->use_empty()) continue;
4024
4025 unsigned Reg;
4026 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004027
Chris Lattner8c494ab2006-10-27 23:50:33 +00004028 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4029 unsigned &RegOut = ConstantsOut[C];
4030 if (RegOut == 0) {
4031 RegOut = FuncInfo.CreateRegForValue(C);
4032 UnorderedChains.push_back(
4033 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004034 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004035 Reg = RegOut;
4036 } else {
4037 Reg = FuncInfo.ValueMap[PHIOp];
4038 if (Reg == 0) {
4039 assert(isa<AllocaInst>(PHIOp) &&
4040 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4041 "Didn't codegen value into a register!??");
4042 Reg = FuncInfo.CreateRegForValue(PHIOp);
4043 UnorderedChains.push_back(
4044 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004045 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004046 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004047
4048 // Remember that this register needs to added to the machine PHI node as
4049 // the input for this MBB.
4050 MVT::ValueType VT = TLI.getValueType(PN->getType());
4051 unsigned NumElements;
4052 if (VT != MVT::Vector)
4053 NumElements = TLI.getNumElements(VT);
4054 else {
4055 MVT::ValueType VT1,VT2;
4056 NumElements =
4057 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4058 VT1, VT2);
4059 }
4060 for (unsigned i = 0, e = NumElements; i != e; ++i)
4061 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4062 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004063 }
4064 ConstantsOut.clear();
4065
Chris Lattnerddb870b2005-01-13 17:59:43 +00004066 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004067 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004068 SDOperand Root = SDL.getRoot();
4069 if (Root.getOpcode() != ISD::EntryToken) {
4070 unsigned i = 0, e = UnorderedChains.size();
4071 for (; i != e; ++i) {
4072 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4073 if (UnorderedChains[i].Val->getOperand(0) == Root)
4074 break; // Don't add the root if we already indirectly depend on it.
4075 }
4076
4077 if (i == e)
4078 UnorderedChains.push_back(Root);
4079 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004080 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4081 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004082 }
4083
Chris Lattner1c08c712005-01-07 07:47:53 +00004084 // Lower the terminator after the copies are emitted.
4085 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004086
Nate Begemanf15485a2006-03-27 01:32:24 +00004087 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004088 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004089 SwitchCases.clear();
4090 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004091 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004092
Chris Lattnera651cf62005-01-17 19:43:36 +00004093 // Make sure the root of the DAG is up-to-date.
4094 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004095}
4096
Nate Begemanf15485a2006-03-27 01:32:24 +00004097void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004098 // Get alias analysis for load/store combining.
4099 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4100
Chris Lattneraf21d552005-10-10 16:47:10 +00004101 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004102 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004103
Bill Wendling832171c2006-12-07 20:04:42 +00004104 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004105 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004106
Chris Lattner1c08c712005-01-07 07:47:53 +00004107 // Second step, hack on the DAG until it only uses operations and types that
4108 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004109 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004110
Bill Wendling832171c2006-12-07 20:04:42 +00004111 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004112 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004113
Chris Lattneraf21d552005-10-10 16:47:10 +00004114 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004115 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004116
Evan Chenga9c20912006-01-21 02:32:06 +00004117 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004118
Chris Lattnera33ef482005-03-30 01:10:47 +00004119 // Third, instruction select all of the operations to machine code, adding the
4120 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004121 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004122
Bill Wendling832171c2006-12-07 20:04:42 +00004123 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004124 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004125}
Chris Lattner1c08c712005-01-07 07:47:53 +00004126
Nate Begemanf15485a2006-03-27 01:32:24 +00004127void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4128 FunctionLoweringInfo &FuncInfo) {
4129 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4130 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004131 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004132 CurDAG = &DAG;
4133
4134 // First step, lower LLVM code to some DAG. This DAG may use operations and
4135 // types that are not supported by the target.
4136 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4137
4138 // Second step, emit the lowered DAG as machine code.
4139 CodeGenAndEmitDAG(DAG);
4140 }
4141
Chris Lattnera33ef482005-03-30 01:10:47 +00004142 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004143 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004144 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004145 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4146 MachineInstr *PHI = PHINodesToUpdate[i].first;
4147 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4148 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004149 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004150 PHI->addMachineBasicBlockOperand(BB);
4151 }
4152 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004153 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004154
Nate Begeman9453eea2006-04-23 06:26:20 +00004155 // If the JumpTable record is filled in, then we need to emit a jump table.
4156 // Updating the PHI nodes is tricky in this case, since we need to determine
4157 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004158 if (JT.Reg) {
4159 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004160 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004161 CurDAG = &SDAG;
4162 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004163 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004164 // Set the current basic block to the mbb we wish to insert the code into
4165 BB = JT.MBB;
4166 SDL.setCurrentBasicBlock(BB);
4167 // Emit the code
4168 SDL.visitJumpTable(JT);
4169 SDAG.setRoot(SDL.getRoot());
4170 CodeGenAndEmitDAG(SDAG);
4171 // Update PHI Nodes
4172 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4173 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4174 MachineBasicBlock *PHIBB = PHI->getParent();
4175 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4176 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004177 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004178 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004179 PHI->addMachineBasicBlockOperand(RangeBB);
4180 }
4181 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004182 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004183 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004184 }
4185 }
4186 return;
4187 }
4188
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004189 // If the switch block involved a branch to one of the actual successors, we
4190 // need to update PHI nodes in that block.
4191 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4192 MachineInstr *PHI = PHINodesToUpdate[i].first;
4193 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4194 "This is not a machine PHI node that we are updating!");
4195 if (BB->isSuccessor(PHI->getParent())) {
4196 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4197 PHI->addMachineBasicBlockOperand(BB);
4198 }
4199 }
4200
Nate Begemanf15485a2006-03-27 01:32:24 +00004201 // If we generated any switch lowering information, build and codegen any
4202 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004203 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004204 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004205 CurDAG = &SDAG;
4206 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004207
Nate Begemanf15485a2006-03-27 01:32:24 +00004208 // Set the current basic block to the mbb we wish to insert the code into
4209 BB = SwitchCases[i].ThisBB;
4210 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004211
Nate Begemanf15485a2006-03-27 01:32:24 +00004212 // Emit the code
4213 SDL.visitSwitchCase(SwitchCases[i]);
4214 SDAG.setRoot(SDL.getRoot());
4215 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004216
4217 // Handle any PHI nodes in successors of this chunk, as if we were coming
4218 // from the original BB before switch expansion. Note that PHI nodes can
4219 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4220 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004221 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004222 for (MachineBasicBlock::iterator Phi = BB->begin();
4223 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4224 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4225 for (unsigned pn = 0; ; ++pn) {
4226 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4227 if (PHINodesToUpdate[pn].first == Phi) {
4228 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4229 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4230 break;
4231 }
4232 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004233 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004234
4235 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004236 if (BB == SwitchCases[i].FalseBB)
4237 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004238
4239 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004240 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004241 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004242 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004243 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004244 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004245}
Evan Chenga9c20912006-01-21 02:32:06 +00004246
Jim Laskey13ec7022006-08-01 14:21:23 +00004247
Evan Chenga9c20912006-01-21 02:32:06 +00004248//===----------------------------------------------------------------------===//
4249/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4250/// target node in the graph.
4251void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4252 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004253
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004254 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004255
4256 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004257 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004258 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004259 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004260
Jim Laskey9ff542f2006-08-01 18:29:48 +00004261 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004262 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004263 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004264}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004265
Chris Lattner03fc53c2006-03-06 00:22:00 +00004266
Jim Laskey9ff542f2006-08-01 18:29:48 +00004267HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4268 return new HazardRecognizer();
4269}
4270
Chris Lattner75548062006-10-11 03:58:02 +00004271//===----------------------------------------------------------------------===//
4272// Helper functions used by the generated instruction selector.
4273//===----------------------------------------------------------------------===//
4274// Calls to these methods are generated by tblgen.
4275
4276/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4277/// the dag combiner simplified the 255, we still want to match. RHS is the
4278/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4279/// specified in the .td file (e.g. 255).
4280bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4281 int64_t DesiredMaskS) {
4282 uint64_t ActualMask = RHS->getValue();
4283 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4284
4285 // If the actual mask exactly matches, success!
4286 if (ActualMask == DesiredMask)
4287 return true;
4288
4289 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4290 if (ActualMask & ~DesiredMask)
4291 return false;
4292
4293 // Otherwise, the DAG Combiner may have proven that the value coming in is
4294 // either already zero or is not demanded. Check for known zero input bits.
4295 uint64_t NeededMask = DesiredMask & ~ActualMask;
4296 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4297 return true;
4298
4299 // TODO: check to see if missing bits are just not demanded.
4300
4301 // Otherwise, this pattern doesn't match.
4302 return false;
4303}
4304
4305/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4306/// the dag combiner simplified the 255, we still want to match. RHS is the
4307/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4308/// specified in the .td file (e.g. 255).
4309bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4310 int64_t DesiredMaskS) {
4311 uint64_t ActualMask = RHS->getValue();
4312 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4313
4314 // If the actual mask exactly matches, success!
4315 if (ActualMask == DesiredMask)
4316 return true;
4317
4318 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4319 if (ActualMask & ~DesiredMask)
4320 return false;
4321
4322 // Otherwise, the DAG Combiner may have proven that the value coming in is
4323 // either already zero or is not demanded. Check for known zero input bits.
4324 uint64_t NeededMask = DesiredMask & ~ActualMask;
4325
4326 uint64_t KnownZero, KnownOne;
4327 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4328
4329 // If all the missing bits in the or are already known to be set, match!
4330 if ((NeededMask & KnownOne) == NeededMask)
4331 return true;
4332
4333 // TODO: check to see if missing bits are just not demanded.
4334
4335 // Otherwise, this pattern doesn't match.
4336 return false;
4337}
4338
Jim Laskey9ff542f2006-08-01 18:29:48 +00004339
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004340/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4341/// by tblgen. Others should not call it.
4342void SelectionDAGISel::
4343SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4344 std::vector<SDOperand> InOps;
4345 std::swap(InOps, Ops);
4346
4347 Ops.push_back(InOps[0]); // input chain.
4348 Ops.push_back(InOps[1]); // input asm string.
4349
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004350 unsigned i = 2, e = InOps.size();
4351 if (InOps[e-1].getValueType() == MVT::Flag)
4352 --e; // Don't process a flag operand if it is here.
4353
4354 while (i != e) {
4355 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4356 if ((Flags & 7) != 4 /*MEM*/) {
4357 // Just skip over this operand, copying the operands verbatim.
4358 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4359 i += (Flags >> 3) + 1;
4360 } else {
4361 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4362 // Otherwise, this is a memory operand. Ask the target to select it.
4363 std::vector<SDOperand> SelOps;
4364 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004365 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004366 exit(1);
4367 }
4368
4369 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004370 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4371 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004372 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4373 i += 2;
4374 }
4375 }
4376
4377 // Add the flag input back if present.
4378 if (e != InOps.size())
4379 Ops.push_back(InOps.back());
4380}