blob: 2f79fe568065547dc95a15995e67054cd23909c8 [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"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/SelectionDAG.h"
32#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000033#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetFrameInfo.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000040#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
43#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000044#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattnerda8abb02005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000051ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
53static cl::opt<bool>
54ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000056#else
Chris Lattner5e46a192006-04-02 03:07:27 +000057static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Chris Lattner20a49212006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Cheng4ef10862006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000076 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner03fc53c2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Cheng4ef10862006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner864635a2006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000141 };
142}
Evan Cheng4ef10862006-01-23 07:01:07 +0000143
Chris Lattner1c08c712005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000173
Chris Lattner3c384492006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner1c08c712005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000185/// PHI nodes or outside of the basic block that defines it, or used by a
186/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000187static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
188 if (isa<PHINode>(I)) return true;
189 BasicBlock *BB = I->getParent();
190 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000191 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
192 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 return true;
194 return false;
195}
196
Chris Lattnerbf209482005-10-30 19:42:35 +0000197/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000198/// entry block, return true. This includes arguments used by switches, since
199/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000200static bool isOnlyUsedInEntryBlock(Argument *A) {
201 BasicBlock *Entry = A->getParent()->begin();
202 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000203 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000204 return false; // Use not in entry block.
205 return true;
206}
207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000209 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000210 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
211
Chris Lattnerbf209482005-10-30 19:42:35 +0000212 // Create a vreg for each argument register that is not dead and is used
213 // outside of the entry block for the function.
214 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
215 AI != E; ++AI)
216 if (!isOnlyUsedInEntryBlock(AI))
217 InitializeRegForValue(AI);
218
Chris Lattner1c08c712005-01-07 07:47:53 +0000219 // Initialize the mapping of values to registers. This is only set up for
220 // instruction values that are used outside of the block that defines
221 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000222 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000223 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
224 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
225 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
226 const Type *Ty = AI->getAllocatedType();
227 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000228 unsigned Align =
229 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
230 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000231
232 // If the alignment of the value is smaller than the size of the value,
233 // and if the size of the value is particularly small (<= 8 bytes),
234 // round up to the size of the value for potentially better performance.
235 //
236 // FIXME: This could be made better with a preferred alignment hook in
237 // TargetData. It serves primarily to 8-byte align doubles for X86.
238 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000239 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000240 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000242 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000243 }
244
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000245 for (; BB != EB; ++BB)
246 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
248 if (!isa<AllocaInst>(I) ||
249 !StaticAllocaMap.count(cast<AllocaInst>(I)))
250 InitializeRegForValue(I);
251
252 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
253 // also creates the initial PHI MachineInstrs, though none of the input
254 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000255 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000256 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
257 MBBMap[BB] = MBB;
258 MF.getBasicBlockList().push_back(MBB);
259
260 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
261 // appropriate.
262 PHINode *PN;
263 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000264 (PN = dyn_cast<PHINode>(I)); ++I)
265 if (!PN->use_empty()) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000266 MVT::ValueType VT = TLI.getValueType(PN->getType());
267 unsigned NumElements;
268 if (VT != MVT::Vector)
269 NumElements = TLI.getNumElements(VT);
270 else {
271 MVT::ValueType VT1,VT2;
272 NumElements =
273 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
274 VT1, VT2);
275 }
Chris Lattnerf44fd882005-01-07 21:34:19 +0000276 unsigned PHIReg = ValueMap[PN];
277 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
278 for (unsigned i = 0; i != NumElements; ++i)
279 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
280 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000281 }
282}
283
Chris Lattner3c384492006-03-16 19:51:18 +0000284/// CreateRegForValue - Allocate the appropriate number of virtual registers of
285/// the correctly promoted or expanded types. Assign these registers
286/// consecutive vreg numbers and return the first assigned number.
287unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
288 MVT::ValueType VT = TLI.getValueType(V->getType());
289
290 // The number of multiples of registers that we need, to, e.g., split up
291 // a <2 x int64> -> 4 x i32 registers.
292 unsigned NumVectorRegs = 1;
293
294 // If this is a packed type, figure out what type it will decompose into
295 // and how many of the elements it will use.
296 if (VT == MVT::Vector) {
297 const PackedType *PTy = cast<PackedType>(V->getType());
298 unsigned NumElts = PTy->getNumElements();
299 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
300
301 // Divide the input until we get to a supported size. This will always
302 // end with a scalar if the target doesn't support vectors.
303 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
304 NumElts >>= 1;
305 NumVectorRegs <<= 1;
306 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000307 if (NumElts == 1)
308 VT = EltTy;
309 else
310 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000311 }
312
313 // The common case is that we will only create one register for this
314 // value. If we have that case, create and return the virtual register.
315 unsigned NV = TLI.getNumElements(VT);
316 if (NV == 1) {
317 // If we are promoting this value, pick the next largest supported type.
318 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
319 unsigned Reg = MakeReg(PromotedType);
320 // If this is a vector of supported or promoted types (e.g. 4 x i16),
321 // create all of the registers.
322 for (unsigned i = 1; i != NumVectorRegs; ++i)
323 MakeReg(PromotedType);
324 return Reg;
325 }
326
327 // If this value is represented with multiple target registers, make sure
328 // to create enough consecutive registers of the right (smaller) type.
329 unsigned NT = VT-1; // Find the type to use.
330 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
331 --NT;
332
333 unsigned R = MakeReg((MVT::ValueType)NT);
334 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
335 MakeReg((MVT::ValueType)NT);
336 return R;
337}
Chris Lattner1c08c712005-01-07 07:47:53 +0000338
339//===----------------------------------------------------------------------===//
340/// SelectionDAGLowering - This is the common target-independent lowering
341/// implementation that is parameterized by a TargetLowering object.
342/// Also, targets can overload any lowering method.
343///
344namespace llvm {
345class SelectionDAGLowering {
346 MachineBasicBlock *CurMBB;
347
348 std::map<const Value*, SDOperand> NodeMap;
349
Chris Lattnerd3948112005-01-17 22:19:26 +0000350 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
351 /// them up and then emit token factor nodes when possible. This allows us to
352 /// get simple disambiguation between loads without worrying about alias
353 /// analysis.
354 std::vector<SDOperand> PendingLoads;
355
Nate Begemanf15485a2006-03-27 01:32:24 +0000356 /// Case - A pair of values to record the Value for a switch case, and the
357 /// case's target basic block.
358 typedef std::pair<Constant*, MachineBasicBlock*> Case;
359 typedef std::vector<Case>::iterator CaseItr;
360 typedef std::pair<CaseItr, CaseItr> CaseRange;
361
362 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
363 /// of conditional branches.
364 struct CaseRec {
365 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
366 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
367
368 /// CaseBB - The MBB in which to emit the compare and branch
369 MachineBasicBlock *CaseBB;
370 /// LT, GE - If nonzero, we know the current case value must be less-than or
371 /// greater-than-or-equal-to these Constants.
372 Constant *LT;
373 Constant *GE;
374 /// Range - A pair of iterators representing the range of case values to be
375 /// processed at this point in the binary search tree.
376 CaseRange Range;
377 };
378
379 /// The comparison function for sorting Case values.
380 struct CaseCmp {
381 bool operator () (const Case& C1, const Case& C2) {
382 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
383 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
384
385 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
386 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
387 }
388 };
389
Chris Lattner1c08c712005-01-07 07:47:53 +0000390public:
391 // TLI - This is information that describes the available target features we
392 // need for lowering. This indicates when operations are unavailable,
393 // implemented with a libcall, etc.
394 TargetLowering &TLI;
395 SelectionDAG &DAG;
396 const TargetData &TD;
397
Nate Begemanf15485a2006-03-27 01:32:24 +0000398 /// SwitchCases - Vector of CaseBlock structures used to communicate
399 /// SwitchInst code generation information.
400 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
401
Chris Lattner1c08c712005-01-07 07:47:53 +0000402 /// FuncInfo - Information about the function as a whole.
403 ///
404 FunctionLoweringInfo &FuncInfo;
405
406 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000407 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000408 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
409 FuncInfo(funcinfo) {
410 }
411
Chris Lattnera651cf62005-01-17 19:43:36 +0000412 /// getRoot - Return the current virtual root of the Selection DAG.
413 ///
414 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000415 if (PendingLoads.empty())
416 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000417
Chris Lattnerd3948112005-01-17 22:19:26 +0000418 if (PendingLoads.size() == 1) {
419 SDOperand Root = PendingLoads[0];
420 DAG.setRoot(Root);
421 PendingLoads.clear();
422 return Root;
423 }
424
425 // Otherwise, we have to make a token factor node.
426 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
427 PendingLoads.clear();
428 DAG.setRoot(Root);
429 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000430 }
431
Chris Lattner1c08c712005-01-07 07:47:53 +0000432 void visit(Instruction &I) { visit(I.getOpcode(), I); }
433
434 void visit(unsigned Opcode, User &I) {
435 switch (Opcode) {
436 default: assert(0 && "Unknown instruction type encountered!");
437 abort();
438 // Build the switch statement using the Instruction.def file.
439#define HANDLE_INST(NUM, OPCODE, CLASS) \
440 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
441#include "llvm/Instruction.def"
442 }
443 }
444
445 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
446
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000447 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
448 SDOperand SrcValue, SDOperand Root,
449 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000450
451 SDOperand getIntPtrConstant(uint64_t Val) {
452 return DAG.getConstant(Val, TLI.getPointerTy());
453 }
454
Chris Lattner199862b2006-03-16 19:57:50 +0000455 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000456
457 const SDOperand &setValue(const Value *V, SDOperand NewN) {
458 SDOperand &N = NodeMap[V];
459 assert(N.Val == 0 && "Already set a value for this node!");
460 return N = NewN;
461 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000462
Chris Lattner864635a2006-02-22 22:37:12 +0000463 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
464 MVT::ValueType VT,
465 bool OutReg, bool InReg,
466 std::set<unsigned> &OutputRegs,
467 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000468
Chris Lattner1c08c712005-01-07 07:47:53 +0000469 // Terminator instructions.
470 void visitRet(ReturnInst &I);
471 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000472 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
Nate Begemanf15485a2006-03-27 01:32:24 +0000475 // Helper for visitSwitch
476 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
477
Chris Lattner1c08c712005-01-07 07:47:53 +0000478 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000482 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000483 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000484 void visitAdd(User &I) {
485 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000486 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000487 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000488 void visitMul(User &I) {
489 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000490 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000491 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000492 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000493 visitBinary(I,
494 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
495 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000496 }
497 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000500 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000501 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
502 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
503 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000504 void visitShl(User &I) { visitShift(I, ISD::SHL); }
505 void visitShr(User &I) {
506 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000507 }
508
509 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
510 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
511 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
512 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
513 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
514 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
515 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
516
Chris Lattner2bbd8102006-03-29 00:11:43 +0000517 void visitExtractElement(User &I);
518 void visitInsertElement(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000519
Chris Lattner1c08c712005-01-07 07:47:53 +0000520 void visitGetElementPtr(User &I);
521 void visitCast(User &I);
522 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000523
524 void visitMalloc(MallocInst &I);
525 void visitFree(FreeInst &I);
526 void visitAlloca(AllocaInst &I);
527 void visitLoad(LoadInst &I);
528 void visitStore(StoreInst &I);
529 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
530 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000531 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000532 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000533 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000534
Chris Lattner1c08c712005-01-07 07:47:53 +0000535 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000536 void visitVAArg(VAArgInst &I);
537 void visitVAEnd(CallInst &I);
538 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000539 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000540
Chris Lattner7041ee32005-01-11 05:56:49 +0000541 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000542
543 void visitUserOp1(Instruction &I) {
544 assert(0 && "UserOp1 should not exist at instruction selection time!");
545 abort();
546 }
547 void visitUserOp2(Instruction &I) {
548 assert(0 && "UserOp2 should not exist at instruction selection time!");
549 abort();
550 }
551};
552} // end namespace llvm
553
Chris Lattner199862b2006-03-16 19:57:50 +0000554SDOperand SelectionDAGLowering::getValue(const Value *V) {
555 SDOperand &N = NodeMap[V];
556 if (N.Val) return N;
557
558 const Type *VTy = V->getType();
559 MVT::ValueType VT = TLI.getValueType(VTy);
560 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
561 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
562 visit(CE->getOpcode(), *CE);
563 assert(N.Val && "visit didn't populate the ValueMap!");
564 return N;
565 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
566 return N = DAG.getGlobalAddress(GV, VT);
567 } else if (isa<ConstantPointerNull>(C)) {
568 return N = DAG.getConstant(0, TLI.getPointerTy());
569 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000570 if (!isa<PackedType>(VTy))
571 return N = DAG.getNode(ISD::UNDEF, VT);
572
Chris Lattnerb2827b02006-03-19 00:52:58 +0000573 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000574 const PackedType *PTy = cast<PackedType>(VTy);
575 unsigned NumElements = PTy->getNumElements();
576 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
577
578 std::vector<SDOperand> Ops;
579 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
580
581 // Create a VConstant node with generic Vector type.
582 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
583 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerb2827b02006-03-19 00:52:58 +0000584 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000585 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
586 return N = DAG.getConstantFP(CFP->getValue(), VT);
587 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
588 unsigned NumElements = PTy->getNumElements();
589 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000590
591 // Now that we know the number and type of the elements, push a
592 // Constant or ConstantFP node onto the ops list for each element of
593 // the packed constant.
594 std::vector<SDOperand> Ops;
595 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000596 for (unsigned i = 0; i != NumElements; ++i)
597 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000598 } else {
599 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
600 SDOperand Op;
601 if (MVT::isFloatingPoint(PVT))
602 Op = DAG.getConstantFP(0, PVT);
603 else
604 Op = DAG.getConstant(0, PVT);
605 Ops.assign(NumElements, Op);
606 }
607
Chris Lattnerb2827b02006-03-19 00:52:58 +0000608 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000609 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
610 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerb2827b02006-03-19 00:52:58 +0000611 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000612 } else {
613 // Canonicalize all constant ints to be unsigned.
614 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
615 }
616 }
617
618 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
619 std::map<const AllocaInst*, int>::iterator SI =
620 FuncInfo.StaticAllocaMap.find(AI);
621 if (SI != FuncInfo.StaticAllocaMap.end())
622 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
623 }
624
625 std::map<const Value*, unsigned>::const_iterator VMI =
626 FuncInfo.ValueMap.find(V);
627 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
628
629 unsigned InReg = VMI->second;
630
631 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000632 if (VT != MVT::Vector) {
633 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000634
Chris Lattner70c2a612006-03-31 02:06:56 +0000635 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
636 if (DestVT < VT) {
637 // Source must be expanded. This input value is actually coming from the
638 // register pair VMI->second and VMI->second+1.
639 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
640 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
641 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000642 if (MVT::isFloatingPoint(VT))
643 N = DAG.getNode(ISD::FP_ROUND, VT, N);
644 else
645 N = DAG.getNode(ISD::TRUNCATE, VT, N);
646 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000647 } else {
648 // Otherwise, if this is a vector, make it available as a generic vector
649 // here.
650 MVT::ValueType PTyElementVT, PTyLegalElementVT;
651 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(VTy),PTyElementVT,
652 PTyLegalElementVT);
653
654 // Build a VBUILD_VECTOR with the input registers.
655 std::vector<SDOperand> Ops;
656 if (PTyElementVT == PTyLegalElementVT) {
657 // If the value types are legal, just VBUILD the CopyFromReg nodes.
658 for (unsigned i = 0; i != NE; ++i)
659 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
660 PTyElementVT));
661 } else if (PTyElementVT < PTyLegalElementVT) {
662 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
663 for (unsigned i = 0; i != NE; ++i) {
664 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
665 PTyElementVT);
666 if (MVT::isFloatingPoint(PTyElementVT))
667 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
668 else
669 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
670 Ops.push_back(Op);
671 }
672 } else {
673 // If the register was expanded, use BUILD_PAIR.
674 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
675 for (unsigned i = 0; i != NE/2; ++i) {
676 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
677 PTyElementVT);
678 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
679 PTyElementVT);
680 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
681 }
682 }
683
684 Ops.push_back(DAG.getConstant(NE, MVT::i32));
685 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
686 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000687 }
688
689 return N;
690}
691
692
Chris Lattner1c08c712005-01-07 07:47:53 +0000693void SelectionDAGLowering::visitRet(ReturnInst &I) {
694 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000695 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000696 return;
697 }
Nate Begemanee625572006-01-27 21:09:22 +0000698 std::vector<SDOperand> NewValues;
699 NewValues.push_back(getRoot());
700 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
701 SDOperand RetOp = getValue(I.getOperand(i));
702
703 // If this is an integer return value, we need to promote it ourselves to
704 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
705 // than sign/zero.
706 if (MVT::isInteger(RetOp.getValueType()) &&
707 RetOp.getValueType() < MVT::i64) {
708 MVT::ValueType TmpVT;
709 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
710 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
711 else
712 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000713
Nate Begemanee625572006-01-27 21:09:22 +0000714 if (I.getOperand(i)->getType()->isSigned())
715 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
716 else
717 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
718 }
719 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 }
Nate Begemanee625572006-01-27 21:09:22 +0000721 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000722}
723
724void SelectionDAGLowering::visitBr(BranchInst &I) {
725 // Update machine-CFG edges.
726 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemanf15485a2006-03-27 01:32:24 +0000727 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000728
729 // Figure out which block is immediately after the current one.
730 MachineBasicBlock *NextBlock = 0;
731 MachineFunction::iterator BBI = CurMBB;
732 if (++BBI != CurMBB->getParent()->end())
733 NextBlock = BBI;
734
735 if (I.isUnconditional()) {
736 // If this is not a fall-through branch, emit the branch.
737 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000738 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000739 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000740 } else {
741 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemanf15485a2006-03-27 01:32:24 +0000742 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000743
744 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000745 if (Succ1MBB == NextBlock) {
746 // If the condition is false, fall through. This means we should branch
747 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000748 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000749 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000750 } else if (Succ0MBB == NextBlock) {
751 // If the condition is true, fall through. This means we should branch if
752 // the condition is false to Succ #1. Invert the condition first.
753 SDOperand True = DAG.getConstant(1, Cond.getValueType());
754 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000755 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000756 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000757 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000758 std::vector<SDOperand> Ops;
759 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000760 // If the false case is the current basic block, then this is a self
761 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
762 // adds an extra instruction in the loop. Instead, invert the
763 // condition and emit "Loop: ... br!cond Loop; br Out.
764 if (CurMBB == Succ1MBB) {
765 std::swap(Succ0MBB, Succ1MBB);
766 SDOperand True = DAG.getConstant(1, Cond.getValueType());
767 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
768 }
Nate Begeman81e80972006-03-17 01:40:33 +0000769 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
770 DAG.getBasicBlock(Succ0MBB));
771 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
772 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000773 }
774 }
775}
776
Nate Begemanf15485a2006-03-27 01:32:24 +0000777/// visitSwitchCase - Emits the necessary code to represent a single node in
778/// the binary search tree resulting from lowering a switch instruction.
779void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
780 SDOperand SwitchOp = getValue(CB.SwitchV);
781 SDOperand CaseOp = getValue(CB.CaseC);
782 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
783
784 // Set NextBlock to be the MBB immediately after the current one, if any.
785 // This is used to avoid emitting unnecessary branches to the next block.
786 MachineBasicBlock *NextBlock = 0;
787 MachineFunction::iterator BBI = CurMBB;
788 if (++BBI != CurMBB->getParent()->end())
789 NextBlock = BBI;
790
791 // If the lhs block is the next block, invert the condition so that we can
792 // fall through to the lhs instead of the rhs block.
793 if (CB.LHSBB == NextBlock) {
794 std::swap(CB.LHSBB, CB.RHSBB);
795 SDOperand True = DAG.getConstant(1, Cond.getValueType());
796 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
797 }
798 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
799 DAG.getBasicBlock(CB.LHSBB));
800 if (CB.RHSBB == NextBlock)
801 DAG.setRoot(BrCond);
802 else
803 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
804 DAG.getBasicBlock(CB.RHSBB)));
805 // Update successor info
806 CurMBB->addSuccessor(CB.LHSBB);
807 CurMBB->addSuccessor(CB.RHSBB);
808}
809
810void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
811 // Figure out which block is immediately after the current one.
812 MachineBasicBlock *NextBlock = 0;
813 MachineFunction::iterator BBI = CurMBB;
814 if (++BBI != CurMBB->getParent()->end())
815 NextBlock = BBI;
816
817 // If there is only the default destination, branch to it if it is not the
818 // next basic block. Otherwise, just fall through.
819 if (I.getNumOperands() == 2) {
820 // Update machine-CFG edges.
821 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
822 // If this is not a fall-through branch, emit the branch.
823 if (DefaultMBB != NextBlock)
824 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
825 DAG.getBasicBlock(DefaultMBB)));
826 return;
827 }
828
829 // If there are any non-default case statements, create a vector of Cases
830 // representing each one, and sort the vector so that we can efficiently
831 // create a binary search tree from them.
832 std::vector<Case> Cases;
833 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
834 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
835 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
836 }
837 std::sort(Cases.begin(), Cases.end(), CaseCmp());
838
839 // Get the Value to be switched on and default basic blocks, which will be
840 // inserted into CaseBlock records, representing basic blocks in the binary
841 // search tree.
842 Value *SV = I.getOperand(0);
843 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
844
845 // Get the current MachineFunction and LLVM basic block, for use in creating
846 // and inserting new MBBs during the creation of the binary search tree.
847 MachineFunction *CurMF = CurMBB->getParent();
848 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
849
850 // Push the initial CaseRec onto the worklist
851 std::vector<CaseRec> CaseVec;
852 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
853
854 while (!CaseVec.empty()) {
855 // Grab a record representing a case range to process off the worklist
856 CaseRec CR = CaseVec.back();
857 CaseVec.pop_back();
858
859 // Size is the number of Cases represented by this range. If Size is 1,
860 // then we are processing a leaf of the binary search tree. Otherwise,
861 // we need to pick a pivot, and push left and right ranges onto the
862 // worklist.
863 unsigned Size = CR.Range.second - CR.Range.first;
864
865 if (Size == 1) {
866 // Create a CaseBlock record representing a conditional branch to
867 // the Case's target mbb if the value being switched on SV is equal
868 // to C. Otherwise, branch to default.
869 Constant *C = CR.Range.first->first;
870 MachineBasicBlock *Target = CR.Range.first->second;
871 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
872 CR.CaseBB);
873 // If the MBB representing the leaf node is the current MBB, then just
874 // call visitSwitchCase to emit the code into the current block.
875 // Otherwise, push the CaseBlock onto the vector to be later processed
876 // by SDISel, and insert the node's MBB before the next MBB.
877 if (CR.CaseBB == CurMBB)
878 visitSwitchCase(CB);
879 else {
880 SwitchCases.push_back(CB);
881 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
882 }
883 } else {
884 // split case range at pivot
885 CaseItr Pivot = CR.Range.first + (Size / 2);
886 CaseRange LHSR(CR.Range.first, Pivot);
887 CaseRange RHSR(Pivot, CR.Range.second);
888 Constant *C = Pivot->first;
889 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
890 // We know that we branch to the LHS if the Value being switched on is
891 // less than the Pivot value, C. We use this to optimize our binary
892 // tree a bit, by recognizing that if SV is greater than or equal to the
893 // LHS's Case Value, and that Case Value is exactly one less than the
894 // Pivot's Value, then we can branch directly to the LHS's Target,
895 // rather than creating a leaf node for it.
896 if ((LHSR.second - LHSR.first) == 1 &&
897 LHSR.first->first == CR.GE &&
898 cast<ConstantIntegral>(C)->getRawValue() ==
899 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
900 LHSBB = LHSR.first->second;
901 } else {
902 LHSBB = new MachineBasicBlock(LLVMBB);
903 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
904 }
905 // Similar to the optimization above, if the Value being switched on is
906 // known to be less than the Constant CR.LT, and the current Case Value
907 // is CR.LT - 1, then we can branch directly to the target block for
908 // the current Case Value, rather than emitting a RHS leaf node for it.
909 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
910 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
911 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
912 RHSBB = RHSR.first->second;
913 } else {
914 RHSBB = new MachineBasicBlock(LLVMBB);
915 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
916 }
917 // Create a CaseBlock record representing a conditional branch to
918 // the LHS node if the value being switched on SV is less than C.
919 // Otherwise, branch to LHS.
920 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
921 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
922 if (CR.CaseBB == CurMBB)
923 visitSwitchCase(CB);
924 else {
925 SwitchCases.push_back(CB);
926 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
927 }
928 }
929 }
930}
931
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000932void SelectionDAGLowering::visitSub(User &I) {
933 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000934 if (I.getType()->isFloatingPoint()) {
935 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
936 if (CFP->isExactlyValue(-0.0)) {
937 SDOperand Op2 = getValue(I.getOperand(1));
938 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
939 return;
940 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000941 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000942 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000943}
944
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000945void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
946 unsigned VecOp) {
947 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000948 SDOperand Op1 = getValue(I.getOperand(0));
949 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000950
Chris Lattnerb67eb912005-11-19 18:40:42 +0000951 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000952 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
953 } else if (Ty->isFloatingPoint()) {
954 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
955 } else {
956 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattnerc7029802006-03-18 01:44:44 +0000957 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
958 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
959 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000960 }
Nate Begemane21ea612005-11-18 07:42:56 +0000961}
Chris Lattner2c49f272005-01-19 22:31:21 +0000962
Nate Begemane21ea612005-11-18 07:42:56 +0000963void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
964 SDOperand Op1 = getValue(I.getOperand(0));
965 SDOperand Op2 = getValue(I.getOperand(1));
966
967 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
968
Chris Lattner1c08c712005-01-07 07:47:53 +0000969 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
970}
971
972void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
973 ISD::CondCode UnsignedOpcode) {
974 SDOperand Op1 = getValue(I.getOperand(0));
975 SDOperand Op2 = getValue(I.getOperand(1));
976 ISD::CondCode Opcode = SignedOpcode;
977 if (I.getOperand(0)->getType()->isUnsigned())
978 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000979 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000980}
981
982void SelectionDAGLowering::visitSelect(User &I) {
983 SDOperand Cond = getValue(I.getOperand(0));
984 SDOperand TrueVal = getValue(I.getOperand(1));
985 SDOperand FalseVal = getValue(I.getOperand(2));
986 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
987 TrueVal, FalseVal));
988}
989
990void SelectionDAGLowering::visitCast(User &I) {
991 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +0000992 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000993 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +0000994
Chris Lattnere25ca692006-03-22 20:09:35 +0000995 if (DestVT == MVT::Vector) {
996 // This is a cast to a vector from something else. This is always a bit
997 // convert. Get information about the input vector.
998 const PackedType *DestTy = cast<PackedType>(I.getType());
999 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1000 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1001 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1002 DAG.getValueType(EltVT)));
1003 } else if (SrcVT == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001004 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001005 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +00001006 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001007 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +00001008 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001009 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001010 } else if (isInteger(SrcVT)) {
1011 if (isInteger(DestVT)) { // Int -> Int cast
1012 if (DestVT < SrcVT) // Truncating cast?
1013 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001014 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001015 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001016 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001017 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner7e358902006-03-22 22:20:49 +00001018 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001019 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001020 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001021 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001022 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001023 } else {
1024 assert(0 && "Unknown cast!");
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001025 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001026 } else if (isFloatingPoint(SrcVT)) {
1027 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1028 if (DestVT < SrcVT) // Rounding cast?
1029 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001030 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001031 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001032 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001033 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001034 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001035 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001036 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001037 } else {
1038 assert(0 && "Unknown cast!");
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001039 }
1040 } else {
Chris Lattnere25ca692006-03-22 20:09:35 +00001041 assert(SrcVT == MVT::Vector && "Unknown cast!");
1042 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1043 // This is a cast from a vector to something else. This is always a bit
1044 // convert. Get information about the input vector.
1045 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner1c08c712005-01-07 07:47:53 +00001046 }
1047}
1048
Chris Lattner2bbd8102006-03-29 00:11:43 +00001049void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001050 SDOperand InVec = getValue(I.getOperand(0));
1051 SDOperand InVal = getValue(I.getOperand(1));
1052 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1053 getValue(I.getOperand(2)));
1054
Chris Lattner2332b9f2006-03-19 01:17:20 +00001055 SDOperand Num = *(InVec.Val->op_end()-2);
1056 SDOperand Typ = *(InVec.Val->op_end()-1);
1057 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1058 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001059}
1060
Chris Lattner2bbd8102006-03-29 00:11:43 +00001061void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001062 SDOperand InVec = getValue(I.getOperand(0));
1063 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1064 getValue(I.getOperand(1)));
1065 SDOperand Typ = *(InVec.Val->op_end()-1);
1066 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1067 TLI.getValueType(I.getType()), InVec, InIdx));
1068}
Chris Lattnerc7029802006-03-18 01:44:44 +00001069
Chris Lattner1c08c712005-01-07 07:47:53 +00001070void SelectionDAGLowering::visitGetElementPtr(User &I) {
1071 SDOperand N = getValue(I.getOperand(0));
1072 const Type *Ty = I.getOperand(0)->getType();
1073 const Type *UIntPtrTy = TD.getIntPtrType();
1074
1075 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1076 OI != E; ++OI) {
1077 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001078 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001079 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1080 if (Field) {
1081 // N = N + Offset
1082 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1083 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001084 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001085 }
1086 Ty = StTy->getElementType(Field);
1087 } else {
1088 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001089
Chris Lattner7c0104b2005-11-09 04:45:33 +00001090 // If this is a constant subscript, handle it quickly.
1091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1092 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +00001093
Chris Lattner7c0104b2005-11-09 04:45:33 +00001094 uint64_t Offs;
1095 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1096 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1097 else
1098 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1099 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1100 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001101 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001102
1103 // N = N + Idx * ElementSize;
1104 uint64_t ElementSize = TD.getTypeSize(Ty);
1105 SDOperand IdxN = getValue(Idx);
1106
1107 // If the index is smaller or larger than intptr_t, truncate or extend
1108 // it.
1109 if (IdxN.getValueType() < N.getValueType()) {
1110 if (Idx->getType()->isSigned())
1111 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1112 else
1113 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1114 } else if (IdxN.getValueType() > N.getValueType())
1115 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1116
1117 // If this is a multiply by a power of two, turn it into a shl
1118 // immediately. This is a very common case.
1119 if (isPowerOf2_64(ElementSize)) {
1120 unsigned Amt = Log2_64(ElementSize);
1121 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001122 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001123 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1124 continue;
1125 }
1126
1127 SDOperand Scale = getIntPtrConstant(ElementSize);
1128 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1129 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001130 }
1131 }
1132 setValue(&I, N);
1133}
1134
1135void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1136 // If this is a fixed sized alloca in the entry block of the function,
1137 // allocate it statically on the stack.
1138 if (FuncInfo.StaticAllocaMap.count(&I))
1139 return; // getValue will auto-populate this.
1140
1141 const Type *Ty = I.getAllocatedType();
1142 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +00001143 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1144 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001145
1146 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001147 MVT::ValueType IntPtr = TLI.getPointerTy();
1148 if (IntPtr < AllocSize.getValueType())
1149 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1150 else if (IntPtr > AllocSize.getValueType())
1151 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001152
Chris Lattner68cd65e2005-01-22 23:04:37 +00001153 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001154 getIntPtrConstant(TySize));
1155
1156 // Handle alignment. If the requested alignment is less than or equal to the
1157 // stack alignment, ignore it and round the size of the allocation up to the
1158 // stack alignment size. If the size is greater than the stack alignment, we
1159 // note this in the DYNAMIC_STACKALLOC node.
1160 unsigned StackAlign =
1161 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1162 if (Align <= StackAlign) {
1163 Align = 0;
1164 // Add SA-1 to the size.
1165 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1166 getIntPtrConstant(StackAlign-1));
1167 // Mask out the low bits for alignment purposes.
1168 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1169 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1170 }
1171
Chris Lattneradf6c2a2005-05-14 07:29:57 +00001172 std::vector<MVT::ValueType> VTs;
1173 VTs.push_back(AllocSize.getValueType());
1174 VTs.push_back(MVT::Other);
1175 std::vector<SDOperand> Ops;
1176 Ops.push_back(getRoot());
1177 Ops.push_back(AllocSize);
1178 Ops.push_back(getIntPtrConstant(Align));
1179 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +00001180 DAG.setRoot(setValue(&I, DSA).getValue(1));
1181
1182 // Inform the Frame Information that we have just allocated a variable-sized
1183 // object.
1184 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1185}
1186
Chris Lattner1c08c712005-01-07 07:47:53 +00001187void SelectionDAGLowering::visitLoad(LoadInst &I) {
1188 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001189
Chris Lattnerd3948112005-01-17 22:19:26 +00001190 SDOperand Root;
1191 if (I.isVolatile())
1192 Root = getRoot();
1193 else {
1194 // Do not serialize non-volatile loads against each other.
1195 Root = DAG.getRoot();
1196 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001197
1198 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1199 Root, I.isVolatile()));
1200}
1201
1202SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1203 SDOperand SrcValue, SDOperand Root,
1204 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001205 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001206 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001207 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattnerc7029802006-03-18 01:44:44 +00001208 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001209 } else {
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001210 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001211 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001212
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001213 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001214 DAG.setRoot(L.getValue(1));
1215 else
1216 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001217
1218 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001219}
1220
1221
1222void SelectionDAGLowering::visitStore(StoreInst &I) {
1223 Value *SrcV = I.getOperand(0);
1224 SDOperand Src = getValue(SrcV);
1225 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +00001226 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +00001227 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001228}
1229
Chris Lattner0eade312006-03-24 02:22:33 +00001230/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1231/// access memory and has no other side effects at all.
1232static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1233#define GET_NO_MEMORY_INTRINSICS
1234#include "llvm/Intrinsics.gen"
1235#undef GET_NO_MEMORY_INTRINSICS
1236 return false;
1237}
1238
Chris Lattnere58a7802006-04-02 03:41:14 +00001239// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1240// have any side-effects or if it only reads memory.
1241static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1242#define GET_SIDE_EFFECT_INFO
1243#include "llvm/Intrinsics.gen"
1244#undef GET_SIDE_EFFECT_INFO
1245 return false;
1246}
1247
Chris Lattner0eade312006-03-24 02:22:33 +00001248/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1249/// node.
1250void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1251 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001252 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001253 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001254
1255 // Build the operand list.
1256 std::vector<SDOperand> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001257 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1258 if (OnlyLoad) {
1259 // We don't need to serialize loads against other loads.
1260 Ops.push_back(DAG.getRoot());
1261 } else {
1262 Ops.push_back(getRoot());
1263 }
1264 }
Chris Lattner0eade312006-03-24 02:22:33 +00001265
1266 // Add the intrinsic ID as an integer operand.
1267 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1268
1269 // Add all operands of the call to the operand list.
1270 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1271 SDOperand Op = getValue(I.getOperand(i));
1272
1273 // If this is a vector type, force it to the right packed type.
1274 if (Op.getValueType() == MVT::Vector) {
1275 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1276 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1277
1278 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1279 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1280 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1281 }
1282
1283 assert(TLI.isTypeLegal(Op.getValueType()) &&
1284 "Intrinsic uses a non-legal type?");
1285 Ops.push_back(Op);
1286 }
1287
1288 std::vector<MVT::ValueType> VTs;
1289 if (I.getType() != Type::VoidTy) {
1290 MVT::ValueType VT = TLI.getValueType(I.getType());
1291 if (VT == MVT::Vector) {
1292 const PackedType *DestTy = cast<PackedType>(I.getType());
1293 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1294
1295 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1296 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1297 }
1298
1299 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1300 VTs.push_back(VT);
1301 }
1302 if (HasChain)
1303 VTs.push_back(MVT::Other);
1304
1305 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001306 SDOperand Result;
1307 if (!HasChain)
1308 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1309 else if (I.getType() != Type::VoidTy)
1310 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1311 else
1312 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1313
Chris Lattnere58a7802006-04-02 03:41:14 +00001314 if (HasChain) {
1315 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1316 if (OnlyLoad)
1317 PendingLoads.push_back(Chain);
1318 else
1319 DAG.setRoot(Chain);
1320 }
Chris Lattner0eade312006-03-24 02:22:33 +00001321 if (I.getType() != Type::VoidTy) {
1322 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1323 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1324 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1325 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1326 DAG.getValueType(EVT));
1327 }
1328 setValue(&I, Result);
1329 }
1330}
1331
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001332/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1333/// we want to emit this as a call to a named external function, return the name
1334/// otherwise lower it and return null.
1335const char *
1336SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1337 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001338 default:
1339 // By default, turn this into a target intrinsic node.
1340 visitTargetIntrinsic(I, Intrinsic);
1341 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001342 case Intrinsic::vastart: visitVAStart(I); return 0;
1343 case Intrinsic::vaend: visitVAEnd(I); return 0;
1344 case Intrinsic::vacopy: visitVACopy(I); return 0;
1345 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1346 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1347 case Intrinsic::setjmp:
1348 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1349 break;
1350 case Intrinsic::longjmp:
1351 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1352 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001353 case Intrinsic::memcpy_i32:
1354 case Intrinsic::memcpy_i64:
1355 visitMemIntrinsic(I, ISD::MEMCPY);
1356 return 0;
1357 case Intrinsic::memset_i32:
1358 case Intrinsic::memset_i64:
1359 visitMemIntrinsic(I, ISD::MEMSET);
1360 return 0;
1361 case Intrinsic::memmove_i32:
1362 case Intrinsic::memmove_i64:
1363 visitMemIntrinsic(I, ISD::MEMMOVE);
1364 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001365
Chris Lattner86cb6432005-12-13 17:40:33 +00001366 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001367 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001368 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001369 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskeyce72b172006-02-11 01:01:30 +00001370 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +00001371
Jim Laskeyce72b172006-02-11 01:01:30 +00001372 Ops.push_back(getRoot());
Jim Laskey43970fe2006-03-23 18:06:46 +00001373 Ops.push_back(getValue(SPI.getLineValue()));
1374 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner36ce6912005-11-29 06:21:05 +00001375
Jim Laskey43970fe2006-03-23 18:06:46 +00001376 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001377 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001378 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1379
Jim Laskeyce72b172006-02-11 01:01:30 +00001380 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1381 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1382
Jim Laskey43970fe2006-03-23 18:06:46 +00001383 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +00001384 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001385
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001386 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001387 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001388 case Intrinsic::dbg_region_start: {
1389 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1390 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001391 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001392 std::vector<SDOperand> Ops;
1393
1394 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1395
1396 Ops.push_back(getRoot());
1397 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1398
1399 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1400 }
1401
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001402 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001403 }
1404 case Intrinsic::dbg_region_end: {
1405 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1406 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001407 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001408 std::vector<SDOperand> Ops;
1409
1410 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1411
1412 Ops.push_back(getRoot());
1413 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1414
1415 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1416 }
1417
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001418 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001419 }
1420 case Intrinsic::dbg_func_start: {
1421 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1422 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001423 if (DebugInfo && FSI.getSubprogram() &&
1424 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001425 std::vector<SDOperand> Ops;
1426
1427 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1428
1429 Ops.push_back(getRoot());
1430 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1431
1432 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1433 }
1434
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001435 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001436 }
1437 case Intrinsic::dbg_declare: {
1438 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1439 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00001440 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001441 std::vector<SDOperand> Ops;
1442
Jim Laskey0892cee2006-03-24 09:50:27 +00001443 SDOperand AddressOp = getValue(DI.getAddress());
1444 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001445 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1446 }
1447 }
1448
1449 return 0;
1450 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001451
Reid Spencer0b118202006-01-16 21:12:35 +00001452 case Intrinsic::isunordered_f32:
1453 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001454 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1455 getValue(I.getOperand(2)), ISD::SETUO));
1456 return 0;
1457
Reid Spencer0b118202006-01-16 21:12:35 +00001458 case Intrinsic::sqrt_f32:
1459 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001460 setValue(&I, DAG.getNode(ISD::FSQRT,
1461 getValue(I.getOperand(1)).getValueType(),
1462 getValue(I.getOperand(1))));
1463 return 0;
1464 case Intrinsic::pcmarker: {
1465 SDOperand Tmp = getValue(I.getOperand(1));
1466 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1467 return 0;
1468 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001469 case Intrinsic::readcyclecounter: {
1470 std::vector<MVT::ValueType> VTs;
1471 VTs.push_back(MVT::i64);
1472 VTs.push_back(MVT::Other);
1473 std::vector<SDOperand> Ops;
1474 Ops.push_back(getRoot());
1475 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1476 setValue(&I, Tmp);
1477 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001478 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001479 }
Nate Begemand88fc032006-01-14 03:14:10 +00001480 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001481 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001482 case Intrinsic::bswap_i64:
1483 setValue(&I, DAG.getNode(ISD::BSWAP,
1484 getValue(I.getOperand(1)).getValueType(),
1485 getValue(I.getOperand(1))));
1486 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001487 case Intrinsic::cttz_i8:
1488 case Intrinsic::cttz_i16:
1489 case Intrinsic::cttz_i32:
1490 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001491 setValue(&I, DAG.getNode(ISD::CTTZ,
1492 getValue(I.getOperand(1)).getValueType(),
1493 getValue(I.getOperand(1))));
1494 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001495 case Intrinsic::ctlz_i8:
1496 case Intrinsic::ctlz_i16:
1497 case Intrinsic::ctlz_i32:
1498 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001499 setValue(&I, DAG.getNode(ISD::CTLZ,
1500 getValue(I.getOperand(1)).getValueType(),
1501 getValue(I.getOperand(1))));
1502 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001503 case Intrinsic::ctpop_i8:
1504 case Intrinsic::ctpop_i16:
1505 case Intrinsic::ctpop_i32:
1506 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001507 setValue(&I, DAG.getNode(ISD::CTPOP,
1508 getValue(I.getOperand(1)).getValueType(),
1509 getValue(I.getOperand(1))));
1510 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001511 case Intrinsic::stacksave: {
1512 std::vector<MVT::ValueType> VTs;
1513 VTs.push_back(TLI.getPointerTy());
1514 VTs.push_back(MVT::Other);
1515 std::vector<SDOperand> Ops;
1516 Ops.push_back(getRoot());
1517 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1518 setValue(&I, Tmp);
1519 DAG.setRoot(Tmp.getValue(1));
1520 return 0;
1521 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001522 case Intrinsic::stackrestore: {
1523 SDOperand Tmp = getValue(I.getOperand(1));
1524 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001525 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001526 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001527 case Intrinsic::prefetch:
1528 // FIXME: Currently discarding prefetches.
1529 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001530 }
1531}
1532
1533
Chris Lattner1c08c712005-01-07 07:47:53 +00001534void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001535 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001536 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001537 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001538 if (unsigned IID = F->getIntrinsicID()) {
1539 RenameFn = visitIntrinsicCall(I, IID);
1540 if (!RenameFn)
1541 return;
1542 } else { // Not an LLVM intrinsic.
1543 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001544 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1545 if (I.getNumOperands() == 3 && // Basic sanity checks.
1546 I.getOperand(1)->getType()->isFloatingPoint() &&
1547 I.getType() == I.getOperand(1)->getType() &&
1548 I.getType() == I.getOperand(2)->getType()) {
1549 SDOperand LHS = getValue(I.getOperand(1));
1550 SDOperand RHS = getValue(I.getOperand(2));
1551 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1552 LHS, RHS));
1553 return;
1554 }
1555 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001556 if (I.getNumOperands() == 2 && // Basic sanity checks.
1557 I.getOperand(1)->getType()->isFloatingPoint() &&
1558 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001559 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001560 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1561 return;
1562 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001563 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001564 if (I.getNumOperands() == 2 && // Basic sanity checks.
1565 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001566 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001567 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001568 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1569 return;
1570 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001571 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001572 if (I.getNumOperands() == 2 && // Basic sanity checks.
1573 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001574 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001575 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001576 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1577 return;
1578 }
1579 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001580 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001581 } else if (isa<InlineAsm>(I.getOperand(0))) {
1582 visitInlineAsm(I);
1583 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001584 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001585
Chris Lattner64e14b12005-01-08 22:48:57 +00001586 SDOperand Callee;
1587 if (!RenameFn)
1588 Callee = getValue(I.getOperand(0));
1589 else
1590 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001591 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001592 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001593 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1594 Value *Arg = I.getOperand(i);
1595 SDOperand ArgNode = getValue(Arg);
1596 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1597 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001598
Nate Begeman8e21e712005-03-26 01:29:23 +00001599 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1600 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001601
Chris Lattnercf5734d2005-01-08 19:26:18 +00001602 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001603 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001604 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001605 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001606 setValue(&I, Result.first);
1607 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001608}
1609
Chris Lattner864635a2006-02-22 22:37:12 +00001610SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001611 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001612 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1613 Chain = Val.getValue(1);
1614 Flag = Val.getValue(2);
1615
1616 // If the result was expanded, copy from the top part.
1617 if (Regs.size() > 1) {
1618 assert(Regs.size() == 2 &&
1619 "Cannot expand to more than 2 elts yet!");
1620 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1621 Chain = Val.getValue(1);
1622 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001623 if (DAG.getTargetLoweringInfo().isLittleEndian())
1624 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1625 else
1626 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001627 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001628
Chris Lattner864635a2006-02-22 22:37:12 +00001629 // Otherwise, if the return value was promoted, truncate it to the
1630 // appropriate type.
1631 if (RegVT == ValueVT)
1632 return Val;
1633
1634 if (MVT::isInteger(RegVT))
1635 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1636 else
1637 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1638}
1639
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001640/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1641/// specified value into the registers specified by this object. This uses
1642/// Chain/Flag as the input and updates them for the output Chain/Flag.
1643void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001644 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001645 if (Regs.size() == 1) {
1646 // If there is a single register and the types differ, this must be
1647 // a promotion.
1648 if (RegVT != ValueVT) {
1649 if (MVT::isInteger(RegVT))
1650 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1651 else
1652 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1653 }
1654 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1655 Flag = Chain.getValue(1);
1656 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001657 std::vector<unsigned> R(Regs);
1658 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1659 std::reverse(R.begin(), R.end());
1660
1661 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001662 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1663 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001664 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001665 Flag = Chain.getValue(1);
1666 }
1667 }
1668}
Chris Lattner864635a2006-02-22 22:37:12 +00001669
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001670/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1671/// operand list. This adds the code marker and includes the number of
1672/// values added into it.
1673void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001674 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001675 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1676 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1677 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1678}
Chris Lattner864635a2006-02-22 22:37:12 +00001679
1680/// isAllocatableRegister - If the specified register is safe to allocate,
1681/// i.e. it isn't a stack pointer or some other special register, return the
1682/// register class for the register. Otherwise, return null.
1683static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001684isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1685 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001686 MVT::ValueType FoundVT = MVT::Other;
1687 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001688 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1689 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001690 MVT::ValueType ThisVT = MVT::Other;
1691
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001692 const TargetRegisterClass *RC = *RCI;
1693 // If none of the the value types for this register class are valid, we
1694 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001695 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1696 I != E; ++I) {
1697 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001698 // If we have already found this register in a different register class,
1699 // choose the one with the largest VT specified. For example, on
1700 // PowerPC, we favor f64 register classes over f32.
1701 if (FoundVT == MVT::Other ||
1702 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1703 ThisVT = *I;
1704 break;
1705 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001706 }
1707 }
1708
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001709 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001710
Chris Lattner864635a2006-02-22 22:37:12 +00001711 // NOTE: This isn't ideal. In particular, this might allocate the
1712 // frame pointer in functions that need it (due to them not being taken
1713 // out of allocation, because a variable sized allocation hasn't been seen
1714 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001715 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1716 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001717 if (*I == Reg) {
1718 // We found a matching register class. Keep looking at others in case
1719 // we find one with larger registers that this physreg is also in.
1720 FoundRC = RC;
1721 FoundVT = ThisVT;
1722 break;
1723 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001724 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001725 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00001726}
1727
1728RegsForValue SelectionDAGLowering::
1729GetRegistersForValue(const std::string &ConstrCode,
1730 MVT::ValueType VT, bool isOutReg, bool isInReg,
1731 std::set<unsigned> &OutputRegs,
1732 std::set<unsigned> &InputRegs) {
1733 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1734 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1735 std::vector<unsigned> Regs;
1736
1737 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1738 MVT::ValueType RegVT;
1739 MVT::ValueType ValueVT = VT;
1740
1741 if (PhysReg.first) {
1742 if (VT == MVT::Other)
1743 ValueVT = *PhysReg.second->vt_begin();
1744 RegVT = VT;
1745
1746 // This is a explicit reference to a physical register.
1747 Regs.push_back(PhysReg.first);
1748
1749 // If this is an expanded reference, add the rest of the regs to Regs.
1750 if (NumRegs != 1) {
1751 RegVT = *PhysReg.second->vt_begin();
1752 TargetRegisterClass::iterator I = PhysReg.second->begin();
1753 TargetRegisterClass::iterator E = PhysReg.second->end();
1754 for (; *I != PhysReg.first; ++I)
1755 assert(I != E && "Didn't find reg!");
1756
1757 // Already added the first reg.
1758 --NumRegs; ++I;
1759 for (; NumRegs; --NumRegs, ++I) {
1760 assert(I != E && "Ran out of registers to allocate!");
1761 Regs.push_back(*I);
1762 }
1763 }
1764 return RegsForValue(Regs, RegVT, ValueVT);
1765 }
1766
1767 // This is a reference to a register class. Allocate NumRegs consecutive,
1768 // available, registers from the class.
1769 std::vector<unsigned> RegClassRegs =
1770 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1771
1772 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1773 MachineFunction &MF = *CurMBB->getParent();
1774 unsigned NumAllocated = 0;
1775 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1776 unsigned Reg = RegClassRegs[i];
1777 // See if this register is available.
1778 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1779 (isInReg && InputRegs.count(Reg))) { // Already used.
1780 // Make sure we find consecutive registers.
1781 NumAllocated = 0;
1782 continue;
1783 }
1784
1785 // Check to see if this register is allocatable (i.e. don't give out the
1786 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001787 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001788 if (!RC) {
1789 // Make sure we find consecutive registers.
1790 NumAllocated = 0;
1791 continue;
1792 }
1793
1794 // Okay, this register is good, we can use it.
1795 ++NumAllocated;
1796
1797 // If we allocated enough consecutive
1798 if (NumAllocated == NumRegs) {
1799 unsigned RegStart = (i-NumAllocated)+1;
1800 unsigned RegEnd = i+1;
1801 // Mark all of the allocated registers used.
1802 for (unsigned i = RegStart; i != RegEnd; ++i) {
1803 unsigned Reg = RegClassRegs[i];
1804 Regs.push_back(Reg);
1805 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1806 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1807 }
1808
1809 return RegsForValue(Regs, *RC->vt_begin(), VT);
1810 }
1811 }
1812
1813 // Otherwise, we couldn't allocate enough registers for this.
1814 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001815}
1816
Chris Lattner864635a2006-02-22 22:37:12 +00001817
Chris Lattnerce7518c2006-01-26 22:24:51 +00001818/// visitInlineAsm - Handle a call to an InlineAsm object.
1819///
1820void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1821 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1822
1823 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1824 MVT::Other);
1825
1826 // Note, we treat inline asms both with and without side-effects as the same.
1827 // If an inline asm doesn't have side effects and doesn't access memory, we
1828 // could not choose to not chain it.
1829 bool hasSideEffects = IA->hasSideEffects();
1830
Chris Lattner2cc2f662006-02-01 01:28:23 +00001831 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001832 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001833
1834 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1835 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1836 /// if it is a def of that register.
1837 std::vector<SDOperand> AsmNodeOperands;
1838 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1839 AsmNodeOperands.push_back(AsmStr);
1840
1841 SDOperand Chain = getRoot();
1842 SDOperand Flag;
1843
Chris Lattner4e4b5762006-02-01 18:59:47 +00001844 // We fully assign registers here at isel time. This is not optimal, but
1845 // should work. For register classes that correspond to LLVM classes, we
1846 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1847 // over the constraints, collecting fixed registers that we know we can't use.
1848 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001849 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001850 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1851 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1852 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001853
Chris Lattner1efa40f2006-02-22 00:56:39 +00001854 MVT::ValueType OpVT;
1855
1856 // Compute the value type for each operand and add it to ConstraintVTs.
1857 switch (Constraints[i].Type) {
1858 case InlineAsm::isOutput:
1859 if (!Constraints[i].isIndirectOutput) {
1860 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1861 OpVT = TLI.getValueType(I.getType());
1862 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001863 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001864 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1865 OpNum++; // Consumes a call operand.
1866 }
1867 break;
1868 case InlineAsm::isInput:
1869 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1870 OpNum++; // Consumes a call operand.
1871 break;
1872 case InlineAsm::isClobber:
1873 OpVT = MVT::Other;
1874 break;
1875 }
1876
1877 ConstraintVTs.push_back(OpVT);
1878
Chris Lattner864635a2006-02-22 22:37:12 +00001879 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1880 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001881
Chris Lattner864635a2006-02-22 22:37:12 +00001882 // Build a list of regs that this operand uses. This always has a single
1883 // element for promoted/expanded operands.
1884 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1885 false, false,
1886 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001887
1888 switch (Constraints[i].Type) {
1889 case InlineAsm::isOutput:
1890 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001891 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001892 // If this is an early-clobber output, it cannot be assigned to the same
1893 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001894 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001895 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001896 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001897 case InlineAsm::isInput:
1898 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001899 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001900 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001901 case InlineAsm::isClobber:
1902 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001903 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1904 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001905 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001906 }
1907 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001908
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001909 // Loop over all of the inputs, copying the operand values into the
1910 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001911 RegsForValue RetValRegs;
1912 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001913 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001914
Chris Lattner6656dd12006-01-31 02:03:41 +00001915 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001916 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1917 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001918
Chris Lattner2cc2f662006-02-01 01:28:23 +00001919 switch (Constraints[i].Type) {
1920 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001921 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1922 if (ConstraintCode.size() == 1) // not a physreg name.
1923 CTy = TLI.getConstraintType(ConstraintCode[0]);
1924
1925 if (CTy == TargetLowering::C_Memory) {
1926 // Memory output.
1927 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1928
1929 // Check that the operand (the address to store to) isn't a float.
1930 if (!MVT::isInteger(InOperandVal.getValueType()))
1931 assert(0 && "MATCH FAIL!");
1932
1933 if (!Constraints[i].isIndirectOutput)
1934 assert(0 && "MATCH FAIL!");
1935
1936 OpNum++; // Consumes a call operand.
1937
1938 // Extend/truncate to the right pointer type if needed.
1939 MVT::ValueType PtrType = TLI.getPointerTy();
1940 if (InOperandVal.getValueType() < PtrType)
1941 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1942 else if (InOperandVal.getValueType() > PtrType)
1943 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1944
1945 // Add information to the INLINEASM node to know about this output.
1946 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1947 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1948 AsmNodeOperands.push_back(InOperandVal);
1949 break;
1950 }
1951
1952 // Otherwise, this is a register output.
1953 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1954
Chris Lattner864635a2006-02-22 22:37:12 +00001955 // If this is an early-clobber output, or if there is an input
1956 // constraint that matches this, we need to reserve the input register
1957 // so no other inputs allocate to it.
1958 bool UsesInputRegister = false;
1959 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1960 UsesInputRegister = true;
1961
1962 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001963 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001964 RegsForValue Regs =
1965 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1966 true, UsesInputRegister,
1967 OutputRegs, InputRegs);
1968 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001969
Chris Lattner2cc2f662006-02-01 01:28:23 +00001970 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001971 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001972 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001973 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001974 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001975 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001976 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1977 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001978 OpNum++; // Consumes a call operand.
1979 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001980
1981 // Add information to the INLINEASM node to know that this register is
1982 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001983 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001984 break;
1985 }
1986 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001987 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001988 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001989
Chris Lattner2223aea2006-02-02 00:25:23 +00001990 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1991 // If this is required to match an output register we have already set,
1992 // just use its register.
1993 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001994
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001995 // Scan until we find the definition we already emitted of this operand.
1996 // When we find it, create a RegsForValue operand.
1997 unsigned CurOp = 2; // The first operand.
1998 for (; OperandNo; --OperandNo) {
1999 // Advance to the next operand.
2000 unsigned NumOps =
2001 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2002 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2003 "Skipped past definitions?");
2004 CurOp += (NumOps>>3)+1;
2005 }
2006
2007 unsigned NumOps =
2008 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2009 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2010 "Skipped past definitions?");
2011
2012 // Add NumOps>>3 registers to MatchedRegs.
2013 RegsForValue MatchedRegs;
2014 MatchedRegs.ValueVT = InOperandVal.getValueType();
2015 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2016 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2017 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2018 MatchedRegs.Regs.push_back(Reg);
2019 }
2020
2021 // Use the produced MatchedRegs object to
2022 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2023 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002024 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002025 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002026
2027 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2028 if (ConstraintCode.size() == 1) // not a physreg name.
2029 CTy = TLI.getConstraintType(ConstraintCode[0]);
2030
2031 if (CTy == TargetLowering::C_Other) {
2032 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2033 assert(0 && "MATCH FAIL!");
2034
2035 // Add information to the INLINEASM node to know about this input.
2036 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2037 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2038 AsmNodeOperands.push_back(InOperandVal);
2039 break;
2040 } else if (CTy == TargetLowering::C_Memory) {
2041 // Memory input.
2042
2043 // Check that the operand isn't a float.
2044 if (!MVT::isInteger(InOperandVal.getValueType()))
2045 assert(0 && "MATCH FAIL!");
2046
2047 // Extend/truncate to the right pointer type if needed.
2048 MVT::ValueType PtrType = TLI.getPointerTy();
2049 if (InOperandVal.getValueType() < PtrType)
2050 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2051 else if (InOperandVal.getValueType() > PtrType)
2052 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2053
2054 // Add information to the INLINEASM node to know about this input.
2055 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2056 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2057 AsmNodeOperands.push_back(InOperandVal);
2058 break;
2059 }
2060
2061 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2062
2063 // Copy the input into the appropriate registers.
2064 RegsForValue InRegs =
2065 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2066 false, true, OutputRegs, InputRegs);
2067 // FIXME: should be match fail.
2068 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2069
2070 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2071
2072 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002073 break;
2074 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002075 case InlineAsm::isClobber: {
2076 RegsForValue ClobberedRegs =
2077 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2078 OutputRegs, InputRegs);
2079 // Add the clobbered value to the operand list, so that the register
2080 // allocator is aware that the physreg got clobbered.
2081 if (!ClobberedRegs.Regs.empty())
2082 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002083 break;
2084 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002085 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002086 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002087
2088 // Finish up input operands.
2089 AsmNodeOperands[0] = Chain;
2090 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2091
2092 std::vector<MVT::ValueType> VTs;
2093 VTs.push_back(MVT::Other);
2094 VTs.push_back(MVT::Flag);
2095 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2096 Flag = Chain.getValue(1);
2097
Chris Lattner6656dd12006-01-31 02:03:41 +00002098 // If this asm returns a register value, copy the result from that register
2099 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002100 if (!RetValRegs.Regs.empty())
2101 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002102
Chris Lattner6656dd12006-01-31 02:03:41 +00002103 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2104
2105 // Process indirect outputs, first output all of the flagged copies out of
2106 // physregs.
2107 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002108 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002109 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002110 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2111 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002112 }
2113
2114 // Emit the non-flagged stores from the physregs.
2115 std::vector<SDOperand> OutChains;
2116 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2117 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2118 StoresToEmit[i].first,
2119 getValue(StoresToEmit[i].second),
2120 DAG.getSrcValue(StoresToEmit[i].second)));
2121 if (!OutChains.empty())
2122 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00002123 DAG.setRoot(Chain);
2124}
2125
2126
Chris Lattner1c08c712005-01-07 07:47:53 +00002127void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2128 SDOperand Src = getValue(I.getOperand(0));
2129
2130 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002131
2132 if (IntPtr < Src.getValueType())
2133 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2134 else if (IntPtr > Src.getValueType())
2135 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002136
2137 // Scale the source by the type size.
2138 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2139 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2140 Src, getIntPtrConstant(ElementSize));
2141
2142 std::vector<std::pair<SDOperand, const Type*> > Args;
2143 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002144
2145 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002146 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002147 DAG.getExternalSymbol("malloc", IntPtr),
2148 Args, DAG);
2149 setValue(&I, Result.first); // Pointers always fit in registers
2150 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002151}
2152
2153void SelectionDAGLowering::visitFree(FreeInst &I) {
2154 std::vector<std::pair<SDOperand, const Type*> > Args;
2155 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2156 TLI.getTargetData().getIntPtrType()));
2157 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002158 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002159 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002160 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2161 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002162}
2163
Chris Lattner025c39b2005-08-26 20:54:47 +00002164// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2165// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2166// instructions are special in various ways, which require special support to
2167// insert. The specified MachineInstr is created but not inserted into any
2168// basic blocks, and the scheduler passes ownership of it to this method.
2169MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2170 MachineBasicBlock *MBB) {
2171 std::cerr << "If a target marks an instruction with "
2172 "'usesCustomDAGSchedInserter', it must implement "
2173 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2174 abort();
2175 return 0;
2176}
2177
Chris Lattner39ae3622005-01-09 00:00:49 +00002178void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002179 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2180 getValue(I.getOperand(1)),
2181 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002182}
2183
2184void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002185 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2186 getValue(I.getOperand(0)),
2187 DAG.getSrcValue(I.getOperand(0)));
2188 setValue(&I, V);
2189 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002190}
2191
2192void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002193 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2194 getValue(I.getOperand(1)),
2195 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002196}
2197
2198void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002199 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2200 getValue(I.getOperand(1)),
2201 getValue(I.getOperand(2)),
2202 DAG.getSrcValue(I.getOperand(1)),
2203 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002204}
2205
Chris Lattner39ae3622005-01-09 00:00:49 +00002206// It is always conservatively correct for llvm.returnaddress and
2207// llvm.frameaddress to return 0.
2208std::pair<SDOperand, SDOperand>
2209TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2210 unsigned Depth, SelectionDAG &DAG) {
2211 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00002212}
2213
Chris Lattner50381b62005-05-14 05:50:48 +00002214SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00002215 assert(0 && "LowerOperation not implemented for this target!");
2216 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00002217 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00002218}
2219
Nate Begeman0aed7842006-01-28 03:14:31 +00002220SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2221 SelectionDAG &DAG) {
2222 assert(0 && "CustomPromoteOperation not implemented for this target!");
2223 abort();
2224 return SDOperand();
2225}
2226
Chris Lattner39ae3622005-01-09 00:00:49 +00002227void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2228 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2229 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00002230 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00002231 setValue(&I, Result.first);
2232 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002233}
2234
Evan Cheng74d0aa92006-02-15 21:59:04 +00002235/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00002236/// operand.
2237static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00002238 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002239 MVT::ValueType CurVT = VT;
2240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2241 uint64_t Val = C->getValue() & 255;
2242 unsigned Shift = 8;
2243 while (CurVT != MVT::i8) {
2244 Val = (Val << Shift) | Val;
2245 Shift <<= 1;
2246 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002247 }
2248 return DAG.getConstant(Val, VT);
2249 } else {
2250 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2251 unsigned Shift = 8;
2252 while (CurVT != MVT::i8) {
2253 Value =
2254 DAG.getNode(ISD::OR, VT,
2255 DAG.getNode(ISD::SHL, VT, Value,
2256 DAG.getConstant(Shift, MVT::i8)), Value);
2257 Shift <<= 1;
2258 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002259 }
2260
2261 return Value;
2262 }
2263}
2264
Evan Cheng74d0aa92006-02-15 21:59:04 +00002265/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2266/// used when a memcpy is turned into a memset when the source is a constant
2267/// string ptr.
2268static SDOperand getMemsetStringVal(MVT::ValueType VT,
2269 SelectionDAG &DAG, TargetLowering &TLI,
2270 std::string &Str, unsigned Offset) {
2271 MVT::ValueType CurVT = VT;
2272 uint64_t Val = 0;
2273 unsigned MSB = getSizeInBits(VT) / 8;
2274 if (TLI.isLittleEndian())
2275 Offset = Offset + MSB - 1;
2276 for (unsigned i = 0; i != MSB; ++i) {
2277 Val = (Val << 8) | Str[Offset];
2278 Offset += TLI.isLittleEndian() ? -1 : 1;
2279 }
2280 return DAG.getConstant(Val, VT);
2281}
2282
Evan Cheng1db92f92006-02-14 08:22:34 +00002283/// getMemBasePlusOffset - Returns base and offset node for the
2284static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2285 SelectionDAG &DAG, TargetLowering &TLI) {
2286 MVT::ValueType VT = Base.getValueType();
2287 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2288}
2289
Evan Chengc4f8eee2006-02-14 20:12:38 +00002290/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00002291/// to replace the memset / memcpy is below the threshold. It also returns the
2292/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00002293static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2294 unsigned Limit, uint64_t Size,
2295 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002296 MVT::ValueType VT;
2297
2298 if (TLI.allowsUnalignedMemoryAccesses()) {
2299 VT = MVT::i64;
2300 } else {
2301 switch (Align & 7) {
2302 case 0:
2303 VT = MVT::i64;
2304 break;
2305 case 4:
2306 VT = MVT::i32;
2307 break;
2308 case 2:
2309 VT = MVT::i16;
2310 break;
2311 default:
2312 VT = MVT::i8;
2313 break;
2314 }
2315 }
2316
Evan Cheng80e89d72006-02-14 09:11:59 +00002317 MVT::ValueType LVT = MVT::i64;
2318 while (!TLI.isTypeLegal(LVT))
2319 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2320 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00002321
Evan Cheng80e89d72006-02-14 09:11:59 +00002322 if (VT > LVT)
2323 VT = LVT;
2324
Evan Chengdea72452006-02-14 23:05:54 +00002325 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00002326 while (Size != 0) {
2327 unsigned VTSize = getSizeInBits(VT) / 8;
2328 while (VTSize > Size) {
2329 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002330 VTSize >>= 1;
2331 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002332 assert(MVT::isInteger(VT));
2333
2334 if (++NumMemOps > Limit)
2335 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00002336 MemOps.push_back(VT);
2337 Size -= VTSize;
2338 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002339
2340 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00002341}
2342
Chris Lattner7041ee32005-01-11 05:56:49 +00002343void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002344 SDOperand Op1 = getValue(I.getOperand(1));
2345 SDOperand Op2 = getValue(I.getOperand(2));
2346 SDOperand Op3 = getValue(I.getOperand(3));
2347 SDOperand Op4 = getValue(I.getOperand(4));
2348 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2349 if (Align == 0) Align = 1;
2350
2351 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2352 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00002353
2354 // Expand memset / memcpy to a series of load / store ops
2355 // if the size operand falls below a certain threshold.
2356 std::vector<SDOperand> OutChains;
2357 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00002358 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00002359 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00002360 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2361 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00002362 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00002363 unsigned Offset = 0;
2364 for (unsigned i = 0; i < NumMemOps; i++) {
2365 MVT::ValueType VT = MemOps[i];
2366 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00002367 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00002368 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2369 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00002370 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2371 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00002372 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00002373 Offset += VTSize;
2374 }
Evan Cheng1db92f92006-02-14 08:22:34 +00002375 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002376 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00002377 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002378 case ISD::MEMCPY: {
2379 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2380 Size->getValue(), Align, TLI)) {
2381 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00002382 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002383 GlobalAddressSDNode *G = NULL;
2384 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00002385 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002386
2387 if (Op2.getOpcode() == ISD::GlobalAddress)
2388 G = cast<GlobalAddressSDNode>(Op2);
2389 else if (Op2.getOpcode() == ISD::ADD &&
2390 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2391 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2392 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00002393 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00002394 }
2395 if (G) {
2396 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00002397 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00002398 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00002399 if (!Str.empty()) {
2400 CopyFromStr = true;
2401 SrcOff += SrcDelta;
2402 }
2403 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00002404 }
2405
Evan Chengc080d6f2006-02-15 01:54:51 +00002406 for (unsigned i = 0; i < NumMemOps; i++) {
2407 MVT::ValueType VT = MemOps[i];
2408 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002409 SDOperand Value, Chain, Store;
2410
Evan Chengcffbb512006-02-16 23:11:42 +00002411 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00002412 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2413 Chain = getRoot();
2414 Store =
2415 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2416 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2417 DAG.getSrcValue(I.getOperand(1), DstOff));
2418 } else {
2419 Value = DAG.getLoad(VT, getRoot(),
2420 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2421 DAG.getSrcValue(I.getOperand(2), SrcOff));
2422 Chain = Value.getValue(1);
2423 Store =
2424 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2425 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2426 DAG.getSrcValue(I.getOperand(1), DstOff));
2427 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002428 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002429 SrcOff += VTSize;
2430 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00002431 }
2432 }
2433 break;
2434 }
2435 }
2436
2437 if (!OutChains.empty()) {
2438 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2439 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00002440 }
2441 }
2442
Chris Lattner7041ee32005-01-11 05:56:49 +00002443 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00002444 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00002445 Ops.push_back(Op1);
2446 Ops.push_back(Op2);
2447 Ops.push_back(Op3);
2448 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00002449 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00002450}
2451
Chris Lattner7041ee32005-01-11 05:56:49 +00002452//===----------------------------------------------------------------------===//
2453// SelectionDAGISel code
2454//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002455
2456unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2457 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2458}
2459
Chris Lattner495a0b52005-08-17 06:37:43 +00002460void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002461 // FIXME: we only modify the CFG to split critical edges. This
2462 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002463}
Chris Lattner1c08c712005-01-07 07:47:53 +00002464
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002465
2466/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2467/// casting to the type of GEPI.
2468static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2469 Value *Ptr, Value *PtrOffset) {
2470 if (V) return V; // Already computed.
2471
2472 BasicBlock::iterator InsertPt;
2473 if (BB == GEPI->getParent()) {
2474 // If insert into the GEP's block, insert right after the GEP.
2475 InsertPt = GEPI;
2476 ++InsertPt;
2477 } else {
2478 // Otherwise, insert at the top of BB, after any PHI nodes
2479 InsertPt = BB->begin();
2480 while (isa<PHINode>(InsertPt)) ++InsertPt;
2481 }
2482
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002483 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2484 // BB so that there is only one value live across basic blocks (the cast
2485 // operand).
2486 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2487 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2488 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2489
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002490 // Add the offset, cast it to the right type.
2491 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2492 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2493 return V = Ptr;
2494}
2495
2496
2497/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2498/// selection, we want to be a bit careful about some things. In particular, if
2499/// we have a GEP instruction that is used in a different block than it is
2500/// defined, the addressing expression of the GEP cannot be folded into loads or
2501/// stores that use it. In this case, decompose the GEP and move constant
2502/// indices into blocks that use it.
2503static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2504 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002505 // If this GEP is only used inside the block it is defined in, there is no
2506 // need to rewrite it.
2507 bool isUsedOutsideDefBB = false;
2508 BasicBlock *DefBB = GEPI->getParent();
2509 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2510 UI != E; ++UI) {
2511 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2512 isUsedOutsideDefBB = true;
2513 break;
2514 }
2515 }
2516 if (!isUsedOutsideDefBB) return;
2517
2518 // If this GEP has no non-zero constant indices, there is nothing we can do,
2519 // ignore it.
2520 bool hasConstantIndex = false;
2521 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2522 E = GEPI->op_end(); OI != E; ++OI) {
2523 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2524 if (CI->getRawValue()) {
2525 hasConstantIndex = true;
2526 break;
2527 }
2528 }
Chris Lattner3802c252005-12-11 09:05:13 +00002529 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2530 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002531
2532 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2533 // constant offset (which we now know is non-zero) and deal with it later.
2534 uint64_t ConstantOffset = 0;
2535 const Type *UIntPtrTy = TD.getIntPtrType();
2536 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2537 const Type *Ty = GEPI->getOperand(0)->getType();
2538
2539 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2540 E = GEPI->op_end(); OI != E; ++OI) {
2541 Value *Idx = *OI;
2542 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2543 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2544 if (Field)
2545 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2546 Ty = StTy->getElementType(Field);
2547 } else {
2548 Ty = cast<SequentialType>(Ty)->getElementType();
2549
2550 // Handle constant subscripts.
2551 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2552 if (CI->getRawValue() == 0) continue;
2553
2554 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2555 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2556 else
2557 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2558 continue;
2559 }
2560
2561 // Ptr = Ptr + Idx * ElementSize;
2562
2563 // Cast Idx to UIntPtrTy if needed.
2564 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2565
2566 uint64_t ElementSize = TD.getTypeSize(Ty);
2567 // Mask off bits that should not be set.
2568 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2569 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2570
2571 // Multiply by the element size and add to the base.
2572 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2573 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2574 }
2575 }
2576
2577 // Make sure that the offset fits in uintptr_t.
2578 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2579 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2580
2581 // Okay, we have now emitted all of the variable index parts to the BB that
2582 // the GEP is defined in. Loop over all of the using instructions, inserting
2583 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002584 // instruction to use the newly computed value, making GEPI dead. When the
2585 // user is a load or store instruction address, we emit the add into the user
2586 // block, otherwise we use a canonical version right next to the gep (these
2587 // won't be foldable as addresses, so we might as well share the computation).
2588
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002589 std::map<BasicBlock*,Value*> InsertedExprs;
2590 while (!GEPI->use_empty()) {
2591 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002592
2593 // If this use is not foldable into the addressing mode, use a version
2594 // emitted in the GEP block.
2595 Value *NewVal;
2596 if (!isa<LoadInst>(User) &&
2597 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2598 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2599 Ptr, PtrOffset);
2600 } else {
2601 // Otherwise, insert the code in the User's block so it can be folded into
2602 // any users in that block.
2603 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002604 User->getParent(), GEPI,
2605 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002606 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002607 User->replaceUsesOfWith(GEPI, NewVal);
2608 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002609
2610 // Finally, the GEP is dead, remove it.
2611 GEPI->eraseFromParent();
2612}
2613
Chris Lattner1c08c712005-01-07 07:47:53 +00002614bool SelectionDAGISel::runOnFunction(Function &Fn) {
2615 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2616 RegMap = MF.getSSARegMap();
2617 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2618
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002619 // First, split all critical edges for PHI nodes with incoming values that are
2620 // constants, this way the load of the constant into a vreg will not be placed
2621 // into MBBs that are used some other way.
2622 //
2623 // In this pass we also look for GEP instructions that are used across basic
2624 // blocks and rewrites them to improve basic-block-at-a-time selection.
2625 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002626 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2627 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002628 BasicBlock::iterator BBI;
2629 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002630 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2631 if (isa<Constant>(PN->getIncomingValue(i)))
2632 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002633
2634 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2635 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2636 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002637 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002638
Chris Lattner1c08c712005-01-07 07:47:53 +00002639 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2640
2641 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2642 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002643
Chris Lattner1c08c712005-01-07 07:47:53 +00002644 return true;
2645}
2646
2647
Chris Lattnerddb870b2005-01-13 17:59:43 +00002648SDOperand SelectionDAGISel::
2649CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002650 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002651 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002652 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002653 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002654
2655 // If this type is not legal, we must make sure to not create an invalid
2656 // register use.
2657 MVT::ValueType SrcVT = Op.getValueType();
2658 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2659 SelectionDAG &DAG = SDL.DAG;
2660 if (SrcVT == DestVT) {
2661 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00002662 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00002663 // Handle copies from generic vectors to registers.
2664 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2665 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2666 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00002667
Chris Lattner70c2a612006-03-31 02:06:56 +00002668 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2669 // MVT::Vector type.
2670 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2671 DAG.getConstant(NE, MVT::i32),
2672 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00002673
Chris Lattner70c2a612006-03-31 02:06:56 +00002674 // Loop over all of the elements of the resultant vector,
2675 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2676 // copying them into output registers.
2677 std::vector<SDOperand> OutChains;
2678 SDOperand Root = SDL.getRoot();
2679 for (unsigned i = 0; i != NE; ++i) {
2680 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2681 Op, DAG.getConstant(i, MVT::i32));
2682 if (PTyElementVT == PTyLegalElementVT) {
2683 // Elements are legal.
2684 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2685 } else if (PTyLegalElementVT > PTyElementVT) {
2686 // Elements are promoted.
2687 if (MVT::isFloatingPoint(PTyLegalElementVT))
2688 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2689 else
2690 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2691 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2692 } else {
2693 // Elements are expanded.
2694 // The src value is expanded into multiple registers.
2695 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2696 Elt, DAG.getConstant(0, MVT::i32));
2697 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2698 Elt, DAG.getConstant(1, MVT::i32));
2699 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2700 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2701 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00002702 }
Chris Lattner70c2a612006-03-31 02:06:56 +00002703 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002704 } else if (SrcVT < DestVT) {
2705 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002706 if (MVT::isFloatingPoint(SrcVT))
2707 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2708 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002709 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002710 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2711 } else {
2712 // The src value is expanded into multiple registers.
2713 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2714 Op, DAG.getConstant(0, MVT::i32));
2715 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2716 Op, DAG.getConstant(1, MVT::i32));
2717 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2718 return DAG.getCopyToReg(Op, Reg+1, Hi);
2719 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002720}
2721
Chris Lattner068a81e2005-01-17 17:15:02 +00002722void SelectionDAGISel::
2723LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2724 std::vector<SDOperand> &UnorderedChains) {
2725 // If this is the entry block, emit arguments.
2726 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002727 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002728 SDOperand OldRoot = SDL.DAG.getRoot();
2729 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002730
Chris Lattnerbf209482005-10-30 19:42:35 +00002731 unsigned a = 0;
2732 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2733 AI != E; ++AI, ++a)
2734 if (!AI->use_empty()) {
2735 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002736
Chris Lattnerbf209482005-10-30 19:42:35 +00002737 // If this argument is live outside of the entry block, insert a copy from
2738 // whereever we got it to the vreg that other BB's will reference it as.
2739 if (FuncInfo.ValueMap.count(AI)) {
2740 SDOperand Copy =
2741 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2742 UnorderedChains.push_back(Copy);
2743 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002744 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002745
2746 // Next, if the function has live ins that need to be copied into vregs,
2747 // emit the copies now, into the top of the block.
2748 MachineFunction &MF = SDL.DAG.getMachineFunction();
2749 if (MF.livein_begin() != MF.livein_end()) {
2750 SSARegMap *RegMap = MF.getSSARegMap();
2751 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2752 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2753 E = MF.livein_end(); LI != E; ++LI)
2754 if (LI->second)
2755 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2756 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002757 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002758
2759 // Finally, if the target has anything special to do, allow it to do so.
2760 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002761}
2762
2763
Chris Lattner1c08c712005-01-07 07:47:53 +00002764void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2765 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00002766 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002767 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002768
2769 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002770
Chris Lattnerbf209482005-10-30 19:42:35 +00002771 // Lower any arguments needed in this block if this is the entry block.
2772 if (LLVMBB == &LLVMBB->getParent()->front())
2773 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002774
2775 BB = FuncInfo.MBBMap[LLVMBB];
2776 SDL.setCurrentBasicBlock(BB);
2777
2778 // Lower all of the non-terminator instructions.
2779 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2780 I != E; ++I)
2781 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00002782
Chris Lattner1c08c712005-01-07 07:47:53 +00002783 // Ensure that all instructions which are used outside of their defining
2784 // blocks are available as virtual registers.
2785 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002786 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002787 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002788 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002789 UnorderedChains.push_back(
2790 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002791 }
2792
2793 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2794 // ensure constants are generated when needed. Remember the virtual registers
2795 // that need to be added to the Machine PHI nodes as input. We cannot just
2796 // directly add them, because expansion might result in multiple MBB's for one
2797 // BB. As such, the start of the BB might correspond to a different MBB than
2798 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002799 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002800
2801 // Emit constants only once even if used by multiple PHI nodes.
2802 std::map<Constant*, unsigned> ConstantsOut;
2803
2804 // Check successor nodes PHI nodes that expect a constant to be available from
2805 // this block.
2806 TerminatorInst *TI = LLVMBB->getTerminator();
2807 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2808 BasicBlock *SuccBB = TI->getSuccessor(succ);
2809 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2810 PHINode *PN;
2811
2812 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2813 // nodes and Machine PHI nodes, but the incoming operands have not been
2814 // emitted yet.
2815 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002816 (PN = dyn_cast<PHINode>(I)); ++I)
2817 if (!PN->use_empty()) {
2818 unsigned Reg;
2819 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2820 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2821 unsigned &RegOut = ConstantsOut[C];
2822 if (RegOut == 0) {
2823 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002824 UnorderedChains.push_back(
2825 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002826 }
2827 Reg = RegOut;
2828 } else {
2829 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002830 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002831 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002832 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2833 "Didn't codegen value into a register!??");
2834 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002835 UnorderedChains.push_back(
2836 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002837 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002838 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002839
Chris Lattnerf44fd882005-01-07 21:34:19 +00002840 // Remember that this register needs to added to the machine PHI node as
2841 // the input for this MBB.
Chris Lattner7e021512006-03-31 02:12:18 +00002842 MVT::ValueType VT = TLI.getValueType(PN->getType());
2843 unsigned NumElements;
2844 if (VT != MVT::Vector)
2845 NumElements = TLI.getNumElements(VT);
2846 else {
2847 MVT::ValueType VT1,VT2;
2848 NumElements =
2849 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
2850 VT1, VT2);
2851 }
Chris Lattnerf44fd882005-01-07 21:34:19 +00002852 for (unsigned i = 0, e = NumElements; i != e; ++i)
2853 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002854 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002855 }
2856 ConstantsOut.clear();
2857
Chris Lattnerddb870b2005-01-13 17:59:43 +00002858 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002859 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002860 SDOperand Root = SDL.getRoot();
2861 if (Root.getOpcode() != ISD::EntryToken) {
2862 unsigned i = 0, e = UnorderedChains.size();
2863 for (; i != e; ++i) {
2864 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2865 if (UnorderedChains[i].Val->getOperand(0) == Root)
2866 break; // Don't add the root if we already indirectly depend on it.
2867 }
2868
2869 if (i == e)
2870 UnorderedChains.push_back(Root);
2871 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002872 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2873 }
2874
Chris Lattner1c08c712005-01-07 07:47:53 +00002875 // Lower the terminator after the copies are emitted.
2876 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002877
Nate Begemanf15485a2006-03-27 01:32:24 +00002878 // Copy over any CaseBlock records that may now exist due to SwitchInst
2879 // lowering.
2880 SwitchCases.clear();
2881 SwitchCases = SDL.SwitchCases;
2882
Chris Lattnera651cf62005-01-17 19:43:36 +00002883 // Make sure the root of the DAG is up-to-date.
2884 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002885}
2886
Nate Begemanf15485a2006-03-27 01:32:24 +00002887void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattneraf21d552005-10-10 16:47:10 +00002888 // Run the DAG combiner in pre-legalize mode.
2889 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002890
Chris Lattner1c08c712005-01-07 07:47:53 +00002891 DEBUG(std::cerr << "Lowered selection DAG:\n");
2892 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002893
Chris Lattner1c08c712005-01-07 07:47:53 +00002894 // Second step, hack on the DAG until it only uses operations and types that
2895 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002896 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00002897
Chris Lattner1c08c712005-01-07 07:47:53 +00002898 DEBUG(std::cerr << "Legalized selection DAG:\n");
2899 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002900
Chris Lattneraf21d552005-10-10 16:47:10 +00002901 // Run the DAG combiner in post-legalize mode.
2902 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002903
Evan Chenga9c20912006-01-21 02:32:06 +00002904 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002905
Chris Lattnera33ef482005-03-30 01:10:47 +00002906 // Third, instruction select all of the operations to machine code, adding the
2907 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002908 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00002909
Chris Lattner1c08c712005-01-07 07:47:53 +00002910 DEBUG(std::cerr << "Selected machine code:\n");
2911 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002912}
Chris Lattner1c08c712005-01-07 07:47:53 +00002913
Nate Begemanf15485a2006-03-27 01:32:24 +00002914void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2915 FunctionLoweringInfo &FuncInfo) {
2916 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2917 {
2918 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2919 CurDAG = &DAG;
2920
2921 // First step, lower LLVM code to some DAG. This DAG may use operations and
2922 // types that are not supported by the target.
2923 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2924
2925 // Second step, emit the lowered DAG as machine code.
2926 CodeGenAndEmitDAG(DAG);
2927 }
2928
Chris Lattnera33ef482005-03-30 01:10:47 +00002929 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002930 // PHI nodes in successors.
Nate Begemanf15485a2006-03-27 01:32:24 +00002931 if (SwitchCases.empty()) {
2932 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2933 MachineInstr *PHI = PHINodesToUpdate[i].first;
2934 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2935 "This is not a machine PHI node that we are updating!");
2936 PHI->addRegOperand(PHINodesToUpdate[i].second);
2937 PHI->addMachineBasicBlockOperand(BB);
2938 }
2939 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002940 }
Nate Begemanf15485a2006-03-27 01:32:24 +00002941
2942 // If we generated any switch lowering information, build and codegen any
2943 // additional DAGs necessary.
2944 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2945 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2946 CurDAG = &SDAG;
2947 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2948 // Set the current basic block to the mbb we wish to insert the code into
2949 BB = SwitchCases[i].ThisBB;
2950 SDL.setCurrentBasicBlock(BB);
2951 // Emit the code
2952 SDL.visitSwitchCase(SwitchCases[i]);
2953 SDAG.setRoot(SDL.getRoot());
2954 CodeGenAndEmitDAG(SDAG);
2955 // Iterate over the phi nodes, if there is a phi node in a successor of this
2956 // block (for instance, the default block), then add a pair of operands to
2957 // the phi node for this block, as if we were coming from the original
2958 // BB before switch expansion.
2959 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2960 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2961 MachineBasicBlock *PHIBB = PHI->getParent();
2962 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2963 "This is not a machine PHI node that we are updating!");
2964 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2965 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2966 PHI->addMachineBasicBlockOperand(BB);
2967 }
2968 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002969 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002970}
Evan Chenga9c20912006-01-21 02:32:06 +00002971
2972//===----------------------------------------------------------------------===//
2973/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2974/// target node in the graph.
2975void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2976 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002977 ScheduleDAG *SL = NULL;
2978
2979 switch (ISHeuristic) {
2980 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002981 case defaultScheduling:
2982 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2983 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2984 else /* TargetLowering::SchedulingForRegPressure */
2985 SL = createBURRListDAGScheduler(DAG, BB);
2986 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002987 case noScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002988 SL = createBFS_DAGScheduler(DAG, BB);
2989 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002990 case simpleScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002991 SL = createSimpleDAGScheduler(false, DAG, BB);
2992 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002993 case simpleNoItinScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002994 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002995 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002996 case listSchedulingBURR:
2997 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnera5de4842006-03-05 21:10:33 +00002998 break;
Chris Lattner03fc53c2006-03-06 00:22:00 +00002999 case listSchedulingTD:
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00003000 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattnera5de4842006-03-05 21:10:33 +00003001 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00003002 }
Chris Lattnera3818e62006-01-21 19:12:11 +00003003 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00003004 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00003005}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003006
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00003007HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3008 return new HazardRecognizer();
Chris Lattner03fc53c2006-03-06 00:22:00 +00003009}
3010
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003011/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3012/// by tblgen. Others should not call it.
3013void SelectionDAGISel::
3014SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3015 std::vector<SDOperand> InOps;
3016 std::swap(InOps, Ops);
3017
3018 Ops.push_back(InOps[0]); // input chain.
3019 Ops.push_back(InOps[1]); // input asm string.
3020
3021 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
3022 unsigned i = 2, e = InOps.size();
3023 if (InOps[e-1].getValueType() == MVT::Flag)
3024 --e; // Don't process a flag operand if it is here.
3025
3026 while (i != e) {
3027 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3028 if ((Flags & 7) != 4 /*MEM*/) {
3029 // Just skip over this operand, copying the operands verbatim.
3030 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3031 i += (Flags >> 3) + 1;
3032 } else {
3033 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3034 // Otherwise, this is a memory operand. Ask the target to select it.
3035 std::vector<SDOperand> SelOps;
3036 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3037 std::cerr << "Could not match memory address. Inline asm failure!\n";
3038 exit(1);
3039 }
3040
3041 // Add this to the output node.
3042 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3043 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3044 i += 2;
3045 }
3046 }
3047
3048 // Add the flag input back if present.
3049 if (e != InOps.size())
3050 Ops.push_back(InOps.back());
3051}