blob: 8024fcac46c04045d8fbbd09261b8f6d4f956250 [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"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.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"
Chris Lattner1c08c712005-01-07 07:47:53 +000047#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000048#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattnerda8abb02005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#else
Chris Lattner5e46a192006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000062#endif
63
Jim Laskeyeb577ba2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey9ff542f2006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner864635a2006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000137 };
138}
Evan Cheng4ef10862006-01-23 07:01:07 +0000139
Chris Lattner1c08c712005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Chris Lattner571e4342006-10-27 21:36:01 +0000187
188 /// isExportedInst - Return true if the specified value is an instruction
189 /// exported from its block.
190 bool isExportedInst(const Value *V) {
191 return ValueMap.count(V);
192 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000193
Chris Lattner3c384492006-03-16 19:51:18 +0000194 unsigned CreateRegForValue(const Value *V);
195
Chris Lattner1c08c712005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000205/// PHI nodes or outside of the basic block that defines it, or used by a
206/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000207static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
208 if (isa<PHINode>(I)) return true;
209 BasicBlock *BB = I->getParent();
210 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000211 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000212 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000213 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000214 return true;
215 return false;
216}
217
Chris Lattnerbf209482005-10-30 19:42:35 +0000218/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000219/// entry block, return true. This includes arguments used by switches, since
220/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000221static bool isOnlyUsedInEntryBlock(Argument *A) {
222 BasicBlock *Entry = A->getParent()->begin();
223 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000224 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000225 return false; // Use not in entry block.
226 return true;
227}
228
Chris Lattner1c08c712005-01-07 07:47:53 +0000229FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000230 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000231 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
232
Chris Lattnerbf209482005-10-30 19:42:35 +0000233 // Create a vreg for each argument register that is not dead and is used
234 // outside of the entry block for the function.
235 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
236 AI != E; ++AI)
237 if (!isOnlyUsedInEntryBlock(AI))
238 InitializeRegForValue(AI);
239
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 // Initialize the mapping of values to registers. This is only set up for
241 // instruction values that are used outside of the block that defines
242 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000243 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000246 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000248 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000249 unsigned Align =
Owen Andersona69571c2006-05-03 01:29:57 +0000250 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000251 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000252
Reid Spencerb83eb642006-10-20 07:07:24 +0000253 // If the alignment of the value is smaller than the size of the
254 // value, and if the size of the value is particularly small
255 // (<= 8 bytes), round up to the size of the value for potentially
256 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000257 //
258 // FIXME: This could be made better with a preferred alignment hook in
259 // TargetData. It serves primarily to 8-byte align doubles for X86.
260 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000262 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000264 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000265 }
266
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000267 for (; BB != EB; ++BB)
268 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000269 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
270 if (!isa<AllocaInst>(I) ||
271 !StaticAllocaMap.count(cast<AllocaInst>(I)))
272 InitializeRegForValue(I);
273
274 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
275 // also creates the initial PHI MachineInstrs, though none of the input
276 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000277 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000278 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
279 MBBMap[BB] = MBB;
280 MF.getBasicBlockList().push_back(MBB);
281
282 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
283 // appropriate.
284 PHINode *PN;
285 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000286 (PN = dyn_cast<PHINode>(I)); ++I)
287 if (!PN->use_empty()) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000288 MVT::ValueType VT = TLI.getValueType(PN->getType());
289 unsigned NumElements;
290 if (VT != MVT::Vector)
291 NumElements = TLI.getNumElements(VT);
292 else {
293 MVT::ValueType VT1,VT2;
294 NumElements =
295 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
296 VT1, VT2);
297 }
Chris Lattnerf44fd882005-01-07 21:34:19 +0000298 unsigned PHIReg = ValueMap[PN];
299 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
300 for (unsigned i = 0; i != NumElements; ++i)
301 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
302 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000303 }
304}
305
Chris Lattner3c384492006-03-16 19:51:18 +0000306/// CreateRegForValue - Allocate the appropriate number of virtual registers of
307/// the correctly promoted or expanded types. Assign these registers
308/// consecutive vreg numbers and return the first assigned number.
309unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
310 MVT::ValueType VT = TLI.getValueType(V->getType());
311
312 // The number of multiples of registers that we need, to, e.g., split up
313 // a <2 x int64> -> 4 x i32 registers.
314 unsigned NumVectorRegs = 1;
315
316 // If this is a packed type, figure out what type it will decompose into
317 // and how many of the elements it will use.
318 if (VT == MVT::Vector) {
319 const PackedType *PTy = cast<PackedType>(V->getType());
320 unsigned NumElts = PTy->getNumElements();
321 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
322
323 // Divide the input until we get to a supported size. This will always
324 // end with a scalar if the target doesn't support vectors.
325 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
326 NumElts >>= 1;
327 NumVectorRegs <<= 1;
328 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000329 if (NumElts == 1)
330 VT = EltTy;
331 else
332 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000333 }
334
335 // The common case is that we will only create one register for this
336 // value. If we have that case, create and return the virtual register.
337 unsigned NV = TLI.getNumElements(VT);
338 if (NV == 1) {
339 // If we are promoting this value, pick the next largest supported type.
340 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
341 unsigned Reg = MakeReg(PromotedType);
342 // If this is a vector of supported or promoted types (e.g. 4 x i16),
343 // create all of the registers.
344 for (unsigned i = 1; i != NumVectorRegs; ++i)
345 MakeReg(PromotedType);
346 return Reg;
347 }
348
349 // If this value is represented with multiple target registers, make sure
350 // to create enough consecutive registers of the right (smaller) type.
351 unsigned NT = VT-1; // Find the type to use.
352 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
353 --NT;
354
355 unsigned R = MakeReg((MVT::ValueType)NT);
356 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
357 MakeReg((MVT::ValueType)NT);
358 return R;
359}
Chris Lattner1c08c712005-01-07 07:47:53 +0000360
361//===----------------------------------------------------------------------===//
362/// SelectionDAGLowering - This is the common target-independent lowering
363/// implementation that is parameterized by a TargetLowering object.
364/// Also, targets can overload any lowering method.
365///
366namespace llvm {
367class SelectionDAGLowering {
368 MachineBasicBlock *CurMBB;
369
370 std::map<const Value*, SDOperand> NodeMap;
371
Chris Lattnerd3948112005-01-17 22:19:26 +0000372 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
373 /// them up and then emit token factor nodes when possible. This allows us to
374 /// get simple disambiguation between loads without worrying about alias
375 /// analysis.
376 std::vector<SDOperand> PendingLoads;
377
Nate Begemanf15485a2006-03-27 01:32:24 +0000378 /// Case - A pair of values to record the Value for a switch case, and the
379 /// case's target basic block.
380 typedef std::pair<Constant*, MachineBasicBlock*> Case;
381 typedef std::vector<Case>::iterator CaseItr;
382 typedef std::pair<CaseItr, CaseItr> CaseRange;
383
384 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
385 /// of conditional branches.
386 struct CaseRec {
387 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
388 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
389
390 /// CaseBB - The MBB in which to emit the compare and branch
391 MachineBasicBlock *CaseBB;
392 /// LT, GE - If nonzero, we know the current case value must be less-than or
393 /// greater-than-or-equal-to these Constants.
394 Constant *LT;
395 Constant *GE;
396 /// Range - A pair of iterators representing the range of case values to be
397 /// processed at this point in the binary search tree.
398 CaseRange Range;
399 };
400
401 /// The comparison function for sorting Case values.
402 struct CaseCmp {
403 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000404 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
405 if (I1->getType()->isUnsigned())
406 return I1->getZExtValue() <
407 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000408
Reid Spencerb83eb642006-10-20 07:07:24 +0000409 return cast<const ConstantInt>(C1.first)->getSExtValue() <
410 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000411 }
412 };
413
Chris Lattner1c08c712005-01-07 07:47:53 +0000414public:
415 // TLI - This is information that describes the available target features we
416 // need for lowering. This indicates when operations are unavailable,
417 // implemented with a libcall, etc.
418 TargetLowering &TLI;
419 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000420 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000421
Nate Begemanf15485a2006-03-27 01:32:24 +0000422 /// SwitchCases - Vector of CaseBlock structures used to communicate
423 /// SwitchInst code generation information.
424 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000425 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000426
Chris Lattner1c08c712005-01-07 07:47:53 +0000427 /// FuncInfo - Information about the function as a whole.
428 ///
429 FunctionLoweringInfo &FuncInfo;
430
431 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000432 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000434 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000435 }
436
Chris Lattnera651cf62005-01-17 19:43:36 +0000437 /// getRoot - Return the current virtual root of the Selection DAG.
438 ///
439 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000440 if (PendingLoads.empty())
441 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000442
Chris Lattnerd3948112005-01-17 22:19:26 +0000443 if (PendingLoads.size() == 1) {
444 SDOperand Root = PendingLoads[0];
445 DAG.setRoot(Root);
446 PendingLoads.clear();
447 return Root;
448 }
449
450 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000451 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
452 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000453 PendingLoads.clear();
454 DAG.setRoot(Root);
455 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000456 }
457
Chris Lattner571e4342006-10-27 21:36:01 +0000458 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
459
Chris Lattner1c08c712005-01-07 07:47:53 +0000460 void visit(Instruction &I) { visit(I.getOpcode(), I); }
461
462 void visit(unsigned Opcode, User &I) {
463 switch (Opcode) {
464 default: assert(0 && "Unknown instruction type encountered!");
465 abort();
466 // Build the switch statement using the Instruction.def file.
467#define HANDLE_INST(NUM, OPCODE, CLASS) \
468 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
469#include "llvm/Instruction.def"
470 }
471 }
472
473 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000475 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000476 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000477 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000478
479 SDOperand getIntPtrConstant(uint64_t Val) {
480 return DAG.getConstant(Val, TLI.getPointerTy());
481 }
482
Chris Lattner199862b2006-03-16 19:57:50 +0000483 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000484
485 const SDOperand &setValue(const Value *V, SDOperand NewN) {
486 SDOperand &N = NodeMap[V];
487 assert(N.Val == 0 && "Already set a value for this node!");
488 return N = NewN;
489 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000490
Chris Lattner864635a2006-02-22 22:37:12 +0000491 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 MVT::ValueType VT,
493 bool OutReg, bool InReg,
494 std::set<unsigned> &OutputRegs,
495 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000496
Chris Lattner571e4342006-10-27 21:36:01 +0000497 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
498 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 unsigned Opc);
500 void ExportFromCurrentBlock(Value *V);
501
Chris Lattner1c08c712005-01-07 07:47:53 +0000502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000505 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507
Nate Begemanf15485a2006-03-27 01:32:24 +0000508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000511
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515
Reid Spencer1628cec2006-10-26 06:15:43 +0000516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000518 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000519 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 else
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000524 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000525 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 else
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000531 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000532 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
533 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
534 void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV, ISD::VSDIV); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000535 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000536 const Type *Ty = I.getType();
Reid Spencer1628cec2006-10-26 06:15:43 +0000537 if (Ty->isFloatingPoint())
538 visitFPBinary(I, ISD::FREM, 0);
539 else
540 visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000541 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000542 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
543 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
544 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000545 void visitShl(User &I) { visitShift(I, ISD::SHL); }
546 void visitShr(User &I) {
547 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000548 }
549
Evan Chengf6f95812006-05-23 06:40:47 +0000550 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
551 ISD::CondCode FPOpc);
552 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
553 ISD::SETOEQ); }
554 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
555 ISD::SETUNE); }
556 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
557 ISD::SETOLE); }
558 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
559 ISD::SETOGE); }
560 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
561 ISD::SETOLT); }
562 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
563 ISD::SETOGT); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000564
Chris Lattner2bbd8102006-03-29 00:11:43 +0000565 void visitExtractElement(User &I);
566 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000567 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000568
Chris Lattner1c08c712005-01-07 07:47:53 +0000569 void visitGetElementPtr(User &I);
570 void visitCast(User &I);
571 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000572
573 void visitMalloc(MallocInst &I);
574 void visitFree(FreeInst &I);
575 void visitAlloca(AllocaInst &I);
576 void visitLoad(LoadInst &I);
577 void visitStore(StoreInst &I);
578 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
579 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000580 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000581 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000582 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000583
Chris Lattner1c08c712005-01-07 07:47:53 +0000584 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 void visitVAArg(VAArgInst &I);
586 void visitVAEnd(CallInst &I);
587 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000588 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000589
Chris Lattner7041ee32005-01-11 05:56:49 +0000590 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000591
592 void visitUserOp1(Instruction &I) {
593 assert(0 && "UserOp1 should not exist at instruction selection time!");
594 abort();
595 }
596 void visitUserOp2(Instruction &I) {
597 assert(0 && "UserOp2 should not exist at instruction selection time!");
598 abort();
599 }
600};
601} // end namespace llvm
602
Chris Lattner199862b2006-03-16 19:57:50 +0000603SDOperand SelectionDAGLowering::getValue(const Value *V) {
604 SDOperand &N = NodeMap[V];
605 if (N.Val) return N;
606
607 const Type *VTy = V->getType();
608 MVT::ValueType VT = TLI.getValueType(VTy);
609 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
611 visit(CE->getOpcode(), *CE);
612 assert(N.Val && "visit didn't populate the ValueMap!");
613 return N;
614 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
615 return N = DAG.getGlobalAddress(GV, VT);
616 } else if (isa<ConstantPointerNull>(C)) {
617 return N = DAG.getConstant(0, TLI.getPointerTy());
618 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000619 if (!isa<PackedType>(VTy))
620 return N = DAG.getNode(ISD::UNDEF, VT);
621
Chris Lattnerb2827b02006-03-19 00:52:58 +0000622 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000623 const PackedType *PTy = cast<PackedType>(VTy);
624 unsigned NumElements = PTy->getNumElements();
625 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
626
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000627 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000628 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
629
630 // Create a VConstant node with generic Vector type.
631 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
632 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000633 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
634 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000635 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
636 return N = DAG.getConstantFP(CFP->getValue(), VT);
637 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
638 unsigned NumElements = PTy->getNumElements();
639 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000640
641 // Now that we know the number and type of the elements, push a
642 // Constant or ConstantFP node onto the ops list for each element of
643 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000644 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000645 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000646 for (unsigned i = 0; i != NumElements; ++i)
647 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000648 } else {
649 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
650 SDOperand Op;
651 if (MVT::isFloatingPoint(PVT))
652 Op = DAG.getConstantFP(0, PVT);
653 else
654 Op = DAG.getConstant(0, PVT);
655 Ops.assign(NumElements, Op);
656 }
657
Chris Lattnerb2827b02006-03-19 00:52:58 +0000658 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000659 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
660 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000661 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000662 } else {
663 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000664 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000665 }
666 }
667
668 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
669 std::map<const AllocaInst*, int>::iterator SI =
670 FuncInfo.StaticAllocaMap.find(AI);
671 if (SI != FuncInfo.StaticAllocaMap.end())
672 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
673 }
674
675 std::map<const Value*, unsigned>::const_iterator VMI =
676 FuncInfo.ValueMap.find(V);
677 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
678
679 unsigned InReg = VMI->second;
680
681 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000682 if (VT != MVT::Vector) {
683 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000684
Chris Lattner70c2a612006-03-31 02:06:56 +0000685 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
686 if (DestVT < VT) {
687 // Source must be expanded. This input value is actually coming from the
688 // register pair VMI->second and VMI->second+1.
689 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
690 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
691 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000692 if (MVT::isFloatingPoint(VT))
693 N = DAG.getNode(ISD::FP_ROUND, VT, N);
694 else
695 N = DAG.getNode(ISD::TRUNCATE, VT, N);
696 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000697 } else {
698 // Otherwise, if this is a vector, make it available as a generic vector
699 // here.
700 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000701 const PackedType *PTy = cast<PackedType>(VTy);
702 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000703 PTyLegalElementVT);
704
705 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000706 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000707 if (PTyElementVT == PTyLegalElementVT) {
708 // If the value types are legal, just VBUILD the CopyFromReg nodes.
709 for (unsigned i = 0; i != NE; ++i)
710 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 PTyElementVT));
712 } else if (PTyElementVT < PTyLegalElementVT) {
713 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
714 for (unsigned i = 0; i != NE; ++i) {
715 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
716 PTyElementVT);
717 if (MVT::isFloatingPoint(PTyElementVT))
718 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
719 else
720 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
721 Ops.push_back(Op);
722 }
723 } else {
724 // If the register was expanded, use BUILD_PAIR.
725 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
726 for (unsigned i = 0; i != NE/2; ++i) {
727 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 PTyElementVT);
729 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
730 PTyElementVT);
731 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
732 }
733 }
734
735 Ops.push_back(DAG.getConstant(NE, MVT::i32));
736 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000737 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000738
739 // Finally, use a VBIT_CONVERT to make this available as the appropriate
740 // vector type.
741 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
742 DAG.getConstant(PTy->getNumElements(),
743 MVT::i32),
744 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000745 }
746
747 return N;
748}
749
750
Chris Lattner1c08c712005-01-07 07:47:53 +0000751void SelectionDAGLowering::visitRet(ReturnInst &I) {
752 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000753 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000754 return;
755 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000756 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000757 NewValues.push_back(getRoot());
758 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
759 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000760 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000761
762 // If this is an integer return value, we need to promote it ourselves to
763 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
764 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000765 // FIXME: C calling convention requires the return type to be promoted to
766 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000767 if (MVT::isInteger(RetOp.getValueType()) &&
768 RetOp.getValueType() < MVT::i64) {
769 MVT::ValueType TmpVT;
770 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
771 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
772 else
773 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000774
Evan Cheng8e7d0562006-05-26 23:09:09 +0000775 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000776 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
777 else
778 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
779 }
780 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000781 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000782 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000783 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
784 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000785}
786
Chris Lattner571e4342006-10-27 21:36:01 +0000787/// ExportFromCurrentBlock - If this condition isn't known to be exported from
788/// the current basic block, add it to ValueMap now so that we'll get a
789/// CopyTo/FromReg.
790void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
791 // No need to export constants.
792 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
793
794 // Already exported?
795 if (FuncInfo.isExportedInst(V)) return;
796
797 unsigned Reg = FuncInfo.InitializeRegForValue(V);
798 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
799}
800
801/// FindMergedConditions - If Cond is an expression like
802void SelectionDAGLowering::FindMergedConditions(Value *Cond,
803 MachineBasicBlock *TBB,
804 MachineBasicBlock *FBB,
805 MachineBasicBlock *CurBB,
806 unsigned Opc) {
807 // FIXME: HANDLE AND.
808 // FIXME: HANDLE NOT
809
810 // If this node is not part of the or/and tree, emit it as a branch.
811 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
812
813 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
814 BOp->getParent() != CurBB->getBasicBlock()) {
815 const BasicBlock *BB = CurBB->getBasicBlock();
816
817 // If the leaf of the tree is a setcond inst, merge the condition into the
818 // caseblock.
819 if (BOp && isa<SetCondInst>(BOp) &&
820 // The operands of the setcc have to be in this block. We don't know
821 // how to export them from some other block.
822 (!isa<Instruction>(BOp->getOperand(0)) ||
823 cast<Instruction>(BOp->getOperand(0))->getParent() == BB ||
824 FuncInfo.isExportedInst(BOp->getOperand(0))) &&
825 (!isa<Instruction>(BOp->getOperand(1)) ||
826 cast<Instruction>(BOp->getOperand(1))->getParent() == BB ||
827 FuncInfo.isExportedInst(BOp->getOperand(1)))) {
828 ExportFromCurrentBlock(BOp->getOperand(0));
829 ExportFromCurrentBlock(BOp->getOperand(1));
830
831 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
832 switch (BOp->getOpcode()) {
833 default: assert(0 && "Unknown setcc opcode!");
834 case Instruction::SetEQ:
835 SignCond = ISD::SETEQ;
836 UnsCond = ISD::SETEQ;
837 FPCond = ISD::SETOEQ;
838 break;
839 case Instruction::SetNE:
840 SignCond = ISD::SETNE;
841 UnsCond = ISD::SETNE;
842 FPCond = ISD::SETUNE;
843 break;
844 case Instruction::SetLE:
845 SignCond = ISD::SETLE;
846 UnsCond = ISD::SETULE;
847 FPCond = ISD::SETOLE;
848 break;
849 case Instruction::SetGE:
850 SignCond = ISD::SETGE;
851 UnsCond = ISD::SETUGE;
852 FPCond = ISD::SETOGE;
853 break;
854 case Instruction::SetLT:
855 SignCond = ISD::SETLT;
856 UnsCond = ISD::SETULT;
857 FPCond = ISD::SETOLT;
858 break;
859 case Instruction::SetGT:
860 SignCond = ISD::SETGT;
861 UnsCond = ISD::SETUGT;
862 FPCond = ISD::SETOGT;
863 break;
864 }
865
866 const Type *OpType = BOp->getOperand(0)->getType();
867 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
868 OpType = PTy->getElementType();
869
870 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
871 Condition = FPCond;
872 else if (OpType->isUnsigned())
873 Condition = UnsCond;
874 else
875 Condition = SignCond;
876
877 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
878 BOp->getOperand(1), TBB, FBB, CurBB);
879 SwitchCases.push_back(CB);
880 return;
881 }
882
883 // Create a CaseBlock record representing this branch.
884 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
885 TBB, FBB, CurBB);
886 SwitchCases.push_back(CB);
887 ExportFromCurrentBlock(Cond);
888 return;
889 }
890
891 // Codegen X | Y as:
892 // jmp_if_X TBB
893 // TmpBB:
894 // jmp_if_Y TBB
895 // jmp FBB
896 //
897 // This requires creation of TmpBB after CurBB.
898 MachineFunction::iterator BBI = CurBB;
899 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
900 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
901
902 // Emit the LHS condition.
903 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
904
905 // Emit the RHS condition into TmpBB.
906 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
907}
908
Chris Lattner1c08c712005-01-07 07:47:53 +0000909void SelectionDAGLowering::visitBr(BranchInst &I) {
910 // Update machine-CFG edges.
911 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000912
913 // Figure out which block is immediately after the current one.
914 MachineBasicBlock *NextBlock = 0;
915 MachineFunction::iterator BBI = CurMBB;
916 if (++BBI != CurMBB->getParent()->end())
917 NextBlock = BBI;
918
919 if (I.isUnconditional()) {
920 // If this is not a fall-through branch, emit the branch.
921 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000922 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000923 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000924
Chris Lattner57ab6592006-10-24 17:57:59 +0000925 // Update machine-CFG edges.
926 CurMBB->addSuccessor(Succ0MBB);
927
928 return;
929 }
930
931 // If this condition is one of the special cases we handle, do special stuff
932 // now.
933 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000934 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000935
936 // If this is a series of conditions that are or'd or and'd together, emit
937 // this as a sequence of branches instead of setcc's with and/or operations.
938 // For example, instead of something like:
939 // cmp A, B
940 // C = seteq
941 // cmp D, E
942 // F = setle
943 // or C, F
944 // jnz foo
945 // Emit:
946 // cmp A, B
947 // je foo
948 // cmp D, E
949 // jle foo
950 //
951 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
952 if (BOp->hasOneUse() &&
953 (/*BOp->getOpcode() == Instruction::And ||*/
954 BOp->getOpcode() == Instruction::Or)) {
955 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
956 //std::cerr << "FOUND: " << SwitchCases.size() << " merged conditions:\n";
957 //I.getParent()->dump();
958
959 visitSwitchCase(SwitchCases[0]);
960 SwitchCases.erase(SwitchCases.begin());
961 return;
962 }
963 }
Chris Lattner24525952006-10-24 18:07:37 +0000964
965 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +0000966 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +0000967 Succ0MBB, Succ1MBB, CurMBB);
968 // Use visitSwitchCase to actually insert the fast branch sequence for this
969 // cond branch.
970 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000971}
972
Nate Begemanf15485a2006-03-27 01:32:24 +0000973/// visitSwitchCase - Emits the necessary code to represent a single node in
974/// the binary search tree resulting from lowering a switch instruction.
975void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +0000976 SDOperand Cond;
977 SDOperand CondLHS = getValue(CB.CmpLHS);
978
Chris Lattner571e4342006-10-27 21:36:01 +0000979 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
980 // handle common cases produced by branch lowering.
981 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +0000982 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +0000983 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
984 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
985 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
986 } else
987 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +0000988
989 // Set NextBlock to be the MBB immediately after the current one, if any.
990 // This is used to avoid emitting unnecessary branches to the next block.
991 MachineBasicBlock *NextBlock = 0;
992 MachineFunction::iterator BBI = CurMBB;
993 if (++BBI != CurMBB->getParent()->end())
994 NextBlock = BBI;
995
996 // If the lhs block is the next block, invert the condition so that we can
997 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +0000998 if (CB.TrueBB == NextBlock) {
999 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001000 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1001 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1002 }
1003 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001004 DAG.getBasicBlock(CB.TrueBB));
1005 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001006 DAG.setRoot(BrCond);
1007 else
1008 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001009 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001010 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001011 CurMBB->addSuccessor(CB.TrueBB);
1012 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001013}
1014
Nate Begeman37efe672006-04-22 18:53:45 +00001015void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001016 // Emit the code for the jump table
1017 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng8825a482006-08-01 01:03:13 +00001018 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
1019 "Jump table entries are 32-bit values");
Evan Cheng2ae5b872006-09-24 05:22:38 +00001020 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng8825a482006-08-01 01:03:13 +00001021 // PIC jump table entries are 32-bit values.
Evan Cheng2ae5b872006-09-24 05:22:38 +00001022 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman37efe672006-04-22 18:53:45 +00001023 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1024 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng8825a482006-08-01 01:03:13 +00001025 DAG.getConstant(EntrySize, PTy));
Nate Begeman2f1ae882006-07-27 01:13:04 +00001026 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
1027 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng2ae5b872006-09-24 05:22:38 +00001028 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Cheng466685d2006-10-09 20:57:25 +00001029 NULL, 0);
Evan Cheng2ae5b872006-09-24 05:22:38 +00001030 if (isPIC) {
Andrew Lenharth16113432006-09-26 20:02:30 +00001031 // For Pic, the sequence is:
1032 // BRIND(load(Jumptable + index) + RelocBase)
1033 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenharth82c3d8f2006-10-11 04:29:42 +00001034 SDOperand Reloc;
1035 if (TLI.usesGlobalOffsetTable())
1036 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1037 else
1038 Reloc = TAB;
Chris Lattnere236ac62006-10-22 22:47:10 +00001039 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1040 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman2f1ae882006-07-27 01:13:04 +00001041 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
1042 } else {
1043 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
1044 }
Nate Begeman37efe672006-04-22 18:53:45 +00001045}
1046
Nate Begemanf15485a2006-03-27 01:32:24 +00001047void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1048 // Figure out which block is immediately after the current one.
1049 MachineBasicBlock *NextBlock = 0;
1050 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001051
Nate Begemanf15485a2006-03-27 01:32:24 +00001052 if (++BBI != CurMBB->getParent()->end())
1053 NextBlock = BBI;
1054
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001055 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1056
Nate Begemanf15485a2006-03-27 01:32:24 +00001057 // If there is only the default destination, branch to it if it is not the
1058 // next basic block. Otherwise, just fall through.
1059 if (I.getNumOperands() == 2) {
1060 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001061
Nate Begemanf15485a2006-03-27 01:32:24 +00001062 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001063 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001064 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001065 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001066
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001067 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001068 return;
1069 }
1070
1071 // If there are any non-default case statements, create a vector of Cases
1072 // representing each one, and sort the vector so that we can efficiently
1073 // create a binary search tree from them.
1074 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001075
Nate Begemanf15485a2006-03-27 01:32:24 +00001076 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1077 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1078 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1079 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001080
Nate Begemanf15485a2006-03-27 01:32:24 +00001081 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1082
1083 // Get the Value to be switched on and default basic blocks, which will be
1084 // inserted into CaseBlock records, representing basic blocks in the binary
1085 // search tree.
1086 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001087
1088 // Get the MachineFunction which holds the current MBB. This is used during
1089 // emission of jump tables, and when inserting any additional MBBs necessary
1090 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001091 MachineFunction *CurMF = CurMBB->getParent();
1092 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001093
1094 // If the switch has few cases (two or less) emit a series of specific
1095 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001096 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001097 // TODO: If any two of the cases has the same destination, and if one value
1098 // is the same as the other, but has one bit unset that the other has set,
1099 // use bit manipulation to do two compares at once. For example:
1100 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1101
Chris Lattnerb3543432006-10-23 18:38:22 +00001102 // Rearrange the case blocks so that the last one falls through if possible.
1103 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1104 // The last case block won't fall through into 'NextBlock' if we emit the
1105 // branches in this order. See if rearranging a case value would help.
1106 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1107 if (Cases[i].second == NextBlock) {
1108 std::swap(Cases[i], Cases.back());
1109 break;
1110 }
1111 }
1112 }
1113
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001114 // Create a CaseBlock record representing a conditional branch to
1115 // the Case's target mbb if the value being switched on SV is equal
1116 // to C.
1117 MachineBasicBlock *CurBlock = CurMBB;
1118 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1119 MachineBasicBlock *FallThrough;
1120 if (i != e-1) {
1121 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1122 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1123 } else {
1124 // If the last case doesn't match, go to the default block.
1125 FallThrough = Default;
1126 }
1127
1128 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1129 Cases[i].second, FallThrough, CurBlock);
1130
1131 // If emitting the first comparison, just call visitSwitchCase to emit the
1132 // code into the current block. Otherwise, push the CaseBlock onto the
1133 // vector to be later processed by SDISel, and insert the node's MBB
1134 // before the next MBB.
1135 if (CurBlock == CurMBB)
1136 visitSwitchCase(CB);
1137 else
1138 SwitchCases.push_back(CB);
1139
1140 CurBlock = FallThrough;
1141 }
1142 return;
1143 }
Nate Begeman37efe672006-04-22 18:53:45 +00001144
Nate Begeman17c275f2006-05-08 16:51:36 +00001145 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1146 // target supports indirect branches, then emit a jump table rather than
1147 // lowering the switch to a binary tree of conditional branches.
Nate Begeman9453eea2006-04-23 06:26:20 +00001148 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001149 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001150 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1151 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001152 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1153
Nate Begeman17c275f2006-05-08 16:51:36 +00001154 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001155 // Create a new basic block to hold the code for loading the address
1156 // of the jump table, and jumping to it. Update successor information;
1157 // we will either branch to the default case for the switch, or the jump
1158 // table.
1159 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1160 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1161 CurMBB->addSuccessor(Default);
1162 CurMBB->addSuccessor(JumpTableBB);
1163
1164 // Subtract the lowest switch case value from the value being switched on
1165 // and conditional branch to default mbb if the result is greater than the
1166 // difference between smallest and largest cases.
1167 SDOperand SwitchOp = getValue(SV);
1168 MVT::ValueType VT = SwitchOp.getValueType();
1169 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1170 DAG.getConstant(First, VT));
1171
1172 // The SDNode we just created, which holds the value being switched on
1173 // minus the the smallest case value, needs to be copied to a virtual
1174 // register so it can be used as an index into the jump table in a
1175 // subsequent basic block. This value may be smaller or larger than the
1176 // target's pointer type, and therefore require extension or truncating.
1177 if (VT > TLI.getPointerTy())
1178 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1179 else
1180 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001181
Nate Begeman37efe672006-04-22 18:53:45 +00001182 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1183 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1184
1185 // Emit the range check for the jump table, and branch to the default
1186 // block for the switch statement if the value being switched on exceeds
1187 // the largest case in the switch.
1188 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1189 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1190 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1191 DAG.getBasicBlock(Default)));
1192
Nate Begemanf4360a42006-05-03 03:48:02 +00001193 // Build a vector of destination BBs, corresponding to each target
1194 // of the jump table. If the value of the jump table slot corresponds to
1195 // a case statement, push the case's BB onto the vector, otherwise, push
1196 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001197 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001198 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001199 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001200 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001201 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001202 ++ii;
1203 } else {
1204 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001205 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001206
1207 // Update successor info
Chris Lattnerc66764c2006-09-10 06:36:57 +00001208 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1209 E = DestBBs.end(); I != E; ++I)
1210 JumpTableBB->addSuccessor(*I);
Nate Begemanf4360a42006-05-03 03:48:02 +00001211
1212 // Create a jump table index for this jump table, or return an existing
1213 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001214 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1215
1216 // Set the jump table information so that we can codegen it as a second
1217 // MachineBasicBlock
1218 JT.Reg = JumpTableReg;
1219 JT.JTI = JTI;
1220 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001221 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001222 return;
1223 }
1224 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001225
1226 // Push the initial CaseRec onto the worklist
1227 std::vector<CaseRec> CaseVec;
1228 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1229
1230 while (!CaseVec.empty()) {
1231 // Grab a record representing a case range to process off the worklist
1232 CaseRec CR = CaseVec.back();
1233 CaseVec.pop_back();
1234
1235 // Size is the number of Cases represented by this range. If Size is 1,
1236 // then we are processing a leaf of the binary search tree. Otherwise,
1237 // we need to pick a pivot, and push left and right ranges onto the
1238 // worklist.
1239 unsigned Size = CR.Range.second - CR.Range.first;
1240
1241 if (Size == 1) {
1242 // Create a CaseBlock record representing a conditional branch to
1243 // the Case's target mbb if the value being switched on SV is equal
1244 // to C. Otherwise, branch to default.
1245 Constant *C = CR.Range.first->first;
1246 MachineBasicBlock *Target = CR.Range.first->second;
1247 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1248 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001249
Nate Begemanf15485a2006-03-27 01:32:24 +00001250 // If the MBB representing the leaf node is the current MBB, then just
1251 // call visitSwitchCase to emit the code into the current block.
1252 // Otherwise, push the CaseBlock onto the vector to be later processed
1253 // by SDISel, and insert the node's MBB before the next MBB.
1254 if (CR.CaseBB == CurMBB)
1255 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001256 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001257 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001258 } else {
1259 // split case range at pivot
1260 CaseItr Pivot = CR.Range.first + (Size / 2);
1261 CaseRange LHSR(CR.Range.first, Pivot);
1262 CaseRange RHSR(Pivot, CR.Range.second);
1263 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001264 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001265
Nate Begemanf15485a2006-03-27 01:32:24 +00001266 // We know that we branch to the LHS if the Value being switched on is
1267 // less than the Pivot value, C. We use this to optimize our binary
1268 // tree a bit, by recognizing that if SV is greater than or equal to the
1269 // LHS's Case Value, and that Case Value is exactly one less than the
1270 // Pivot's Value, then we can branch directly to the LHS's Target,
1271 // rather than creating a leaf node for it.
1272 if ((LHSR.second - LHSR.first) == 1 &&
1273 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001274 cast<ConstantIntegral>(C)->getZExtValue() ==
1275 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001276 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001277 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001278 TrueBB = new MachineBasicBlock(LLVMBB);
1279 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1280 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001281 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001282
Nate Begemanf15485a2006-03-27 01:32:24 +00001283 // Similar to the optimization above, if the Value being switched on is
1284 // known to be less than the Constant CR.LT, and the current Case Value
1285 // is CR.LT - 1, then we can branch directly to the target block for
1286 // the current Case Value, rather than emitting a RHS leaf node for it.
1287 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001288 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1289 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001290 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001291 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001292 FalseBB = new MachineBasicBlock(LLVMBB);
1293 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1294 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001295 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001296
Nate Begemanf15485a2006-03-27 01:32:24 +00001297 // Create a CaseBlock record representing a conditional branch to
1298 // the LHS node if the value being switched on SV is less than C.
1299 // Otherwise, branch to LHS.
1300 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001301 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001302
Nate Begemanf15485a2006-03-27 01:32:24 +00001303 if (CR.CaseBB == CurMBB)
1304 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001305 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001306 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001307 }
1308 }
1309}
1310
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001311void SelectionDAGLowering::visitSub(User &I) {
1312 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001313 if (I.getType()->isFloatingPoint()) {
1314 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1315 if (CFP->isExactlyValue(-0.0)) {
1316 SDOperand Op2 = getValue(I.getOperand(1));
1317 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1318 return;
1319 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001320 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1321 } else
1322 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001323}
1324
Reid Spencer1628cec2006-10-26 06:15:43 +00001325void
1326SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001327 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001328 SDOperand Op1 = getValue(I.getOperand(0));
1329 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001330
Reid Spencer1628cec2006-10-26 06:15:43 +00001331 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001332 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1333 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1334 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001335 } else {
1336 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1337 }
1338}
1339
1340void
1341SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1342 const Type *Ty = I.getType();
1343 SDOperand Op1 = getValue(I.getOperand(0));
1344 SDOperand Op2 = getValue(I.getOperand(1));
1345
1346 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1347 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1348 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1349 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1350 } else {
1351 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001352 }
Nate Begemane21ea612005-11-18 07:42:56 +00001353}
Chris Lattner2c49f272005-01-19 22:31:21 +00001354
Nate Begemane21ea612005-11-18 07:42:56 +00001355void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1356 SDOperand Op1 = getValue(I.getOperand(0));
1357 SDOperand Op2 = getValue(I.getOperand(1));
1358
1359 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1360
Chris Lattner1c08c712005-01-07 07:47:53 +00001361 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1362}
1363
1364void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001365 ISD::CondCode UnsignedOpcode,
1366 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001367 SDOperand Op1 = getValue(I.getOperand(0));
1368 SDOperand Op2 = getValue(I.getOperand(1));
1369 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001370 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001371 Opcode = FPOpcode;
1372 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001373 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001374 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001375}
1376
1377void SelectionDAGLowering::visitSelect(User &I) {
1378 SDOperand Cond = getValue(I.getOperand(0));
1379 SDOperand TrueVal = getValue(I.getOperand(1));
1380 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001381 if (!isa<PackedType>(I.getType())) {
1382 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1383 TrueVal, FalseVal));
1384 } else {
1385 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1386 *(TrueVal.Val->op_end()-2),
1387 *(TrueVal.Val->op_end()-1)));
1388 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001389}
1390
1391void SelectionDAGLowering::visitCast(User &I) {
1392 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001393 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001394 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +00001395
Chris Lattnere25ca692006-03-22 20:09:35 +00001396 if (DestVT == MVT::Vector) {
1397 // This is a cast to a vector from something else. This is always a bit
1398 // convert. Get information about the input vector.
1399 const PackedType *DestTy = cast<PackedType>(I.getType());
1400 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1401 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1402 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1403 DAG.getValueType(EltVT)));
1404 } else if (SrcVT == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001405 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001406 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +00001407 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001408 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +00001409 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001410 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001411 } else if (isInteger(SrcVT)) {
1412 if (isInteger(DestVT)) { // Int -> Int cast
1413 if (DestVT < SrcVT) // Truncating cast?
1414 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001415 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001416 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001417 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001418 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner7e358902006-03-22 22:20:49 +00001419 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001420 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001421 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001422 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001423 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001424 } else {
1425 assert(0 && "Unknown cast!");
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001426 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001427 } else if (isFloatingPoint(SrcVT)) {
1428 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1429 if (DestVT < SrcVT) // Rounding cast?
1430 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001431 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001432 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001433 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001434 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001435 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001436 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001437 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001438 } else {
1439 assert(0 && "Unknown cast!");
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001440 }
1441 } else {
Chris Lattnere25ca692006-03-22 20:09:35 +00001442 assert(SrcVT == MVT::Vector && "Unknown cast!");
1443 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1444 // This is a cast from a vector to something else. This is always a bit
1445 // convert. Get information about the input vector.
1446 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner1c08c712005-01-07 07:47:53 +00001447 }
1448}
1449
Chris Lattner2bbd8102006-03-29 00:11:43 +00001450void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001451 SDOperand InVec = getValue(I.getOperand(0));
1452 SDOperand InVal = getValue(I.getOperand(1));
1453 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1454 getValue(I.getOperand(2)));
1455
Chris Lattner2332b9f2006-03-19 01:17:20 +00001456 SDOperand Num = *(InVec.Val->op_end()-2);
1457 SDOperand Typ = *(InVec.Val->op_end()-1);
1458 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1459 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001460}
1461
Chris Lattner2bbd8102006-03-29 00:11:43 +00001462void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001463 SDOperand InVec = getValue(I.getOperand(0));
1464 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1465 getValue(I.getOperand(1)));
1466 SDOperand Typ = *(InVec.Val->op_end()-1);
1467 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1468 TLI.getValueType(I.getType()), InVec, InIdx));
1469}
Chris Lattnerc7029802006-03-18 01:44:44 +00001470
Chris Lattner3e104b12006-04-08 04:15:24 +00001471void SelectionDAGLowering::visitShuffleVector(User &I) {
1472 SDOperand V1 = getValue(I.getOperand(0));
1473 SDOperand V2 = getValue(I.getOperand(1));
1474 SDOperand Mask = getValue(I.getOperand(2));
1475
1476 SDOperand Num = *(V1.Val->op_end()-2);
1477 SDOperand Typ = *(V2.Val->op_end()-1);
1478 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1479 V1, V2, Mask, Num, Typ));
1480}
1481
1482
Chris Lattner1c08c712005-01-07 07:47:53 +00001483void SelectionDAGLowering::visitGetElementPtr(User &I) {
1484 SDOperand N = getValue(I.getOperand(0));
1485 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001486
1487 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1488 OI != E; ++OI) {
1489 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001490 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001491 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001492 if (Field) {
1493 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001494 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001495 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001496 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001497 }
1498 Ty = StTy->getElementType(Field);
1499 } else {
1500 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001501
Chris Lattner7c0104b2005-11-09 04:45:33 +00001502 // If this is a constant subscript, handle it quickly.
1503 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001504 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001505 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001506 if (CI->getType()->isSigned())
1507 Offs = (int64_t)
1508 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001509 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001510 Offs =
1511 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001512 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1513 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001514 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001515
1516 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001517 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001518 SDOperand IdxN = getValue(Idx);
1519
1520 // If the index is smaller or larger than intptr_t, truncate or extend
1521 // it.
1522 if (IdxN.getValueType() < N.getValueType()) {
1523 if (Idx->getType()->isSigned())
1524 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1525 else
1526 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1527 } else if (IdxN.getValueType() > N.getValueType())
1528 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1529
1530 // If this is a multiply by a power of two, turn it into a shl
1531 // immediately. This is a very common case.
1532 if (isPowerOf2_64(ElementSize)) {
1533 unsigned Amt = Log2_64(ElementSize);
1534 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001535 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001536 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1537 continue;
1538 }
1539
1540 SDOperand Scale = getIntPtrConstant(ElementSize);
1541 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1542 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001543 }
1544 }
1545 setValue(&I, N);
1546}
1547
1548void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1549 // If this is a fixed sized alloca in the entry block of the function,
1550 // allocate it statically on the stack.
1551 if (FuncInfo.StaticAllocaMap.count(&I))
1552 return; // getValue will auto-populate this.
1553
1554 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001555 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1556 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001557 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001558
1559 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001560 MVT::ValueType IntPtr = TLI.getPointerTy();
1561 if (IntPtr < AllocSize.getValueType())
1562 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1563 else if (IntPtr > AllocSize.getValueType())
1564 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001565
Chris Lattner68cd65e2005-01-22 23:04:37 +00001566 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001567 getIntPtrConstant(TySize));
1568
1569 // Handle alignment. If the requested alignment is less than or equal to the
1570 // stack alignment, ignore it and round the size of the allocation up to the
1571 // stack alignment size. If the size is greater than the stack alignment, we
1572 // note this in the DYNAMIC_STACKALLOC node.
1573 unsigned StackAlign =
1574 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1575 if (Align <= StackAlign) {
1576 Align = 0;
1577 // Add SA-1 to the size.
1578 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1579 getIntPtrConstant(StackAlign-1));
1580 // Mask out the low bits for alignment purposes.
1581 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1582 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1583 }
1584
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001585 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001586 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1587 MVT::Other);
1588 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001589 DAG.setRoot(setValue(&I, DSA).getValue(1));
1590
1591 // Inform the Frame Information that we have just allocated a variable-sized
1592 // object.
1593 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1594}
1595
Chris Lattner1c08c712005-01-07 07:47:53 +00001596void SelectionDAGLowering::visitLoad(LoadInst &I) {
1597 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001598
Chris Lattnerd3948112005-01-17 22:19:26 +00001599 SDOperand Root;
1600 if (I.isVolatile())
1601 Root = getRoot();
1602 else {
1603 // Do not serialize non-volatile loads against each other.
1604 Root = DAG.getRoot();
1605 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001606
Evan Cheng466685d2006-10-09 20:57:25 +00001607 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001608 Root, I.isVolatile()));
1609}
1610
1611SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001612 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001613 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001614 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001615 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001616 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001617 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1618 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001619 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001620 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001621 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001622
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001623 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001624 DAG.setRoot(L.getValue(1));
1625 else
1626 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001627
1628 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001629}
1630
1631
1632void SelectionDAGLowering::visitStore(StoreInst &I) {
1633 Value *SrcV = I.getOperand(0);
1634 SDOperand Src = getValue(SrcV);
1635 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001636 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1637 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001638}
1639
Chris Lattner0eade312006-03-24 02:22:33 +00001640/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1641/// access memory and has no other side effects at all.
1642static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1643#define GET_NO_MEMORY_INTRINSICS
1644#include "llvm/Intrinsics.gen"
1645#undef GET_NO_MEMORY_INTRINSICS
1646 return false;
1647}
1648
Chris Lattnere58a7802006-04-02 03:41:14 +00001649// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1650// have any side-effects or if it only reads memory.
1651static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1652#define GET_SIDE_EFFECT_INFO
1653#include "llvm/Intrinsics.gen"
1654#undef GET_SIDE_EFFECT_INFO
1655 return false;
1656}
1657
Chris Lattner0eade312006-03-24 02:22:33 +00001658/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1659/// node.
1660void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1661 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001662 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001663 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001664
1665 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001666 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001667 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1668 if (OnlyLoad) {
1669 // We don't need to serialize loads against other loads.
1670 Ops.push_back(DAG.getRoot());
1671 } else {
1672 Ops.push_back(getRoot());
1673 }
1674 }
Chris Lattner0eade312006-03-24 02:22:33 +00001675
1676 // Add the intrinsic ID as an integer operand.
1677 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1678
1679 // Add all operands of the call to the operand list.
1680 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1681 SDOperand Op = getValue(I.getOperand(i));
1682
1683 // If this is a vector type, force it to the right packed type.
1684 if (Op.getValueType() == MVT::Vector) {
1685 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1686 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1687
1688 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1689 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1690 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1691 }
1692
1693 assert(TLI.isTypeLegal(Op.getValueType()) &&
1694 "Intrinsic uses a non-legal type?");
1695 Ops.push_back(Op);
1696 }
1697
1698 std::vector<MVT::ValueType> VTs;
1699 if (I.getType() != Type::VoidTy) {
1700 MVT::ValueType VT = TLI.getValueType(I.getType());
1701 if (VT == MVT::Vector) {
1702 const PackedType *DestTy = cast<PackedType>(I.getType());
1703 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1704
1705 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1706 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1707 }
1708
1709 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1710 VTs.push_back(VT);
1711 }
1712 if (HasChain)
1713 VTs.push_back(MVT::Other);
1714
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001715 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1716
Chris Lattner0eade312006-03-24 02:22:33 +00001717 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001718 SDOperand Result;
1719 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001720 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1721 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001722 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001723 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1724 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001725 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001726 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1727 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001728
Chris Lattnere58a7802006-04-02 03:41:14 +00001729 if (HasChain) {
1730 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1731 if (OnlyLoad)
1732 PendingLoads.push_back(Chain);
1733 else
1734 DAG.setRoot(Chain);
1735 }
Chris Lattner0eade312006-03-24 02:22:33 +00001736 if (I.getType() != Type::VoidTy) {
1737 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1738 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1739 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1740 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1741 DAG.getValueType(EVT));
1742 }
1743 setValue(&I, Result);
1744 }
1745}
1746
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001747/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1748/// we want to emit this as a call to a named external function, return the name
1749/// otherwise lower it and return null.
1750const char *
1751SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1752 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001753 default:
1754 // By default, turn this into a target intrinsic node.
1755 visitTargetIntrinsic(I, Intrinsic);
1756 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001757 case Intrinsic::vastart: visitVAStart(I); return 0;
1758 case Intrinsic::vaend: visitVAEnd(I); return 0;
1759 case Intrinsic::vacopy: visitVACopy(I); return 0;
1760 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1761 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1762 case Intrinsic::setjmp:
1763 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1764 break;
1765 case Intrinsic::longjmp:
1766 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1767 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001768 case Intrinsic::memcpy_i32:
1769 case Intrinsic::memcpy_i64:
1770 visitMemIntrinsic(I, ISD::MEMCPY);
1771 return 0;
1772 case Intrinsic::memset_i32:
1773 case Intrinsic::memset_i64:
1774 visitMemIntrinsic(I, ISD::MEMSET);
1775 return 0;
1776 case Intrinsic::memmove_i32:
1777 case Intrinsic::memmove_i64:
1778 visitMemIntrinsic(I, ISD::MEMMOVE);
1779 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001780
Chris Lattner86cb6432005-12-13 17:40:33 +00001781 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001782 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001783 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001784 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001785 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001786
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001787 Ops[0] = getRoot();
1788 Ops[1] = getValue(SPI.getLineValue());
1789 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001790
Jim Laskey43970fe2006-03-23 18:06:46 +00001791 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001792 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001793 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1794
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001795 Ops[3] = DAG.getString(CompileUnit->getFileName());
1796 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001797
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001798 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001799 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001800
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001801 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001802 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001803 case Intrinsic::dbg_region_start: {
1804 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1805 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001806 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001807 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001808 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1809 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001810 }
1811
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001812 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001813 }
1814 case Intrinsic::dbg_region_end: {
1815 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1816 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001817 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001818 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001819 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1820 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001821 }
1822
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001823 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001824 }
1825 case Intrinsic::dbg_func_start: {
1826 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1827 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001828 if (DebugInfo && FSI.getSubprogram() &&
1829 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001830 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001831 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1832 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001833 }
1834
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001835 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001836 }
1837 case Intrinsic::dbg_declare: {
1838 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1839 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00001840 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00001841 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001842 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00001843 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00001844 }
1845
1846 return 0;
1847 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001848
Reid Spencer0b118202006-01-16 21:12:35 +00001849 case Intrinsic::isunordered_f32:
1850 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001851 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1852 getValue(I.getOperand(2)), ISD::SETUO));
1853 return 0;
1854
Reid Spencer0b118202006-01-16 21:12:35 +00001855 case Intrinsic::sqrt_f32:
1856 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001857 setValue(&I, DAG.getNode(ISD::FSQRT,
1858 getValue(I.getOperand(1)).getValueType(),
1859 getValue(I.getOperand(1))));
1860 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00001861 case Intrinsic::powi_f32:
1862 case Intrinsic::powi_f64:
1863 setValue(&I, DAG.getNode(ISD::FPOWI,
1864 getValue(I.getOperand(1)).getValueType(),
1865 getValue(I.getOperand(1)),
1866 getValue(I.getOperand(2))));
1867 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001868 case Intrinsic::pcmarker: {
1869 SDOperand Tmp = getValue(I.getOperand(1));
1870 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1871 return 0;
1872 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001873 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001874 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001875 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1876 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1877 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001878 setValue(&I, Tmp);
1879 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001880 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001881 }
Nate Begemand88fc032006-01-14 03:14:10 +00001882 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001883 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001884 case Intrinsic::bswap_i64:
1885 setValue(&I, DAG.getNode(ISD::BSWAP,
1886 getValue(I.getOperand(1)).getValueType(),
1887 getValue(I.getOperand(1))));
1888 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001889 case Intrinsic::cttz_i8:
1890 case Intrinsic::cttz_i16:
1891 case Intrinsic::cttz_i32:
1892 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001893 setValue(&I, DAG.getNode(ISD::CTTZ,
1894 getValue(I.getOperand(1)).getValueType(),
1895 getValue(I.getOperand(1))));
1896 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001897 case Intrinsic::ctlz_i8:
1898 case Intrinsic::ctlz_i16:
1899 case Intrinsic::ctlz_i32:
1900 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001901 setValue(&I, DAG.getNode(ISD::CTLZ,
1902 getValue(I.getOperand(1)).getValueType(),
1903 getValue(I.getOperand(1))));
1904 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001905 case Intrinsic::ctpop_i8:
1906 case Intrinsic::ctpop_i16:
1907 case Intrinsic::ctpop_i32:
1908 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001909 setValue(&I, DAG.getNode(ISD::CTPOP,
1910 getValue(I.getOperand(1)).getValueType(),
1911 getValue(I.getOperand(1))));
1912 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001913 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001914 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001915 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1916 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00001917 setValue(&I, Tmp);
1918 DAG.setRoot(Tmp.getValue(1));
1919 return 0;
1920 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001921 case Intrinsic::stackrestore: {
1922 SDOperand Tmp = getValue(I.getOperand(1));
1923 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001924 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001925 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001926 case Intrinsic::prefetch:
1927 // FIXME: Currently discarding prefetches.
1928 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001929 }
1930}
1931
1932
Chris Lattner1c08c712005-01-07 07:47:53 +00001933void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001934 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001935 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001936 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001937 if (unsigned IID = F->getIntrinsicID()) {
1938 RenameFn = visitIntrinsicCall(I, IID);
1939 if (!RenameFn)
1940 return;
1941 } else { // Not an LLVM intrinsic.
1942 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001943 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1944 if (I.getNumOperands() == 3 && // Basic sanity checks.
1945 I.getOperand(1)->getType()->isFloatingPoint() &&
1946 I.getType() == I.getOperand(1)->getType() &&
1947 I.getType() == I.getOperand(2)->getType()) {
1948 SDOperand LHS = getValue(I.getOperand(1));
1949 SDOperand RHS = getValue(I.getOperand(2));
1950 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1951 LHS, RHS));
1952 return;
1953 }
1954 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001955 if (I.getNumOperands() == 2 && // Basic sanity checks.
1956 I.getOperand(1)->getType()->isFloatingPoint() &&
1957 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001958 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001959 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1960 return;
1961 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001962 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001963 if (I.getNumOperands() == 2 && // Basic sanity checks.
1964 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001965 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001966 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001967 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1968 return;
1969 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001970 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001971 if (I.getNumOperands() == 2 && // Basic sanity checks.
1972 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001973 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001974 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001975 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1976 return;
1977 }
1978 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001979 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001980 } else if (isa<InlineAsm>(I.getOperand(0))) {
1981 visitInlineAsm(I);
1982 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001983 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001984
Chris Lattner64e14b12005-01-08 22:48:57 +00001985 SDOperand Callee;
1986 if (!RenameFn)
1987 Callee = getValue(I.getOperand(0));
1988 else
1989 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001990 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001991 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001992 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1993 Value *Arg = I.getOperand(i);
1994 SDOperand ArgNode = getValue(Arg);
1995 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1996 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001997
Nate Begeman8e21e712005-03-26 01:29:23 +00001998 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1999 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00002000
Chris Lattnercf5734d2005-01-08 19:26:18 +00002001 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00002002 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00002003 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002004 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002005 setValue(&I, Result.first);
2006 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002007}
2008
Chris Lattner864635a2006-02-22 22:37:12 +00002009SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002010 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002011 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2012 Chain = Val.getValue(1);
2013 Flag = Val.getValue(2);
2014
2015 // If the result was expanded, copy from the top part.
2016 if (Regs.size() > 1) {
2017 assert(Regs.size() == 2 &&
2018 "Cannot expand to more than 2 elts yet!");
2019 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002020 Chain = Hi.getValue(1);
2021 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002022 if (DAG.getTargetLoweringInfo().isLittleEndian())
2023 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2024 else
2025 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002026 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002027
Chris Lattnercf752aa2006-06-08 18:22:48 +00002028 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002029 // appropriate type.
2030 if (RegVT == ValueVT)
2031 return Val;
2032
Chris Lattnercf752aa2006-06-08 18:22:48 +00002033 if (MVT::isInteger(RegVT)) {
2034 if (ValueVT < RegVT)
2035 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2036 else
2037 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2038 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002039 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002040 }
Chris Lattner864635a2006-02-22 22:37:12 +00002041}
2042
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002043/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2044/// specified value into the registers specified by this object. This uses
2045/// Chain/Flag as the input and updates them for the output Chain/Flag.
2046void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002047 SDOperand &Chain, SDOperand &Flag,
2048 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002049 if (Regs.size() == 1) {
2050 // If there is a single register and the types differ, this must be
2051 // a promotion.
2052 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002053 if (MVT::isInteger(RegVT)) {
2054 if (RegVT < ValueVT)
2055 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2056 else
2057 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2058 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002059 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2060 }
2061 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2062 Flag = Chain.getValue(1);
2063 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002064 std::vector<unsigned> R(Regs);
2065 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2066 std::reverse(R.begin(), R.end());
2067
2068 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002069 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002070 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002071 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002072 Flag = Chain.getValue(1);
2073 }
2074 }
2075}
Chris Lattner864635a2006-02-22 22:37:12 +00002076
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002077/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2078/// operand list. This adds the code marker and includes the number of
2079/// values added into it.
2080void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002081 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002082 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2083 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2084 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2085}
Chris Lattner864635a2006-02-22 22:37:12 +00002086
2087/// isAllocatableRegister - If the specified register is safe to allocate,
2088/// i.e. it isn't a stack pointer or some other special register, return the
2089/// register class for the register. Otherwise, return null.
2090static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002091isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2092 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002093 MVT::ValueType FoundVT = MVT::Other;
2094 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002095 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2096 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002097 MVT::ValueType ThisVT = MVT::Other;
2098
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002099 const TargetRegisterClass *RC = *RCI;
2100 // If none of the the value types for this register class are valid, we
2101 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002102 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2103 I != E; ++I) {
2104 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002105 // If we have already found this register in a different register class,
2106 // choose the one with the largest VT specified. For example, on
2107 // PowerPC, we favor f64 register classes over f32.
2108 if (FoundVT == MVT::Other ||
2109 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2110 ThisVT = *I;
2111 break;
2112 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002113 }
2114 }
2115
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002116 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002117
Chris Lattner864635a2006-02-22 22:37:12 +00002118 // NOTE: This isn't ideal. In particular, this might allocate the
2119 // frame pointer in functions that need it (due to them not being taken
2120 // out of allocation, because a variable sized allocation hasn't been seen
2121 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002122 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2123 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002124 if (*I == Reg) {
2125 // We found a matching register class. Keep looking at others in case
2126 // we find one with larger registers that this physreg is also in.
2127 FoundRC = RC;
2128 FoundVT = ThisVT;
2129 break;
2130 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002131 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002132 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002133}
2134
2135RegsForValue SelectionDAGLowering::
2136GetRegistersForValue(const std::string &ConstrCode,
2137 MVT::ValueType VT, bool isOutReg, bool isInReg,
2138 std::set<unsigned> &OutputRegs,
2139 std::set<unsigned> &InputRegs) {
2140 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2141 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2142 std::vector<unsigned> Regs;
2143
2144 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2145 MVT::ValueType RegVT;
2146 MVT::ValueType ValueVT = VT;
2147
2148 if (PhysReg.first) {
2149 if (VT == MVT::Other)
2150 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002151
2152 // Get the actual register value type. This is important, because the user
2153 // may have asked for (e.g.) the AX register in i32 type. We need to
2154 // remember that AX is actually i16 to get the right extension.
2155 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002156
2157 // This is a explicit reference to a physical register.
2158 Regs.push_back(PhysReg.first);
2159
2160 // If this is an expanded reference, add the rest of the regs to Regs.
2161 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002162 TargetRegisterClass::iterator I = PhysReg.second->begin();
2163 TargetRegisterClass::iterator E = PhysReg.second->end();
2164 for (; *I != PhysReg.first; ++I)
2165 assert(I != E && "Didn't find reg!");
2166
2167 // Already added the first reg.
2168 --NumRegs; ++I;
2169 for (; NumRegs; --NumRegs, ++I) {
2170 assert(I != E && "Ran out of registers to allocate!");
2171 Regs.push_back(*I);
2172 }
2173 }
2174 return RegsForValue(Regs, RegVT, ValueVT);
2175 }
2176
2177 // This is a reference to a register class. Allocate NumRegs consecutive,
2178 // available, registers from the class.
2179 std::vector<unsigned> RegClassRegs =
2180 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2181
2182 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2183 MachineFunction &MF = *CurMBB->getParent();
2184 unsigned NumAllocated = 0;
2185 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2186 unsigned Reg = RegClassRegs[i];
2187 // See if this register is available.
2188 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2189 (isInReg && InputRegs.count(Reg))) { // Already used.
2190 // Make sure we find consecutive registers.
2191 NumAllocated = 0;
2192 continue;
2193 }
2194
2195 // Check to see if this register is allocatable (i.e. don't give out the
2196 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002197 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002198 if (!RC) {
2199 // Make sure we find consecutive registers.
2200 NumAllocated = 0;
2201 continue;
2202 }
2203
2204 // Okay, this register is good, we can use it.
2205 ++NumAllocated;
2206
2207 // If we allocated enough consecutive
2208 if (NumAllocated == NumRegs) {
2209 unsigned RegStart = (i-NumAllocated)+1;
2210 unsigned RegEnd = i+1;
2211 // Mark all of the allocated registers used.
2212 for (unsigned i = RegStart; i != RegEnd; ++i) {
2213 unsigned Reg = RegClassRegs[i];
2214 Regs.push_back(Reg);
2215 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2216 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2217 }
2218
2219 return RegsForValue(Regs, *RC->vt_begin(), VT);
2220 }
2221 }
2222
2223 // Otherwise, we couldn't allocate enough registers for this.
2224 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002225}
2226
Chris Lattner864635a2006-02-22 22:37:12 +00002227
Chris Lattnerce7518c2006-01-26 22:24:51 +00002228/// visitInlineAsm - Handle a call to an InlineAsm object.
2229///
2230void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2231 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2232
2233 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2234 MVT::Other);
2235
2236 // Note, we treat inline asms both with and without side-effects as the same.
2237 // If an inline asm doesn't have side effects and doesn't access memory, we
2238 // could not choose to not chain it.
2239 bool hasSideEffects = IA->hasSideEffects();
2240
Chris Lattner2cc2f662006-02-01 01:28:23 +00002241 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002242 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002243
2244 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2245 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2246 /// if it is a def of that register.
2247 std::vector<SDOperand> AsmNodeOperands;
2248 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2249 AsmNodeOperands.push_back(AsmStr);
2250
2251 SDOperand Chain = getRoot();
2252 SDOperand Flag;
2253
Chris Lattner4e4b5762006-02-01 18:59:47 +00002254 // We fully assign registers here at isel time. This is not optimal, but
2255 // should work. For register classes that correspond to LLVM classes, we
2256 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2257 // over the constraints, collecting fixed registers that we know we can't use.
2258 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002259 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002260 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2261 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2262 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002263
Chris Lattner1efa40f2006-02-22 00:56:39 +00002264 MVT::ValueType OpVT;
2265
2266 // Compute the value type for each operand and add it to ConstraintVTs.
2267 switch (Constraints[i].Type) {
2268 case InlineAsm::isOutput:
2269 if (!Constraints[i].isIndirectOutput) {
2270 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2271 OpVT = TLI.getValueType(I.getType());
2272 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002273 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002274 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2275 OpNum++; // Consumes a call operand.
2276 }
2277 break;
2278 case InlineAsm::isInput:
2279 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2280 OpNum++; // Consumes a call operand.
2281 break;
2282 case InlineAsm::isClobber:
2283 OpVT = MVT::Other;
2284 break;
2285 }
2286
2287 ConstraintVTs.push_back(OpVT);
2288
Chris Lattner864635a2006-02-22 22:37:12 +00002289 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2290 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002291
Chris Lattner864635a2006-02-22 22:37:12 +00002292 // Build a list of regs that this operand uses. This always has a single
2293 // element for promoted/expanded operands.
2294 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2295 false, false,
2296 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002297
2298 switch (Constraints[i].Type) {
2299 case InlineAsm::isOutput:
2300 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002301 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002302 // If this is an early-clobber output, it cannot be assigned to the same
2303 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002304 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002305 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002306 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002307 case InlineAsm::isInput:
2308 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002309 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002310 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002311 case InlineAsm::isClobber:
2312 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002313 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2314 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002315 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002316 }
2317 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002318
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002319 // Loop over all of the inputs, copying the operand values into the
2320 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002321 RegsForValue RetValRegs;
2322 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002323 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002324
Chris Lattner6656dd12006-01-31 02:03:41 +00002325 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002326 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2327 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002328
Chris Lattner2cc2f662006-02-01 01:28:23 +00002329 switch (Constraints[i].Type) {
2330 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002331 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2332 if (ConstraintCode.size() == 1) // not a physreg name.
2333 CTy = TLI.getConstraintType(ConstraintCode[0]);
2334
2335 if (CTy == TargetLowering::C_Memory) {
2336 // Memory output.
2337 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2338
2339 // Check that the operand (the address to store to) isn't a float.
2340 if (!MVT::isInteger(InOperandVal.getValueType()))
2341 assert(0 && "MATCH FAIL!");
2342
2343 if (!Constraints[i].isIndirectOutput)
2344 assert(0 && "MATCH FAIL!");
2345
2346 OpNum++; // Consumes a call operand.
2347
2348 // Extend/truncate to the right pointer type if needed.
2349 MVT::ValueType PtrType = TLI.getPointerTy();
2350 if (InOperandVal.getValueType() < PtrType)
2351 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2352 else if (InOperandVal.getValueType() > PtrType)
2353 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2354
2355 // Add information to the INLINEASM node to know about this output.
2356 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2357 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2358 AsmNodeOperands.push_back(InOperandVal);
2359 break;
2360 }
2361
2362 // Otherwise, this is a register output.
2363 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2364
Chris Lattner864635a2006-02-22 22:37:12 +00002365 // If this is an early-clobber output, or if there is an input
2366 // constraint that matches this, we need to reserve the input register
2367 // so no other inputs allocate to it.
2368 bool UsesInputRegister = false;
2369 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2370 UsesInputRegister = true;
2371
2372 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002373 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002374 RegsForValue Regs =
2375 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2376 true, UsesInputRegister,
2377 OutputRegs, InputRegs);
2378 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00002379
Chris Lattner2cc2f662006-02-01 01:28:23 +00002380 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002381 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002382 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002383 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002384 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002385 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002386 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2387 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002388 OpNum++; // Consumes a call operand.
2389 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002390
2391 // Add information to the INLINEASM node to know that this register is
2392 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002393 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002394 break;
2395 }
2396 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002397 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002398 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002399
Chris Lattner2223aea2006-02-02 00:25:23 +00002400 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2401 // If this is required to match an output register we have already set,
2402 // just use its register.
2403 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002404
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002405 // Scan until we find the definition we already emitted of this operand.
2406 // When we find it, create a RegsForValue operand.
2407 unsigned CurOp = 2; // The first operand.
2408 for (; OperandNo; --OperandNo) {
2409 // Advance to the next operand.
2410 unsigned NumOps =
2411 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002412 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2413 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002414 "Skipped past definitions?");
2415 CurOp += (NumOps>>3)+1;
2416 }
2417
2418 unsigned NumOps =
2419 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2420 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2421 "Skipped past definitions?");
2422
2423 // Add NumOps>>3 registers to MatchedRegs.
2424 RegsForValue MatchedRegs;
2425 MatchedRegs.ValueVT = InOperandVal.getValueType();
2426 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2427 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2428 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2429 MatchedRegs.Regs.push_back(Reg);
2430 }
2431
2432 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002433 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2434 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002435 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002436 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002437 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002438
2439 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2440 if (ConstraintCode.size() == 1) // not a physreg name.
2441 CTy = TLI.getConstraintType(ConstraintCode[0]);
2442
2443 if (CTy == TargetLowering::C_Other) {
2444 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2445 assert(0 && "MATCH FAIL!");
2446
2447 // Add information to the INLINEASM node to know about this input.
2448 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2449 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2450 AsmNodeOperands.push_back(InOperandVal);
2451 break;
2452 } else if (CTy == TargetLowering::C_Memory) {
2453 // Memory input.
2454
2455 // Check that the operand isn't a float.
2456 if (!MVT::isInteger(InOperandVal.getValueType()))
2457 assert(0 && "MATCH FAIL!");
2458
2459 // Extend/truncate to the right pointer type if needed.
2460 MVT::ValueType PtrType = TLI.getPointerTy();
2461 if (InOperandVal.getValueType() < PtrType)
2462 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2463 else if (InOperandVal.getValueType() > PtrType)
2464 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2465
2466 // Add information to the INLINEASM node to know about this input.
2467 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2468 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2469 AsmNodeOperands.push_back(InOperandVal);
2470 break;
2471 }
2472
2473 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2474
2475 // Copy the input into the appropriate registers.
2476 RegsForValue InRegs =
2477 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2478 false, true, OutputRegs, InputRegs);
2479 // FIXME: should be match fail.
2480 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2481
Evan Chenga8441262006-06-15 08:11:54 +00002482 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002483
2484 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002485 break;
2486 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002487 case InlineAsm::isClobber: {
2488 RegsForValue ClobberedRegs =
2489 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2490 OutputRegs, InputRegs);
2491 // Add the clobbered value to the operand list, so that the register
2492 // allocator is aware that the physreg got clobbered.
2493 if (!ClobberedRegs.Regs.empty())
2494 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002495 break;
2496 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002497 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002498 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002499
2500 // Finish up input operands.
2501 AsmNodeOperands[0] = Chain;
2502 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2503
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002504 Chain = DAG.getNode(ISD::INLINEASM,
2505 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002506 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002507 Flag = Chain.getValue(1);
2508
Chris Lattner6656dd12006-01-31 02:03:41 +00002509 // If this asm returns a register value, copy the result from that register
2510 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002511 if (!RetValRegs.Regs.empty())
2512 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002513
Chris Lattner6656dd12006-01-31 02:03:41 +00002514 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2515
2516 // Process indirect outputs, first output all of the flagged copies out of
2517 // physregs.
2518 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002519 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002520 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002521 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2522 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002523 }
2524
2525 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002526 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002527 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002528 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002529 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002530 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002531 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002532 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2533 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002534 DAG.setRoot(Chain);
2535}
2536
2537
Chris Lattner1c08c712005-01-07 07:47:53 +00002538void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2539 SDOperand Src = getValue(I.getOperand(0));
2540
2541 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002542
2543 if (IntPtr < Src.getValueType())
2544 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2545 else if (IntPtr > Src.getValueType())
2546 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002547
2548 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002549 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002550 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2551 Src, getIntPtrConstant(ElementSize));
2552
2553 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002554 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002555
2556 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002557 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002558 DAG.getExternalSymbol("malloc", IntPtr),
2559 Args, DAG);
2560 setValue(&I, Result.first); // Pointers always fit in registers
2561 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002562}
2563
2564void SelectionDAGLowering::visitFree(FreeInst &I) {
2565 std::vector<std::pair<SDOperand, const Type*> > Args;
2566 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002567 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002568 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002569 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002570 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002571 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2572 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002573}
2574
Chris Lattner025c39b2005-08-26 20:54:47 +00002575// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2576// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2577// instructions are special in various ways, which require special support to
2578// insert. The specified MachineInstr is created but not inserted into any
2579// basic blocks, and the scheduler passes ownership of it to this method.
2580MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2581 MachineBasicBlock *MBB) {
2582 std::cerr << "If a target marks an instruction with "
2583 "'usesCustomDAGSchedInserter', it must implement "
2584 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2585 abort();
2586 return 0;
2587}
2588
Chris Lattner39ae3622005-01-09 00:00:49 +00002589void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002590 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2591 getValue(I.getOperand(1)),
2592 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002593}
2594
2595void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002596 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2597 getValue(I.getOperand(0)),
2598 DAG.getSrcValue(I.getOperand(0)));
2599 setValue(&I, V);
2600 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002601}
2602
2603void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002604 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2605 getValue(I.getOperand(1)),
2606 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002607}
2608
2609void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002610 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2611 getValue(I.getOperand(1)),
2612 getValue(I.getOperand(2)),
2613 DAG.getSrcValue(I.getOperand(1)),
2614 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002615}
2616
Chris Lattnerfdfded52006-04-12 16:20:43 +00002617/// TargetLowering::LowerArguments - This is the default LowerArguments
2618/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002619/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2620/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002621std::vector<SDOperand>
2622TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2623 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2624 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002625 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002626 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2627 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2628
2629 // Add one result value for each formal argument.
2630 std::vector<MVT::ValueType> RetVals;
2631 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2632 MVT::ValueType VT = getValueType(I->getType());
2633
2634 switch (getTypeAction(VT)) {
2635 default: assert(0 && "Unknown type action!");
2636 case Legal:
2637 RetVals.push_back(VT);
2638 break;
2639 case Promote:
2640 RetVals.push_back(getTypeToTransformTo(VT));
2641 break;
2642 case Expand:
2643 if (VT != MVT::Vector) {
2644 // If this is a large integer, it needs to be broken up into small
2645 // integers. Figure out what the destination type is and how many small
2646 // integers it turns into.
2647 MVT::ValueType NVT = getTypeToTransformTo(VT);
2648 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2649 for (unsigned i = 0; i != NumVals; ++i)
2650 RetVals.push_back(NVT);
2651 } else {
2652 // Otherwise, this is a vector type. We only support legal vectors
2653 // right now.
2654 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2655 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002656
Chris Lattnerfdfded52006-04-12 16:20:43 +00002657 // Figure out if there is a Packed type corresponding to this Vector
2658 // type. If so, convert to the packed type.
2659 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2660 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2661 RetVals.push_back(TVT);
2662 } else {
2663 assert(0 && "Don't support illegal by-val vector arguments yet!");
2664 }
2665 }
2666 break;
2667 }
2668 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002669
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002670 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002671
2672 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002673 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2674 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002675 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002676
2677 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002678
2679 // Set up the return result vector.
2680 Ops.clear();
2681 unsigned i = 0;
2682 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2683 MVT::ValueType VT = getValueType(I->getType());
2684
2685 switch (getTypeAction(VT)) {
2686 default: assert(0 && "Unknown type action!");
2687 case Legal:
2688 Ops.push_back(SDOperand(Result, i++));
2689 break;
2690 case Promote: {
2691 SDOperand Op(Result, i++);
2692 if (MVT::isInteger(VT)) {
2693 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2694 : ISD::AssertZext;
2695 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2696 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2697 } else {
2698 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2699 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2700 }
2701 Ops.push_back(Op);
2702 break;
2703 }
2704 case Expand:
2705 if (VT != MVT::Vector) {
2706 // If this is a large integer, it needs to be reassembled from small
2707 // integers. Figure out what the source elt type is and how many small
2708 // integers it is.
2709 MVT::ValueType NVT = getTypeToTransformTo(VT);
2710 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2711 if (NumVals == 2) {
2712 SDOperand Lo = SDOperand(Result, i++);
2713 SDOperand Hi = SDOperand(Result, i++);
2714
2715 if (!isLittleEndian())
2716 std::swap(Lo, Hi);
2717
2718 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2719 } else {
2720 // Value scalarized into many values. Unimp for now.
2721 assert(0 && "Cannot expand i64 -> i16 yet!");
2722 }
2723 } else {
2724 // Otherwise, this is a vector type. We only support legal vectors
2725 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002726 const PackedType *PTy = cast<PackedType>(I->getType());
2727 unsigned NumElems = PTy->getNumElements();
2728 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002729
Chris Lattnerfdfded52006-04-12 16:20:43 +00002730 // Figure out if there is a Packed type corresponding to this Vector
2731 // type. If so, convert to the packed type.
2732 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002733 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002734 SDOperand N = SDOperand(Result, i++);
2735 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002736 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2737 DAG.getConstant(NumElems, MVT::i32),
2738 DAG.getValueType(getValueType(EltTy)));
2739 Ops.push_back(N);
2740 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002741 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002742 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002743 }
2744 }
2745 break;
2746 }
2747 }
2748 return Ops;
2749}
2750
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002751
2752/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2753/// implementation, which just inserts an ISD::CALL node, which is later custom
2754/// lowered by the target to something concrete. FIXME: When all targets are
2755/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2756std::pair<SDOperand, SDOperand>
2757TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2758 unsigned CallingConv, bool isTailCall,
2759 SDOperand Callee,
2760 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00002761 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002762 Ops.push_back(Chain); // Op#0 - Chain
2763 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2764 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2765 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2766 Ops.push_back(Callee);
2767
2768 // Handle all of the outgoing arguments.
2769 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2770 MVT::ValueType VT = getValueType(Args[i].second);
2771 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00002772 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002773 switch (getTypeAction(VT)) {
2774 default: assert(0 && "Unknown type action!");
2775 case Legal:
2776 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002777 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002778 break;
2779 case Promote:
2780 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00002781 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002782 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2783 } else {
2784 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2785 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2786 }
2787 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002788 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002789 break;
2790 case Expand:
2791 if (VT != MVT::Vector) {
2792 // If this is a large integer, it needs to be broken down into small
2793 // integers. Figure out what the source elt type is and how many small
2794 // integers it is.
2795 MVT::ValueType NVT = getTypeToTransformTo(VT);
2796 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2797 if (NumVals == 2) {
2798 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2799 DAG.getConstant(0, getPointerTy()));
2800 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2801 DAG.getConstant(1, getPointerTy()));
2802 if (!isLittleEndian())
2803 std::swap(Lo, Hi);
2804
2805 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00002806 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002807 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00002808 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002809 } else {
2810 // Value scalarized into many values. Unimp for now.
2811 assert(0 && "Cannot expand i64 -> i16 yet!");
2812 }
2813 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002814 // Otherwise, this is a vector type. We only support legal vectors
2815 // right now.
2816 const PackedType *PTy = cast<PackedType>(Args[i].second);
2817 unsigned NumElems = PTy->getNumElements();
2818 const Type *EltTy = PTy->getElementType();
2819
2820 // Figure out if there is a Packed type corresponding to this Vector
2821 // type. If so, convert to the packed type.
2822 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00002823 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2824 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2825 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2826 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002827 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00002828 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002829 assert(0 && "Don't support illegal by-val vector call args yet!");
2830 abort();
2831 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002832 }
2833 break;
2834 }
2835 }
2836
2837 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00002838 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002839
2840 if (RetTy != Type::VoidTy) {
2841 MVT::ValueType VT = getValueType(RetTy);
2842 switch (getTypeAction(VT)) {
2843 default: assert(0 && "Unknown type action!");
2844 case Legal:
2845 RetTys.push_back(VT);
2846 break;
2847 case Promote:
2848 RetTys.push_back(getTypeToTransformTo(VT));
2849 break;
2850 case Expand:
2851 if (VT != MVT::Vector) {
2852 // If this is a large integer, it needs to be reassembled from small
2853 // integers. Figure out what the source elt type is and how many small
2854 // integers it is.
2855 MVT::ValueType NVT = getTypeToTransformTo(VT);
2856 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2857 for (unsigned i = 0; i != NumVals; ++i)
2858 RetTys.push_back(NVT);
2859 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002860 // Otherwise, this is a vector type. We only support legal vectors
2861 // right now.
2862 const PackedType *PTy = cast<PackedType>(RetTy);
2863 unsigned NumElems = PTy->getNumElements();
2864 const Type *EltTy = PTy->getElementType();
2865
2866 // Figure out if there is a Packed type corresponding to this Vector
2867 // type. If so, convert to the packed type.
2868 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2869 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2870 RetTys.push_back(TVT);
2871 } else {
2872 assert(0 && "Don't support illegal by-val vector call results yet!");
2873 abort();
2874 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002875 }
2876 }
2877 }
2878
2879 RetTys.push_back(MVT::Other); // Always has a chain.
2880
2881 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00002882 SDOperand Res = DAG.getNode(ISD::CALL,
2883 DAG.getVTList(&RetTys[0], RetTys.size()),
2884 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002885
2886 // This returns a pair of operands. The first element is the
2887 // return value for the function (if RetTy is not VoidTy). The second
2888 // element is the outgoing token chain.
2889 SDOperand ResVal;
2890 if (RetTys.size() != 1) {
2891 MVT::ValueType VT = getValueType(RetTy);
2892 if (RetTys.size() == 2) {
2893 ResVal = Res;
2894
2895 // If this value was promoted, truncate it down.
2896 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00002897 if (VT == MVT::Vector) {
2898 // Insert a VBITCONVERT to convert from the packed result type to the
2899 // MVT::Vector type.
2900 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2901 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2902
2903 // Figure out if there is a Packed type corresponding to this Vector
2904 // type. If so, convert to the packed type.
2905 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2906 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00002907 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2908 // "N x PTyElementVT" MVT::Vector type.
2909 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00002910 DAG.getConstant(NumElems, MVT::i32),
2911 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00002912 } else {
2913 abort();
2914 }
2915 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002916 unsigned AssertOp = RetTy->isSigned() ?
2917 ISD::AssertSext : ISD::AssertZext;
2918 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2919 DAG.getValueType(VT));
2920 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2921 } else {
2922 assert(MVT::isFloatingPoint(VT));
2923 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2924 }
2925 }
2926 } else if (RetTys.size() == 3) {
2927 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2928 Res.getValue(0), Res.getValue(1));
2929
2930 } else {
2931 assert(0 && "Case not handled yet!");
2932 }
2933 }
2934
2935 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2936}
2937
2938
2939
Chris Lattner39ae3622005-01-09 00:00:49 +00002940// It is always conservatively correct for llvm.returnaddress and
2941// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002942//
2943// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2944// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00002945std::pair<SDOperand, SDOperand>
2946TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2947 unsigned Depth, SelectionDAG &DAG) {
2948 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00002949}
2950
Chris Lattner50381b62005-05-14 05:50:48 +00002951SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00002952 assert(0 && "LowerOperation not implemented for this target!");
2953 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00002954 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00002955}
2956
Nate Begeman0aed7842006-01-28 03:14:31 +00002957SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2958 SelectionDAG &DAG) {
2959 assert(0 && "CustomPromoteOperation not implemented for this target!");
2960 abort();
2961 return SDOperand();
2962}
2963
Chris Lattner39ae3622005-01-09 00:00:49 +00002964void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002965 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00002966 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00002967 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00002968 setValue(&I, Result.first);
2969 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002970}
2971
Evan Cheng74d0aa92006-02-15 21:59:04 +00002972/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00002973/// operand.
2974static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00002975 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002976 MVT::ValueType CurVT = VT;
2977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2978 uint64_t Val = C->getValue() & 255;
2979 unsigned Shift = 8;
2980 while (CurVT != MVT::i8) {
2981 Val = (Val << Shift) | Val;
2982 Shift <<= 1;
2983 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002984 }
2985 return DAG.getConstant(Val, VT);
2986 } else {
2987 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2988 unsigned Shift = 8;
2989 while (CurVT != MVT::i8) {
2990 Value =
2991 DAG.getNode(ISD::OR, VT,
2992 DAG.getNode(ISD::SHL, VT, Value,
2993 DAG.getConstant(Shift, MVT::i8)), Value);
2994 Shift <<= 1;
2995 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002996 }
2997
2998 return Value;
2999 }
3000}
3001
Evan Cheng74d0aa92006-02-15 21:59:04 +00003002/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3003/// used when a memcpy is turned into a memset when the source is a constant
3004/// string ptr.
3005static SDOperand getMemsetStringVal(MVT::ValueType VT,
3006 SelectionDAG &DAG, TargetLowering &TLI,
3007 std::string &Str, unsigned Offset) {
3008 MVT::ValueType CurVT = VT;
3009 uint64_t Val = 0;
3010 unsigned MSB = getSizeInBits(VT) / 8;
3011 if (TLI.isLittleEndian())
3012 Offset = Offset + MSB - 1;
3013 for (unsigned i = 0; i != MSB; ++i) {
3014 Val = (Val << 8) | Str[Offset];
3015 Offset += TLI.isLittleEndian() ? -1 : 1;
3016 }
3017 return DAG.getConstant(Val, VT);
3018}
3019
Evan Cheng1db92f92006-02-14 08:22:34 +00003020/// getMemBasePlusOffset - Returns base and offset node for the
3021static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3022 SelectionDAG &DAG, TargetLowering &TLI) {
3023 MVT::ValueType VT = Base.getValueType();
3024 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3025}
3026
Evan Chengc4f8eee2006-02-14 20:12:38 +00003027/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003028/// to replace the memset / memcpy is below the threshold. It also returns the
3029/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003030static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3031 unsigned Limit, uint64_t Size,
3032 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003033 MVT::ValueType VT;
3034
3035 if (TLI.allowsUnalignedMemoryAccesses()) {
3036 VT = MVT::i64;
3037 } else {
3038 switch (Align & 7) {
3039 case 0:
3040 VT = MVT::i64;
3041 break;
3042 case 4:
3043 VT = MVT::i32;
3044 break;
3045 case 2:
3046 VT = MVT::i16;
3047 break;
3048 default:
3049 VT = MVT::i8;
3050 break;
3051 }
3052 }
3053
Evan Cheng80e89d72006-02-14 09:11:59 +00003054 MVT::ValueType LVT = MVT::i64;
3055 while (!TLI.isTypeLegal(LVT))
3056 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3057 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003058
Evan Cheng80e89d72006-02-14 09:11:59 +00003059 if (VT > LVT)
3060 VT = LVT;
3061
Evan Chengdea72452006-02-14 23:05:54 +00003062 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003063 while (Size != 0) {
3064 unsigned VTSize = getSizeInBits(VT) / 8;
3065 while (VTSize > Size) {
3066 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003067 VTSize >>= 1;
3068 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003069 assert(MVT::isInteger(VT));
3070
3071 if (++NumMemOps > Limit)
3072 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003073 MemOps.push_back(VT);
3074 Size -= VTSize;
3075 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003076
3077 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003078}
3079
Chris Lattner7041ee32005-01-11 05:56:49 +00003080void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003081 SDOperand Op1 = getValue(I.getOperand(1));
3082 SDOperand Op2 = getValue(I.getOperand(2));
3083 SDOperand Op3 = getValue(I.getOperand(3));
3084 SDOperand Op4 = getValue(I.getOperand(4));
3085 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3086 if (Align == 0) Align = 1;
3087
3088 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3089 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003090
3091 // Expand memset / memcpy to a series of load / store ops
3092 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003093 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003094 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003095 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003096 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003097 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3098 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003099 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003100 unsigned Offset = 0;
3101 for (unsigned i = 0; i < NumMemOps; i++) {
3102 MVT::ValueType VT = MemOps[i];
3103 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003104 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003105 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003106 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003107 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003108 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003109 Offset += VTSize;
3110 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003111 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003112 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003113 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003114 case ISD::MEMCPY: {
3115 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3116 Size->getValue(), Align, TLI)) {
3117 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003118 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003119 GlobalAddressSDNode *G = NULL;
3120 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003121 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003122
3123 if (Op2.getOpcode() == ISD::GlobalAddress)
3124 G = cast<GlobalAddressSDNode>(Op2);
3125 else if (Op2.getOpcode() == ISD::ADD &&
3126 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3127 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3128 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003129 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003130 }
3131 if (G) {
3132 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00003133 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00003134 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003135 if (!Str.empty()) {
3136 CopyFromStr = true;
3137 SrcOff += SrcDelta;
3138 }
3139 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003140 }
3141
Evan Chengc080d6f2006-02-15 01:54:51 +00003142 for (unsigned i = 0; i < NumMemOps; i++) {
3143 MVT::ValueType VT = MemOps[i];
3144 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003145 SDOperand Value, Chain, Store;
3146
Evan Chengcffbb512006-02-16 23:11:42 +00003147 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003148 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3149 Chain = getRoot();
3150 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003151 DAG.getStore(Chain, Value,
3152 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003153 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003154 } else {
3155 Value = DAG.getLoad(VT, getRoot(),
3156 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003157 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003158 Chain = Value.getValue(1);
3159 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003160 DAG.getStore(Chain, Value,
3161 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003162 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003163 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003164 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003165 SrcOff += VTSize;
3166 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003167 }
3168 }
3169 break;
3170 }
3171 }
3172
3173 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003174 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3175 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003176 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003177 }
3178 }
3179
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003180 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003181}
3182
Chris Lattner7041ee32005-01-11 05:56:49 +00003183//===----------------------------------------------------------------------===//
3184// SelectionDAGISel code
3185//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003186
3187unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3188 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3189}
3190
Chris Lattner495a0b52005-08-17 06:37:43 +00003191void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003192 // FIXME: we only modify the CFG to split critical edges. This
3193 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003194 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003195}
Chris Lattner1c08c712005-01-07 07:47:53 +00003196
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003197
Chris Lattner90323642006-05-05 21:17:49 +00003198/// OptimizeNoopCopyExpression - We have determined that the specified cast
3199/// instruction is a noop copy (e.g. it's casting from one pointer type to
3200/// another, int->uint, or int->sbyte on PPC.
3201///
3202/// Return true if any changes are made.
3203static bool OptimizeNoopCopyExpression(CastInst *CI) {
3204 BasicBlock *DefBB = CI->getParent();
3205
3206 /// InsertedCasts - Only insert a cast in each block once.
3207 std::map<BasicBlock*, CastInst*> InsertedCasts;
3208
3209 bool MadeChange = false;
3210 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3211 UI != E; ) {
3212 Use &TheUse = UI.getUse();
3213 Instruction *User = cast<Instruction>(*UI);
3214
3215 // Figure out which BB this cast is used in. For PHI's this is the
3216 // appropriate predecessor block.
3217 BasicBlock *UserBB = User->getParent();
3218 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3219 unsigned OpVal = UI.getOperandNo()/2;
3220 UserBB = PN->getIncomingBlock(OpVal);
3221 }
3222
3223 // Preincrement use iterator so we don't invalidate it.
3224 ++UI;
3225
3226 // If this user is in the same block as the cast, don't change the cast.
3227 if (UserBB == DefBB) continue;
3228
3229 // If we have already inserted a cast into this block, use it.
3230 CastInst *&InsertedCast = InsertedCasts[UserBB];
3231
3232 if (!InsertedCast) {
3233 BasicBlock::iterator InsertPt = UserBB->begin();
3234 while (isa<PHINode>(InsertPt)) ++InsertPt;
3235
3236 InsertedCast =
3237 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3238 MadeChange = true;
3239 }
3240
3241 // Replace a use of the cast with a use of the new casat.
3242 TheUse = InsertedCast;
3243 }
3244
3245 // If we removed all uses, nuke the cast.
3246 if (CI->use_empty())
3247 CI->eraseFromParent();
3248
3249 return MadeChange;
3250}
3251
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003252/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3253/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003254static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3255 Instruction *GEPI, Value *Ptr,
3256 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003257 if (V) return V; // Already computed.
3258
3259 BasicBlock::iterator InsertPt;
3260 if (BB == GEPI->getParent()) {
3261 // If insert into the GEP's block, insert right after the GEP.
3262 InsertPt = GEPI;
3263 ++InsertPt;
3264 } else {
3265 // Otherwise, insert at the top of BB, after any PHI nodes
3266 InsertPt = BB->begin();
3267 while (isa<PHINode>(InsertPt)) ++InsertPt;
3268 }
3269
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003270 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3271 // BB so that there is only one value live across basic blocks (the cast
3272 // operand).
3273 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3274 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3275 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3276
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003277 // Add the offset, cast it to the right type.
3278 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003279 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003280}
3281
Chris Lattner90323642006-05-05 21:17:49 +00003282/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3283/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3284/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3285/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3286/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3287/// the constant add into a load or store instruction. Additionally, if a user
3288/// is a pointer-pointer cast, we look through it to find its users.
3289static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3290 Constant *PtrOffset, BasicBlock *DefBB,
3291 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003292 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003293 while (!RepPtr->use_empty()) {
3294 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003295
Chris Lattner90323642006-05-05 21:17:49 +00003296 // If the user is a Pointer-Pointer cast, recurse.
3297 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3298 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003299
Chris Lattner90323642006-05-05 21:17:49 +00003300 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3301 // could invalidate an iterator.
3302 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3303 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003304 }
3305
Chris Lattner90323642006-05-05 21:17:49 +00003306 // If this is a load of the pointer, or a store through the pointer, emit
3307 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003308 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003309 if (isa<LoadInst>(User) ||
3310 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3311 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3312 User->getParent(), GEPI,
3313 Ptr, PtrOffset);
3314 } else {
3315 // If this use is not foldable into the addressing mode, use a version
3316 // emitted in the GEP block.
3317 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3318 Ptr, PtrOffset);
3319 }
3320
Chris Lattnerf0df8822006-05-06 09:10:37 +00003321 if (GEPI->getType() != RepPtr->getType()) {
3322 BasicBlock::iterator IP = NewVal;
3323 ++IP;
3324 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3325 }
Chris Lattner90323642006-05-05 21:17:49 +00003326 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003327 }
3328}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003329
Chris Lattner90323642006-05-05 21:17:49 +00003330
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003331/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3332/// selection, we want to be a bit careful about some things. In particular, if
3333/// we have a GEP instruction that is used in a different block than it is
3334/// defined, the addressing expression of the GEP cannot be folded into loads or
3335/// stores that use it. In this case, decompose the GEP and move constant
3336/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003337static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003338 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003339 // If this GEP is only used inside the block it is defined in, there is no
3340 // need to rewrite it.
3341 bool isUsedOutsideDefBB = false;
3342 BasicBlock *DefBB = GEPI->getParent();
3343 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3344 UI != E; ++UI) {
3345 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3346 isUsedOutsideDefBB = true;
3347 break;
3348 }
3349 }
Chris Lattner90323642006-05-05 21:17:49 +00003350 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003351
3352 // If this GEP has no non-zero constant indices, there is nothing we can do,
3353 // ignore it.
3354 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003355 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003356 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3357 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003358 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003359 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003360 hasConstantIndex = true;
3361 break;
3362 }
Chris Lattner90323642006-05-05 21:17:49 +00003363 } else {
3364 hasVariableIndex = true;
3365 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003366 }
Chris Lattner90323642006-05-05 21:17:49 +00003367
3368 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3369 if (!hasConstantIndex && !hasVariableIndex) {
3370 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3371 GEPI->getName(), GEPI);
3372 GEPI->replaceAllUsesWith(NC);
3373 GEPI->eraseFromParent();
3374 return true;
3375 }
3376
Chris Lattner3802c252005-12-11 09:05:13 +00003377 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003378 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3379 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003380
3381 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3382 // constant offset (which we now know is non-zero) and deal with it later.
3383 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003384 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003385 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3386 const Type *Ty = GEPI->getOperand(0)->getType();
3387
3388 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3389 E = GEPI->op_end(); OI != E; ++OI) {
3390 Value *Idx = *OI;
3391 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003392 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003393 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003394 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003395 Ty = StTy->getElementType(Field);
3396 } else {
3397 Ty = cast<SequentialType>(Ty)->getElementType();
3398
3399 // Handle constant subscripts.
3400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003401 if (CI->getZExtValue() == 0) continue;
3402 if (CI->getType()->isSigned())
3403 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003404 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003405 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003406 continue;
3407 }
3408
3409 // Ptr = Ptr + Idx * ElementSize;
3410
3411 // Cast Idx to UIntPtrTy if needed.
3412 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3413
Owen Andersona69571c2006-05-03 01:29:57 +00003414 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003415 // Mask off bits that should not be set.
3416 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003417 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003418
3419 // Multiply by the element size and add to the base.
3420 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3421 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3422 }
3423 }
3424
3425 // Make sure that the offset fits in uintptr_t.
3426 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003427 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003428
3429 // Okay, we have now emitted all of the variable index parts to the BB that
3430 // the GEP is defined in. Loop over all of the using instructions, inserting
3431 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003432 // instruction to use the newly computed value, making GEPI dead. When the
3433 // user is a load or store instruction address, we emit the add into the user
3434 // block, otherwise we use a canonical version right next to the gep (these
3435 // won't be foldable as addresses, so we might as well share the computation).
3436
Chris Lattnerf0df8822006-05-06 09:10:37 +00003437 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003438 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003439
3440 // Finally, the GEP is dead, remove it.
3441 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003442
3443 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003444}
3445
Chris Lattner57f9a432006-09-28 06:17:10 +00003446/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3447/// constant operands, and if any of the edges feeding the PHI node are
3448/// critical, split them so that the assignments of a constant to a register
3449/// will not be executed on a path that isn't relevant.
3450void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner75548062006-10-11 03:58:02 +00003451 // The most common case is that this is a PHI node with two incoming
3452 // successors handle this case efficiently, because it is simple.
3453 PHINode *PN = cast<PHINode>(BB->begin());
3454 if (PN->getNumIncomingValues() == 2) {
3455 // If neither edge is critical, we never need to split.
3456 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3457 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3458 return;
3459
3460 BasicBlock::iterator BBI = BB->begin();
3461 while ((PN = dyn_cast<PHINode>(BBI++))) {
3462 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3463 if (isa<Constant>(PN->getIncomingValue(i)))
3464 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3465 }
3466 return;
3467 }
3468
3469 // Otherwise, things are a bit trickier.
3470
3471 // BE SMART HERE.
3472
Chris Lattner57f9a432006-09-28 06:17:10 +00003473 BasicBlock::iterator BBI = BB->begin();
3474 while ((PN = dyn_cast<PHINode>(BBI++))) {
3475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3476 if (isa<Constant>(PN->getIncomingValue(i)))
3477 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3478 }
3479}
3480
3481
Chris Lattner1c08c712005-01-07 07:47:53 +00003482bool SelectionDAGISel::runOnFunction(Function &Fn) {
3483 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3484 RegMap = MF.getSSARegMap();
3485 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3486
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003487 // First, split all critical edges for PHI nodes with incoming values that are
3488 // constants, this way the load of the constant into a vreg will not be placed
3489 // into MBBs that are used some other way.
3490 //
Chris Lattner7e598092006-05-05 01:04:50 +00003491 // In this pass we also look for GEP and cast instructions that are used
3492 // across basic blocks and rewrite them to improve basic-block-at-a-time
3493 // selection.
3494 //
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003495 //
Chris Lattner90323642006-05-05 21:17:49 +00003496 bool MadeChange = true;
3497 while (MadeChange) {
3498 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003499 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattner57f9a432006-09-28 06:17:10 +00003500 // If this block has any PHI nodes with constant operands, and if any of the
3501 // edges feeding the PHI node are critical, split them.
3502 if (isa<PHINode>(BB->begin()))
3503 SplitCritEdgesForPHIConstants(BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003504
Chris Lattner57f9a432006-09-28 06:17:10 +00003505 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003506 Instruction *I = BBI++;
3507 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003508 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003509 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003510 // If the source of the cast is a constant, then this should have
3511 // already been constant folded. The only reason NOT to constant fold
3512 // it is if something (e.g. LSR) was careful to place the constant
3513 // evaluation in a block other than then one that uses it (e.g. to hoist
3514 // the address of globals out of a loop). If this is the case, we don't
3515 // want to forward-subst the cast.
3516 if (isa<Constant>(CI->getOperand(0)))
3517 continue;
3518
Chris Lattner7e598092006-05-05 01:04:50 +00003519 // If this is a noop copy, sink it into user blocks to reduce the number
3520 // of virtual registers that must be created and coallesced.
3521 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3522 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3523
3524 // This is an fp<->int conversion?
3525 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3526 continue;
3527
3528 // If this is an extension, it will be a zero or sign extension, which
3529 // isn't a noop.
3530 if (SrcVT < DstVT) continue;
3531
3532 // If these values will be promoted, find out what they will be promoted
3533 // to. This helps us consider truncates on PPC as noop copies when they
3534 // are.
3535 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3536 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3537 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3538 DstVT = TLI.getTypeToTransformTo(DstVT);
3539
3540 // If, after promotion, these are the same types, this is a noop copy.
3541 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003542 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003543 }
3544 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003545 }
Chris Lattner90323642006-05-05 21:17:49 +00003546 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003547
Chris Lattner1c08c712005-01-07 07:47:53 +00003548 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3549
3550 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3551 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003552
Chris Lattner1c08c712005-01-07 07:47:53 +00003553 return true;
3554}
3555
Chris Lattner571e4342006-10-27 21:36:01 +00003556SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3557 unsigned Reg) {
3558 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003559 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003560 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003561 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003562
3563 // If this type is not legal, we must make sure to not create an invalid
3564 // register use.
3565 MVT::ValueType SrcVT = Op.getValueType();
3566 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003567 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003568 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003569 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003570 // Handle copies from generic vectors to registers.
3571 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3572 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3573 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003574
Chris Lattner70c2a612006-03-31 02:06:56 +00003575 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3576 // MVT::Vector type.
3577 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3578 DAG.getConstant(NE, MVT::i32),
3579 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003580
Chris Lattner70c2a612006-03-31 02:06:56 +00003581 // Loop over all of the elements of the resultant vector,
3582 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3583 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003584 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003585 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003586 for (unsigned i = 0; i != NE; ++i) {
3587 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003588 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003589 if (PTyElementVT == PTyLegalElementVT) {
3590 // Elements are legal.
3591 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3592 } else if (PTyLegalElementVT > PTyElementVT) {
3593 // Elements are promoted.
3594 if (MVT::isFloatingPoint(PTyLegalElementVT))
3595 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3596 else
3597 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3598 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3599 } else {
3600 // Elements are expanded.
3601 // The src value is expanded into multiple registers.
3602 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003603 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003604 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003605 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003606 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3607 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3608 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003609 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003610 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3611 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003612 } else if (SrcVT < DestVT) {
3613 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003614 if (MVT::isFloatingPoint(SrcVT))
3615 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3616 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003617 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003618 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003619 } else {
3620 // The src value is expanded into multiple registers.
3621 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003622 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003623 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003624 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003625 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003626 return DAG.getCopyToReg(Op, Reg+1, Hi);
3627 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003628}
3629
Chris Lattner068a81e2005-01-17 17:15:02 +00003630void SelectionDAGISel::
3631LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3632 std::vector<SDOperand> &UnorderedChains) {
3633 // If this is the entry block, emit arguments.
3634 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003635 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003636 SDOperand OldRoot = SDL.DAG.getRoot();
3637 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003638
Chris Lattnerbf209482005-10-30 19:42:35 +00003639 unsigned a = 0;
3640 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3641 AI != E; ++AI, ++a)
3642 if (!AI->use_empty()) {
3643 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003644
Chris Lattnerbf209482005-10-30 19:42:35 +00003645 // If this argument is live outside of the entry block, insert a copy from
3646 // whereever we got it to the vreg that other BB's will reference it as.
3647 if (FuncInfo.ValueMap.count(AI)) {
3648 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003649 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003650 UnorderedChains.push_back(Copy);
3651 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003652 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003653
Chris Lattnerbf209482005-10-30 19:42:35 +00003654 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003655 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003656 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003657}
3658
Chris Lattner1c08c712005-01-07 07:47:53 +00003659void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3660 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003661 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003662 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003663
3664 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003665
Chris Lattnerbf209482005-10-30 19:42:35 +00003666 // Lower any arguments needed in this block if this is the entry block.
3667 if (LLVMBB == &LLVMBB->getParent()->front())
3668 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003669
3670 BB = FuncInfo.MBBMap[LLVMBB];
3671 SDL.setCurrentBasicBlock(BB);
3672
3673 // Lower all of the non-terminator instructions.
3674 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3675 I != E; ++I)
3676 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003677
Chris Lattner1c08c712005-01-07 07:47:53 +00003678 // Ensure that all instructions which are used outside of their defining
3679 // blocks are available as virtual registers.
3680 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003681 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003682 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003683 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003684 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003685 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003686 }
3687
3688 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3689 // ensure constants are generated when needed. Remember the virtual registers
3690 // that need to be added to the Machine PHI nodes as input. We cannot just
3691 // directly add them, because expansion might result in multiple MBB's for one
3692 // BB. As such, the start of the BB might correspond to a different MBB than
3693 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003694 //
Chris Lattner1c08c712005-01-07 07:47:53 +00003695
3696 // Emit constants only once even if used by multiple PHI nodes.
3697 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003698
Chris Lattner1c08c712005-01-07 07:47:53 +00003699 // Check successor nodes PHI nodes that expect a constant to be available from
3700 // this block.
3701 TerminatorInst *TI = LLVMBB->getTerminator();
3702 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3703 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003704 if (!isa<PHINode>(SuccBB->begin())) continue;
3705
Chris Lattner1c08c712005-01-07 07:47:53 +00003706 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3707 PHINode *PN;
3708
3709 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3710 // nodes and Machine PHI nodes, but the incoming operands have not been
3711 // emitted yet.
3712 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00003713 (PN = dyn_cast<PHINode>(I)); ++I)
3714 if (!PN->use_empty()) {
3715 unsigned Reg;
3716 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3717 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3718 unsigned &RegOut = ConstantsOut[C];
3719 if (RegOut == 0) {
3720 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003721 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003722 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00003723 }
3724 Reg = RegOut;
3725 } else {
3726 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00003727 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00003728 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00003729 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3730 "Didn't codegen value into a register!??");
3731 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003732 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003733 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00003734 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003735 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003736
Chris Lattnerf44fd882005-01-07 21:34:19 +00003737 // Remember that this register needs to added to the machine PHI node as
3738 // the input for this MBB.
Chris Lattner7e021512006-03-31 02:12:18 +00003739 MVT::ValueType VT = TLI.getValueType(PN->getType());
3740 unsigned NumElements;
3741 if (VT != MVT::Vector)
3742 NumElements = TLI.getNumElements(VT);
3743 else {
3744 MVT::ValueType VT1,VT2;
3745 NumElements =
3746 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3747 VT1, VT2);
3748 }
Chris Lattnerf44fd882005-01-07 21:34:19 +00003749 for (unsigned i = 0, e = NumElements; i != e; ++i)
3750 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00003751 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003752 }
3753 ConstantsOut.clear();
3754
Chris Lattnerddb870b2005-01-13 17:59:43 +00003755 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00003756 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00003757 SDOperand Root = SDL.getRoot();
3758 if (Root.getOpcode() != ISD::EntryToken) {
3759 unsigned i = 0, e = UnorderedChains.size();
3760 for (; i != e; ++i) {
3761 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3762 if (UnorderedChains[i].Val->getOperand(0) == Root)
3763 break; // Don't add the root if we already indirectly depend on it.
3764 }
3765
3766 if (i == e)
3767 UnorderedChains.push_back(Root);
3768 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003769 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3770 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00003771 }
3772
Chris Lattner1c08c712005-01-07 07:47:53 +00003773 // Lower the terminator after the copies are emitted.
3774 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00003775
Nate Begemanf15485a2006-03-27 01:32:24 +00003776 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00003777 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00003778 SwitchCases.clear();
3779 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00003780 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00003781
Chris Lattnera651cf62005-01-17 19:43:36 +00003782 // Make sure the root of the DAG is up-to-date.
3783 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00003784}
3785
Nate Begemanf15485a2006-03-27 01:32:24 +00003786void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003787 // Get alias analysis for load/store combining.
3788 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3789
Chris Lattneraf21d552005-10-10 16:47:10 +00003790 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003791 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003792
Chris Lattner1c08c712005-01-07 07:47:53 +00003793 DEBUG(std::cerr << "Lowered selection DAG:\n");
3794 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003795
Chris Lattner1c08c712005-01-07 07:47:53 +00003796 // Second step, hack on the DAG until it only uses operations and types that
3797 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00003798 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00003799
Chris Lattner1c08c712005-01-07 07:47:53 +00003800 DEBUG(std::cerr << "Legalized selection DAG:\n");
3801 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003802
Chris Lattneraf21d552005-10-10 16:47:10 +00003803 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003804 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003805
Evan Chenga9c20912006-01-21 02:32:06 +00003806 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00003807
Chris Lattnera33ef482005-03-30 01:10:47 +00003808 // Third, instruction select all of the operations to machine code, adding the
3809 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00003810 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00003811
Chris Lattner1c08c712005-01-07 07:47:53 +00003812 DEBUG(std::cerr << "Selected machine code:\n");
3813 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003814}
Chris Lattner1c08c712005-01-07 07:47:53 +00003815
Nate Begemanf15485a2006-03-27 01:32:24 +00003816void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3817 FunctionLoweringInfo &FuncInfo) {
3818 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3819 {
3820 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3821 CurDAG = &DAG;
3822
3823 // First step, lower LLVM code to some DAG. This DAG may use operations and
3824 // types that are not supported by the target.
3825 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3826
3827 // Second step, emit the lowered DAG as machine code.
3828 CodeGenAndEmitDAG(DAG);
3829 }
3830
Chris Lattnera33ef482005-03-30 01:10:47 +00003831 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00003832 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00003833 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00003834 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3835 MachineInstr *PHI = PHINodesToUpdate[i].first;
3836 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3837 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00003838 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00003839 PHI->addMachineBasicBlockOperand(BB);
3840 }
3841 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00003842 }
Nate Begemanf15485a2006-03-27 01:32:24 +00003843
Nate Begeman9453eea2006-04-23 06:26:20 +00003844 // If the JumpTable record is filled in, then we need to emit a jump table.
3845 // Updating the PHI nodes is tricky in this case, since we need to determine
3846 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00003847 if (JT.Reg) {
3848 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3849 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3850 CurDAG = &SDAG;
3851 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00003852 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00003853 // Set the current basic block to the mbb we wish to insert the code into
3854 BB = JT.MBB;
3855 SDL.setCurrentBasicBlock(BB);
3856 // Emit the code
3857 SDL.visitJumpTable(JT);
3858 SDAG.setRoot(SDL.getRoot());
3859 CodeGenAndEmitDAG(SDAG);
3860 // Update PHI Nodes
3861 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3862 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3863 MachineBasicBlock *PHIBB = PHI->getParent();
3864 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3865 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00003866 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00003867 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00003868 PHI->addMachineBasicBlockOperand(RangeBB);
3869 }
3870 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00003871 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00003872 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00003873 }
3874 }
3875 return;
3876 }
3877
Chris Lattnerb2e806e2006-10-22 23:00:53 +00003878 // If the switch block involved a branch to one of the actual successors, we
3879 // need to update PHI nodes in that block.
3880 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3881 MachineInstr *PHI = PHINodesToUpdate[i].first;
3882 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3883 "This is not a machine PHI node that we are updating!");
3884 if (BB->isSuccessor(PHI->getParent())) {
3885 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3886 PHI->addMachineBasicBlockOperand(BB);
3887 }
3888 }
3889
Nate Begemanf15485a2006-03-27 01:32:24 +00003890 // If we generated any switch lowering information, build and codegen any
3891 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003892 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00003893 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3894 CurDAG = &SDAG;
3895 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003896
Nate Begemanf15485a2006-03-27 01:32:24 +00003897 // Set the current basic block to the mbb we wish to insert the code into
3898 BB = SwitchCases[i].ThisBB;
3899 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003900
Nate Begemanf15485a2006-03-27 01:32:24 +00003901 // Emit the code
3902 SDL.visitSwitchCase(SwitchCases[i]);
3903 SDAG.setRoot(SDL.getRoot());
3904 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003905
3906 // Handle any PHI nodes in successors of this chunk, as if we were coming
3907 // from the original BB before switch expansion. Note that PHI nodes can
3908 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3909 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00003910 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003911 for (MachineBasicBlock::iterator Phi = BB->begin();
3912 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3913 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3914 for (unsigned pn = 0; ; ++pn) {
3915 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3916 if (PHINodesToUpdate[pn].first == Phi) {
3917 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3918 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3919 break;
3920 }
3921 }
Nate Begemanf15485a2006-03-27 01:32:24 +00003922 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003923
3924 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00003925 if (BB == SwitchCases[i].FalseBB)
3926 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003927
3928 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00003929 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00003930 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00003931 }
Chris Lattner57ab6592006-10-24 17:57:59 +00003932 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00003933 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003934}
Evan Chenga9c20912006-01-21 02:32:06 +00003935
Jim Laskey13ec7022006-08-01 14:21:23 +00003936
Evan Chenga9c20912006-01-21 02:32:06 +00003937//===----------------------------------------------------------------------===//
3938/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3939/// target node in the graph.
3940void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3941 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00003942
Jim Laskeyeb577ba2006-08-02 12:30:23 +00003943 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00003944
3945 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00003946 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00003947 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00003948 }
Jim Laskey13ec7022006-08-01 14:21:23 +00003949
Jim Laskey9ff542f2006-08-01 18:29:48 +00003950 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00003951 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00003952 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00003953}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003954
Chris Lattner03fc53c2006-03-06 00:22:00 +00003955
Jim Laskey9ff542f2006-08-01 18:29:48 +00003956HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3957 return new HazardRecognizer();
3958}
3959
Chris Lattner75548062006-10-11 03:58:02 +00003960//===----------------------------------------------------------------------===//
3961// Helper functions used by the generated instruction selector.
3962//===----------------------------------------------------------------------===//
3963// Calls to these methods are generated by tblgen.
3964
3965/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3966/// the dag combiner simplified the 255, we still want to match. RHS is the
3967/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3968/// specified in the .td file (e.g. 255).
3969bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3970 int64_t DesiredMaskS) {
3971 uint64_t ActualMask = RHS->getValue();
3972 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3973
3974 // If the actual mask exactly matches, success!
3975 if (ActualMask == DesiredMask)
3976 return true;
3977
3978 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3979 if (ActualMask & ~DesiredMask)
3980 return false;
3981
3982 // Otherwise, the DAG Combiner may have proven that the value coming in is
3983 // either already zero or is not demanded. Check for known zero input bits.
3984 uint64_t NeededMask = DesiredMask & ~ActualMask;
3985 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3986 return true;
3987
3988 // TODO: check to see if missing bits are just not demanded.
3989
3990 // Otherwise, this pattern doesn't match.
3991 return false;
3992}
3993
3994/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3995/// the dag combiner simplified the 255, we still want to match. RHS is the
3996/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3997/// specified in the .td file (e.g. 255).
3998bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3999 int64_t DesiredMaskS) {
4000 uint64_t ActualMask = RHS->getValue();
4001 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4002
4003 // If the actual mask exactly matches, success!
4004 if (ActualMask == DesiredMask)
4005 return true;
4006
4007 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4008 if (ActualMask & ~DesiredMask)
4009 return false;
4010
4011 // Otherwise, the DAG Combiner may have proven that the value coming in is
4012 // either already zero or is not demanded. Check for known zero input bits.
4013 uint64_t NeededMask = DesiredMask & ~ActualMask;
4014
4015 uint64_t KnownZero, KnownOne;
4016 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4017
4018 // If all the missing bits in the or are already known to be set, match!
4019 if ((NeededMask & KnownOne) == NeededMask)
4020 return true;
4021
4022 // TODO: check to see if missing bits are just not demanded.
4023
4024 // Otherwise, this pattern doesn't match.
4025 return false;
4026}
4027
Jim Laskey9ff542f2006-08-01 18:29:48 +00004028
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004029/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4030/// by tblgen. Others should not call it.
4031void SelectionDAGISel::
4032SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4033 std::vector<SDOperand> InOps;
4034 std::swap(InOps, Ops);
4035
4036 Ops.push_back(InOps[0]); // input chain.
4037 Ops.push_back(InOps[1]); // input asm string.
4038
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004039 unsigned i = 2, e = InOps.size();
4040 if (InOps[e-1].getValueType() == MVT::Flag)
4041 --e; // Don't process a flag operand if it is here.
4042
4043 while (i != e) {
4044 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4045 if ((Flags & 7) != 4 /*MEM*/) {
4046 // Just skip over this operand, copying the operands verbatim.
4047 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4048 i += (Flags >> 3) + 1;
4049 } else {
4050 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4051 // Otherwise, this is a memory operand. Ask the target to select it.
4052 std::vector<SDOperand> SelOps;
4053 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4054 std::cerr << "Could not match memory address. Inline asm failure!\n";
4055 exit(1);
4056 }
4057
4058 // Add this to the output node.
4059 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4060 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4061 i += 2;
4062 }
4063 }
4064
4065 // Add the flag input back if present.
4066 if (e != InOps.size())
4067 Ops.push_back(InOps.back());
4068}