blob: 4eb33c163da64d5d627ef95ce8ddfad5eb3702f9 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-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 Lattnerd4382f02005-09-13 19:30:54 +000033#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-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 Lattnerc9950c12005-08-17 06:37:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000040#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
43#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000044#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattner975f5c92005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Cheng739a6a42006-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 Lattnere05a4612005-01-12 03:41:21 +000056#else
Chris Lattneref598052006-04-02 03:07:27 +000057static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-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 Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-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 Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-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 Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner49409cb2006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner7a60d912005-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 Begemaned728c12006-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 Lattner7a60d912005-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 Begemaned728c12006-03-27 01:32:24 +0000191 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
192 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 return true;
194 return false;
195}
196
Chris Lattner6871b232005-10-30 19:42:35 +0000197/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-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 Lattner6871b232005-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 Begemaned728c12006-03-27 01:32:24 +0000203 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000204 return false; // Use not in entry block.
205 return true;
206}
207
Chris Lattner7a60d912005-01-07 07:47:53 +0000208FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000209 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000210 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
211
Chris Lattner6871b232005-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 Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000222 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-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 Begeman3ee3e692005-11-06 09:00:38 +0000228 unsigned Align =
229 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
230 AI->getAlignment());
Chris Lattnercbefe722005-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 Lattner8396a302005-10-18 22:11:42 +0000239 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000240 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000242 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000243 }
244
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000245 for (; BB != EB; ++BB)
246 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000255 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-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 Lattner8ea875f2005-01-07 21:34:19 +0000264 (PN = dyn_cast<PHINode>(I)); ++I)
265 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-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 Lattner8ea875f2005-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 Lattner7a60d912005-01-07 07:47:53 +0000281 }
282}
283
Chris Lattner49409cb2006-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 Lattner7ececaa2006-03-16 23:05:19 +0000307 if (NumElts == 1)
308 VT = EltTy;
309 else
310 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-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 Lattner7a60d912005-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 Lattner4d9651c2005-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 Begemaned728c12006-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 Lattner7a60d912005-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 Begemaned728c12006-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 Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000407 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000408 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
409 FuncInfo(funcinfo) {
410 }
411
Chris Lattner4108bb02005-01-17 19:43:36 +0000412 /// getRoot - Return the current virtual root of the Selection DAG.
413 ///
414 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000415 if (PendingLoads.empty())
416 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000417
Chris Lattner4d9651c2005-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 Lattner4108bb02005-01-17 19:43:36 +0000430 }
431
Chris Lattner7a60d912005-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 Lattner4024c002006-03-15 22:19:46 +0000447 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
448 SDOperand SrcValue, SDOperand Root,
449 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000450
451 SDOperand getIntPtrConstant(uint64_t Val) {
452 return DAG.getConstant(Val, TLI.getPointerTy());
453 }
454
Chris Lattner8471b152006-03-16 19:57:50 +0000455 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-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 Lattner1558fc62006-02-01 18:59:47 +0000462
Chris Lattner6f87d182006-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 Begemaned728c12006-03-27 01:32:24 +0000468
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 // Terminator instructions.
470 void visitRet(ReturnInst &I);
471 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000472 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
Nate Begemaned728c12006-03-27 01:32:24 +0000475 // Helper for visitSwitch
476 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
477
Chris Lattner7a60d912005-01-07 07:47:53 +0000478 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
Nate Begemanb2e089c2005-11-19 00:36:38 +0000482 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000483 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000484 void visitAdd(User &I) {
485 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000486 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000487 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000488 void visitMul(User &I) {
489 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000490 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000492 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-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 Lattner7a60d912005-01-07 07:47:53 +0000496 }
497 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
Evan Cheng3bf916d2006-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 Begeman127321b2005-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 Lattner7a60d912005-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 Lattner67271862006-03-29 00:11:43 +0000517 void visitExtractElement(User &I);
518 void visitInsertElement(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000519
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 void visitGetElementPtr(User &I);
521 void visitCast(User &I);
522 void visitSelect(User &I);
Chris Lattner7a60d912005-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 Lattner476e67b2006-01-26 22:24:51 +0000531 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000532 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000533 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000534
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000536 void visitVAArg(VAArgInst &I);
537 void visitVAEnd(CallInst &I);
538 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000539 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000540
Chris Lattner875def92005-01-11 05:56:49 +0000541 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-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 Lattner8471b152006-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 Lattnerc16b05e2006-03-19 00:20:20 +0000570 if (!isa<PackedType>(VTy))
571 return N = DAG.getNode(ISD::UNDEF, VT);
572
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000573 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-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 Lattnerf4e1a532006-03-19 00:52:58 +0000584 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-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 Lattner8471b152006-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 Lattner67271862006-03-29 00:11:43 +0000596 for (unsigned i = 0; i != NumElements; ++i)
597 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-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 Lattnerf4e1a532006-03-19 00:52:58 +0000608 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000609 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
610 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000611 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-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 Lattner5fe1f542006-03-31 02:06:56 +0000632 if (VT != MVT::Vector) {
633 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000634
Chris Lattner5fe1f542006-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 Lattner8471b152006-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 Lattner5fe1f542006-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;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000651 const PackedType *PTy = cast<PackedType>(VTy);
652 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000653 PTyLegalElementVT);
654
655 // Build a VBUILD_VECTOR with the input registers.
656 std::vector<SDOperand> Ops;
657 if (PTyElementVT == PTyLegalElementVT) {
658 // If the value types are legal, just VBUILD the CopyFromReg nodes.
659 for (unsigned i = 0; i != NE; ++i)
660 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
661 PTyElementVT));
662 } else if (PTyElementVT < PTyLegalElementVT) {
663 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
664 for (unsigned i = 0; i != NE; ++i) {
665 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
666 PTyElementVT);
667 if (MVT::isFloatingPoint(PTyElementVT))
668 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
669 else
670 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
671 Ops.push_back(Op);
672 }
673 } else {
674 // If the register was expanded, use BUILD_PAIR.
675 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
676 for (unsigned i = 0; i != NE/2; ++i) {
677 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
678 PTyElementVT);
679 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
680 PTyElementVT);
681 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
682 }
683 }
684
685 Ops.push_back(DAG.getConstant(NE, MVT::i32));
686 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
687 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner4a2413a2006-04-05 06:54:42 +0000688
689 // Finally, use a VBIT_CONVERT to make this available as the appropriate
690 // vector type.
691 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
692 DAG.getConstant(PTy->getNumElements(),
693 MVT::i32),
694 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000695 }
696
697 return N;
698}
699
700
Chris Lattner7a60d912005-01-07 07:47:53 +0000701void SelectionDAGLowering::visitRet(ReturnInst &I) {
702 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000703 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000704 return;
705 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000706 std::vector<SDOperand> NewValues;
707 NewValues.push_back(getRoot());
708 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
709 SDOperand RetOp = getValue(I.getOperand(i));
710
711 // If this is an integer return value, we need to promote it ourselves to
712 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
713 // than sign/zero.
714 if (MVT::isInteger(RetOp.getValueType()) &&
715 RetOp.getValueType() < MVT::i64) {
716 MVT::ValueType TmpVT;
717 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
718 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
719 else
720 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000721
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000722 if (I.getOperand(i)->getType()->isSigned())
723 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
724 else
725 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
726 }
727 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000728 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000729 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000730}
731
732void SelectionDAGLowering::visitBr(BranchInst &I) {
733 // Update machine-CFG edges.
734 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000735 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000736
737 // Figure out which block is immediately after the current one.
738 MachineBasicBlock *NextBlock = 0;
739 MachineFunction::iterator BBI = CurMBB;
740 if (++BBI != CurMBB->getParent()->end())
741 NextBlock = BBI;
742
743 if (I.isUnconditional()) {
744 // If this is not a fall-through branch, emit the branch.
745 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000746 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000747 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000748 } else {
749 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000750 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000751
752 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000753 if (Succ1MBB == NextBlock) {
754 // If the condition is false, fall through. This means we should branch
755 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000756 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000757 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000758 } else if (Succ0MBB == NextBlock) {
759 // If the condition is true, fall through. This means we should branch if
760 // the condition is false to Succ #1. Invert the condition first.
761 SDOperand True = DAG.getConstant(1, Cond.getValueType());
762 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000763 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000764 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000765 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000766 std::vector<SDOperand> Ops;
767 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000768 // If the false case is the current basic block, then this is a self
769 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
770 // adds an extra instruction in the loop. Instead, invert the
771 // condition and emit "Loop: ... br!cond Loop; br Out.
772 if (CurMBB == Succ1MBB) {
773 std::swap(Succ0MBB, Succ1MBB);
774 SDOperand True = DAG.getConstant(1, Cond.getValueType());
775 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
776 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000777 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
778 DAG.getBasicBlock(Succ0MBB));
779 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
780 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
782 }
783}
784
Nate Begemaned728c12006-03-27 01:32:24 +0000785/// visitSwitchCase - Emits the necessary code to represent a single node in
786/// the binary search tree resulting from lowering a switch instruction.
787void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
788 SDOperand SwitchOp = getValue(CB.SwitchV);
789 SDOperand CaseOp = getValue(CB.CaseC);
790 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
791
792 // Set NextBlock to be the MBB immediately after the current one, if any.
793 // This is used to avoid emitting unnecessary branches to the next block.
794 MachineBasicBlock *NextBlock = 0;
795 MachineFunction::iterator BBI = CurMBB;
796 if (++BBI != CurMBB->getParent()->end())
797 NextBlock = BBI;
798
799 // If the lhs block is the next block, invert the condition so that we can
800 // fall through to the lhs instead of the rhs block.
801 if (CB.LHSBB == NextBlock) {
802 std::swap(CB.LHSBB, CB.RHSBB);
803 SDOperand True = DAG.getConstant(1, Cond.getValueType());
804 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
805 }
806 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
807 DAG.getBasicBlock(CB.LHSBB));
808 if (CB.RHSBB == NextBlock)
809 DAG.setRoot(BrCond);
810 else
811 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
812 DAG.getBasicBlock(CB.RHSBB)));
813 // Update successor info
814 CurMBB->addSuccessor(CB.LHSBB);
815 CurMBB->addSuccessor(CB.RHSBB);
816}
817
818void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
819 // Figure out which block is immediately after the current one.
820 MachineBasicBlock *NextBlock = 0;
821 MachineFunction::iterator BBI = CurMBB;
822 if (++BBI != CurMBB->getParent()->end())
823 NextBlock = BBI;
824
825 // If there is only the default destination, branch to it if it is not the
826 // next basic block. Otherwise, just fall through.
827 if (I.getNumOperands() == 2) {
828 // Update machine-CFG edges.
829 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
830 // If this is not a fall-through branch, emit the branch.
831 if (DefaultMBB != NextBlock)
832 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
833 DAG.getBasicBlock(DefaultMBB)));
834 return;
835 }
836
837 // If there are any non-default case statements, create a vector of Cases
838 // representing each one, and sort the vector so that we can efficiently
839 // create a binary search tree from them.
840 std::vector<Case> Cases;
841 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
842 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
843 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
844 }
845 std::sort(Cases.begin(), Cases.end(), CaseCmp());
846
847 // Get the Value to be switched on and default basic blocks, which will be
848 // inserted into CaseBlock records, representing basic blocks in the binary
849 // search tree.
850 Value *SV = I.getOperand(0);
851 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
852
853 // Get the current MachineFunction and LLVM basic block, for use in creating
854 // and inserting new MBBs during the creation of the binary search tree.
855 MachineFunction *CurMF = CurMBB->getParent();
856 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
857
858 // Push the initial CaseRec onto the worklist
859 std::vector<CaseRec> CaseVec;
860 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
861
862 while (!CaseVec.empty()) {
863 // Grab a record representing a case range to process off the worklist
864 CaseRec CR = CaseVec.back();
865 CaseVec.pop_back();
866
867 // Size is the number of Cases represented by this range. If Size is 1,
868 // then we are processing a leaf of the binary search tree. Otherwise,
869 // we need to pick a pivot, and push left and right ranges onto the
870 // worklist.
871 unsigned Size = CR.Range.second - CR.Range.first;
872
873 if (Size == 1) {
874 // Create a CaseBlock record representing a conditional branch to
875 // the Case's target mbb if the value being switched on SV is equal
876 // to C. Otherwise, branch to default.
877 Constant *C = CR.Range.first->first;
878 MachineBasicBlock *Target = CR.Range.first->second;
879 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
880 CR.CaseBB);
881 // If the MBB representing the leaf node is the current MBB, then just
882 // call visitSwitchCase to emit the code into the current block.
883 // Otherwise, push the CaseBlock onto the vector to be later processed
884 // by SDISel, and insert the node's MBB before the next MBB.
885 if (CR.CaseBB == CurMBB)
886 visitSwitchCase(CB);
887 else {
888 SwitchCases.push_back(CB);
889 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
890 }
891 } else {
892 // split case range at pivot
893 CaseItr Pivot = CR.Range.first + (Size / 2);
894 CaseRange LHSR(CR.Range.first, Pivot);
895 CaseRange RHSR(Pivot, CR.Range.second);
896 Constant *C = Pivot->first;
897 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
898 // We know that we branch to the LHS if the Value being switched on is
899 // less than the Pivot value, C. We use this to optimize our binary
900 // tree a bit, by recognizing that if SV is greater than or equal to the
901 // LHS's Case Value, and that Case Value is exactly one less than the
902 // Pivot's Value, then we can branch directly to the LHS's Target,
903 // rather than creating a leaf node for it.
904 if ((LHSR.second - LHSR.first) == 1 &&
905 LHSR.first->first == CR.GE &&
906 cast<ConstantIntegral>(C)->getRawValue() ==
907 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
908 LHSBB = LHSR.first->second;
909 } else {
910 LHSBB = new MachineBasicBlock(LLVMBB);
911 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
912 }
913 // Similar to the optimization above, if the Value being switched on is
914 // known to be less than the Constant CR.LT, and the current Case Value
915 // is CR.LT - 1, then we can branch directly to the target block for
916 // the current Case Value, rather than emitting a RHS leaf node for it.
917 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
918 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
919 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
920 RHSBB = RHSR.first->second;
921 } else {
922 RHSBB = new MachineBasicBlock(LLVMBB);
923 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
924 }
925 // Create a CaseBlock record representing a conditional branch to
926 // the LHS node if the value being switched on SV is less than C.
927 // Otherwise, branch to LHS.
928 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
929 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
930 if (CR.CaseBB == CurMBB)
931 visitSwitchCase(CB);
932 else {
933 SwitchCases.push_back(CB);
934 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
935 }
936 }
937 }
938}
939
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000940void SelectionDAGLowering::visitSub(User &I) {
941 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000942 if (I.getType()->isFloatingPoint()) {
943 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
944 if (CFP->isExactlyValue(-0.0)) {
945 SDOperand Op2 = getValue(I.getOperand(1));
946 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
947 return;
948 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000949 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000950 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000951}
952
Nate Begemanb2e089c2005-11-19 00:36:38 +0000953void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
954 unsigned VecOp) {
955 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000956 SDOperand Op1 = getValue(I.getOperand(0));
957 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000958
Chris Lattner19baba62005-11-19 18:40:42 +0000959 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000960 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
961 } else if (Ty->isFloatingPoint()) {
962 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
963 } else {
964 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000965 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
966 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
967 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000968 }
Nate Begeman127321b2005-11-18 07:42:56 +0000969}
Chris Lattner96c26752005-01-19 22:31:21 +0000970
Nate Begeman127321b2005-11-18 07:42:56 +0000971void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
972 SDOperand Op1 = getValue(I.getOperand(0));
973 SDOperand Op2 = getValue(I.getOperand(1));
974
975 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
976
Chris Lattner7a60d912005-01-07 07:47:53 +0000977 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
978}
979
980void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
981 ISD::CondCode UnsignedOpcode) {
982 SDOperand Op1 = getValue(I.getOperand(0));
983 SDOperand Op2 = getValue(I.getOperand(1));
984 ISD::CondCode Opcode = SignedOpcode;
985 if (I.getOperand(0)->getType()->isUnsigned())
986 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000987 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000988}
989
990void SelectionDAGLowering::visitSelect(User &I) {
991 SDOperand Cond = getValue(I.getOperand(0));
992 SDOperand TrueVal = getValue(I.getOperand(1));
993 SDOperand FalseVal = getValue(I.getOperand(2));
994 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
995 TrueVal, FalseVal));
996}
997
998void SelectionDAGLowering::visitCast(User &I) {
999 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001000 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001001 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001002
Chris Lattner2f4119a2006-03-22 20:09:35 +00001003 if (DestVT == MVT::Vector) {
1004 // This is a cast to a vector from something else. This is always a bit
1005 // convert. Get information about the input vector.
1006 const PackedType *DestTy = cast<PackedType>(I.getType());
1007 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1008 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1009 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1010 DAG.getValueType(EltVT)));
1011 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001012 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001013 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001014 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001015 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001016 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001017 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001018 } else if (isInteger(SrcVT)) {
1019 if (isInteger(DestVT)) { // Int -> Int cast
1020 if (DestVT < SrcVT) // Truncating cast?
1021 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001022 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001023 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001024 else
Chris Lattner4024c002006-03-15 22:19:46 +00001025 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001026 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001027 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001028 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001029 else
Chris Lattner4024c002006-03-15 22:19:46 +00001030 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001031 } else {
1032 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001033 }
Chris Lattner4024c002006-03-15 22:19:46 +00001034 } else if (isFloatingPoint(SrcVT)) {
1035 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1036 if (DestVT < SrcVT) // Rounding cast?
1037 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001038 else
Chris Lattner4024c002006-03-15 22:19:46 +00001039 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001040 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001041 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001042 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001043 else
Chris Lattner4024c002006-03-15 22:19:46 +00001044 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001045 } else {
1046 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001047 }
1048 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001049 assert(SrcVT == MVT::Vector && "Unknown cast!");
1050 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1051 // This is a cast from a vector to something else. This is always a bit
1052 // convert. Get information about the input vector.
1053 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001054 }
1055}
1056
Chris Lattner67271862006-03-29 00:11:43 +00001057void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001058 SDOperand InVec = getValue(I.getOperand(0));
1059 SDOperand InVal = getValue(I.getOperand(1));
1060 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1061 getValue(I.getOperand(2)));
1062
Chris Lattner29b23012006-03-19 01:17:20 +00001063 SDOperand Num = *(InVec.Val->op_end()-2);
1064 SDOperand Typ = *(InVec.Val->op_end()-1);
1065 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1066 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001067}
1068
Chris Lattner67271862006-03-29 00:11:43 +00001069void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001070 SDOperand InVec = getValue(I.getOperand(0));
1071 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1072 getValue(I.getOperand(1)));
1073 SDOperand Typ = *(InVec.Val->op_end()-1);
1074 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1075 TLI.getValueType(I.getType()), InVec, InIdx));
1076}
Chris Lattner32206f52006-03-18 01:44:44 +00001077
Chris Lattner7a60d912005-01-07 07:47:53 +00001078void SelectionDAGLowering::visitGetElementPtr(User &I) {
1079 SDOperand N = getValue(I.getOperand(0));
1080 const Type *Ty = I.getOperand(0)->getType();
1081 const Type *UIntPtrTy = TD.getIntPtrType();
1082
1083 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1084 OI != E; ++OI) {
1085 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001086 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001087 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1088 if (Field) {
1089 // N = N + Offset
1090 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1091 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001092 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001093 }
1094 Ty = StTy->getElementType(Field);
1095 } else {
1096 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001097
Chris Lattner43535a12005-11-09 04:45:33 +00001098 // If this is a constant subscript, handle it quickly.
1099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1100 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001101
Chris Lattner43535a12005-11-09 04:45:33 +00001102 uint64_t Offs;
1103 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1104 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1105 else
1106 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1107 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1108 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001109 }
Chris Lattner43535a12005-11-09 04:45:33 +00001110
1111 // N = N + Idx * ElementSize;
1112 uint64_t ElementSize = TD.getTypeSize(Ty);
1113 SDOperand IdxN = getValue(Idx);
1114
1115 // If the index is smaller or larger than intptr_t, truncate or extend
1116 // it.
1117 if (IdxN.getValueType() < N.getValueType()) {
1118 if (Idx->getType()->isSigned())
1119 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1120 else
1121 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1122 } else if (IdxN.getValueType() > N.getValueType())
1123 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1124
1125 // If this is a multiply by a power of two, turn it into a shl
1126 // immediately. This is a very common case.
1127 if (isPowerOf2_64(ElementSize)) {
1128 unsigned Amt = Log2_64(ElementSize);
1129 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001130 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001131 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1132 continue;
1133 }
1134
1135 SDOperand Scale = getIntPtrConstant(ElementSize);
1136 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1137 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001138 }
1139 }
1140 setValue(&I, N);
1141}
1142
1143void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1144 // If this is a fixed sized alloca in the entry block of the function,
1145 // allocate it statically on the stack.
1146 if (FuncInfo.StaticAllocaMap.count(&I))
1147 return; // getValue will auto-populate this.
1148
1149 const Type *Ty = I.getAllocatedType();
1150 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +00001151 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1152 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001153
1154 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001155 MVT::ValueType IntPtr = TLI.getPointerTy();
1156 if (IntPtr < AllocSize.getValueType())
1157 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1158 else if (IntPtr > AllocSize.getValueType())
1159 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001160
Chris Lattnereccb73d2005-01-22 23:04:37 +00001161 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001162 getIntPtrConstant(TySize));
1163
1164 // Handle alignment. If the requested alignment is less than or equal to the
1165 // stack alignment, ignore it and round the size of the allocation up to the
1166 // stack alignment size. If the size is greater than the stack alignment, we
1167 // note this in the DYNAMIC_STACKALLOC node.
1168 unsigned StackAlign =
1169 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1170 if (Align <= StackAlign) {
1171 Align = 0;
1172 // Add SA-1 to the size.
1173 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1174 getIntPtrConstant(StackAlign-1));
1175 // Mask out the low bits for alignment purposes.
1176 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1177 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1178 }
1179
Chris Lattner96c262e2005-05-14 07:29:57 +00001180 std::vector<MVT::ValueType> VTs;
1181 VTs.push_back(AllocSize.getValueType());
1182 VTs.push_back(MVT::Other);
1183 std::vector<SDOperand> Ops;
1184 Ops.push_back(getRoot());
1185 Ops.push_back(AllocSize);
1186 Ops.push_back(getIntPtrConstant(Align));
1187 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +00001188 DAG.setRoot(setValue(&I, DSA).getValue(1));
1189
1190 // Inform the Frame Information that we have just allocated a variable-sized
1191 // object.
1192 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1193}
1194
Chris Lattner7a60d912005-01-07 07:47:53 +00001195void SelectionDAGLowering::visitLoad(LoadInst &I) {
1196 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001197
Chris Lattner4d9651c2005-01-17 22:19:26 +00001198 SDOperand Root;
1199 if (I.isVolatile())
1200 Root = getRoot();
1201 else {
1202 // Do not serialize non-volatile loads against each other.
1203 Root = DAG.getRoot();
1204 }
Chris Lattner4024c002006-03-15 22:19:46 +00001205
1206 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1207 Root, I.isVolatile()));
1208}
1209
1210SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1211 SDOperand SrcValue, SDOperand Root,
1212 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001213 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001214 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001215 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001216 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001217 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001218 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001219 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001220
Chris Lattner4024c002006-03-15 22:19:46 +00001221 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001222 DAG.setRoot(L.getValue(1));
1223 else
1224 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001225
1226 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001227}
1228
1229
1230void SelectionDAGLowering::visitStore(StoreInst &I) {
1231 Value *SrcV = I.getOperand(0);
1232 SDOperand Src = getValue(SrcV);
1233 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001234 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001235 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001236}
1237
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001238/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1239/// access memory and has no other side effects at all.
1240static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1241#define GET_NO_MEMORY_INTRINSICS
1242#include "llvm/Intrinsics.gen"
1243#undef GET_NO_MEMORY_INTRINSICS
1244 return false;
1245}
1246
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001247// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1248// have any side-effects or if it only reads memory.
1249static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1250#define GET_SIDE_EFFECT_INFO
1251#include "llvm/Intrinsics.gen"
1252#undef GET_SIDE_EFFECT_INFO
1253 return false;
1254}
1255
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001256/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1257/// node.
1258void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1259 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001260 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001261 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001262
1263 // Build the operand list.
1264 std::vector<SDOperand> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001265 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1266 if (OnlyLoad) {
1267 // We don't need to serialize loads against other loads.
1268 Ops.push_back(DAG.getRoot());
1269 } else {
1270 Ops.push_back(getRoot());
1271 }
1272 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001273
1274 // Add the intrinsic ID as an integer operand.
1275 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1276
1277 // Add all operands of the call to the operand list.
1278 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1279 SDOperand Op = getValue(I.getOperand(i));
1280
1281 // If this is a vector type, force it to the right packed type.
1282 if (Op.getValueType() == MVT::Vector) {
1283 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1284 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1285
1286 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1287 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1288 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1289 }
1290
1291 assert(TLI.isTypeLegal(Op.getValueType()) &&
1292 "Intrinsic uses a non-legal type?");
1293 Ops.push_back(Op);
1294 }
1295
1296 std::vector<MVT::ValueType> VTs;
1297 if (I.getType() != Type::VoidTy) {
1298 MVT::ValueType VT = TLI.getValueType(I.getType());
1299 if (VT == MVT::Vector) {
1300 const PackedType *DestTy = cast<PackedType>(I.getType());
1301 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1302
1303 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1304 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1305 }
1306
1307 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1308 VTs.push_back(VT);
1309 }
1310 if (HasChain)
1311 VTs.push_back(MVT::Other);
1312
1313 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001314 SDOperand Result;
1315 if (!HasChain)
1316 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1317 else if (I.getType() != Type::VoidTy)
1318 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1319 else
1320 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1321
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001322 if (HasChain) {
1323 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1324 if (OnlyLoad)
1325 PendingLoads.push_back(Chain);
1326 else
1327 DAG.setRoot(Chain);
1328 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001329 if (I.getType() != Type::VoidTy) {
1330 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1331 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1332 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1333 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1334 DAG.getValueType(EVT));
1335 }
1336 setValue(&I, Result);
1337 }
1338}
1339
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001340/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1341/// we want to emit this as a call to a named external function, return the name
1342/// otherwise lower it and return null.
1343const char *
1344SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1345 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001346 default:
1347 // By default, turn this into a target intrinsic node.
1348 visitTargetIntrinsic(I, Intrinsic);
1349 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001350 case Intrinsic::vastart: visitVAStart(I); return 0;
1351 case Intrinsic::vaend: visitVAEnd(I); return 0;
1352 case Intrinsic::vacopy: visitVACopy(I); return 0;
1353 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1354 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1355 case Intrinsic::setjmp:
1356 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1357 break;
1358 case Intrinsic::longjmp:
1359 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1360 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001361 case Intrinsic::memcpy_i32:
1362 case Intrinsic::memcpy_i64:
1363 visitMemIntrinsic(I, ISD::MEMCPY);
1364 return 0;
1365 case Intrinsic::memset_i32:
1366 case Intrinsic::memset_i64:
1367 visitMemIntrinsic(I, ISD::MEMSET);
1368 return 0;
1369 case Intrinsic::memmove_i32:
1370 case Intrinsic::memmove_i64:
1371 visitMemIntrinsic(I, ISD::MEMMOVE);
1372 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001373
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001374 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001375 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001376 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001377 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001378 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001379
Jim Laskey5995d012006-02-11 01:01:30 +00001380 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001381 Ops.push_back(getValue(SPI.getLineValue()));
1382 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001383
Jim Laskeya8bdac82006-03-23 18:06:46 +00001384 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001385 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001386 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1387
Jim Laskey5995d012006-02-11 01:01:30 +00001388 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1389 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1390
Jim Laskeya8bdac82006-03-23 18:06:46 +00001391 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001392 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001393
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001394 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001395 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001396 case Intrinsic::dbg_region_start: {
1397 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1398 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001399 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001400 std::vector<SDOperand> Ops;
1401
1402 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1403
1404 Ops.push_back(getRoot());
1405 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1406
1407 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1408 }
1409
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001410 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001411 }
1412 case Intrinsic::dbg_region_end: {
1413 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1414 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001415 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001416 std::vector<SDOperand> Ops;
1417
1418 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1419
1420 Ops.push_back(getRoot());
1421 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1422
1423 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1424 }
1425
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001426 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001427 }
1428 case Intrinsic::dbg_func_start: {
1429 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1430 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001431 if (DebugInfo && FSI.getSubprogram() &&
1432 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001433 std::vector<SDOperand> Ops;
1434
1435 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1436
1437 Ops.push_back(getRoot());
1438 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1439
1440 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1441 }
1442
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001443 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001444 }
1445 case Intrinsic::dbg_declare: {
1446 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1447 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001448 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001449 std::vector<SDOperand> Ops;
1450
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001451 SDOperand AddressOp = getValue(DI.getAddress());
1452 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001453 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1454 }
1455 }
1456
1457 return 0;
1458 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001459
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001460 case Intrinsic::isunordered_f32:
1461 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001462 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1463 getValue(I.getOperand(2)), ISD::SETUO));
1464 return 0;
1465
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001466 case Intrinsic::sqrt_f32:
1467 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001468 setValue(&I, DAG.getNode(ISD::FSQRT,
1469 getValue(I.getOperand(1)).getValueType(),
1470 getValue(I.getOperand(1))));
1471 return 0;
1472 case Intrinsic::pcmarker: {
1473 SDOperand Tmp = getValue(I.getOperand(1));
1474 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1475 return 0;
1476 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001477 case Intrinsic::readcyclecounter: {
1478 std::vector<MVT::ValueType> VTs;
1479 VTs.push_back(MVT::i64);
1480 VTs.push_back(MVT::Other);
1481 std::vector<SDOperand> Ops;
1482 Ops.push_back(getRoot());
1483 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1484 setValue(&I, Tmp);
1485 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001486 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001487 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001488 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001489 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001490 case Intrinsic::bswap_i64:
1491 setValue(&I, DAG.getNode(ISD::BSWAP,
1492 getValue(I.getOperand(1)).getValueType(),
1493 getValue(I.getOperand(1))));
1494 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001495 case Intrinsic::cttz_i8:
1496 case Intrinsic::cttz_i16:
1497 case Intrinsic::cttz_i32:
1498 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001499 setValue(&I, DAG.getNode(ISD::CTTZ,
1500 getValue(I.getOperand(1)).getValueType(),
1501 getValue(I.getOperand(1))));
1502 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001503 case Intrinsic::ctlz_i8:
1504 case Intrinsic::ctlz_i16:
1505 case Intrinsic::ctlz_i32:
1506 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001507 setValue(&I, DAG.getNode(ISD::CTLZ,
1508 getValue(I.getOperand(1)).getValueType(),
1509 getValue(I.getOperand(1))));
1510 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001511 case Intrinsic::ctpop_i8:
1512 case Intrinsic::ctpop_i16:
1513 case Intrinsic::ctpop_i32:
1514 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001515 setValue(&I, DAG.getNode(ISD::CTPOP,
1516 getValue(I.getOperand(1)).getValueType(),
1517 getValue(I.getOperand(1))));
1518 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001519 case Intrinsic::stacksave: {
1520 std::vector<MVT::ValueType> VTs;
1521 VTs.push_back(TLI.getPointerTy());
1522 VTs.push_back(MVT::Other);
1523 std::vector<SDOperand> Ops;
1524 Ops.push_back(getRoot());
1525 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1526 setValue(&I, Tmp);
1527 DAG.setRoot(Tmp.getValue(1));
1528 return 0;
1529 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001530 case Intrinsic::stackrestore: {
1531 SDOperand Tmp = getValue(I.getOperand(1));
1532 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001533 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001534 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001535 case Intrinsic::prefetch:
1536 // FIXME: Currently discarding prefetches.
1537 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001538 }
1539}
1540
1541
Chris Lattner7a60d912005-01-07 07:47:53 +00001542void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001543 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001544 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001545 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001546 if (unsigned IID = F->getIntrinsicID()) {
1547 RenameFn = visitIntrinsicCall(I, IID);
1548 if (!RenameFn)
1549 return;
1550 } else { // Not an LLVM intrinsic.
1551 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001552 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1553 if (I.getNumOperands() == 3 && // Basic sanity checks.
1554 I.getOperand(1)->getType()->isFloatingPoint() &&
1555 I.getType() == I.getOperand(1)->getType() &&
1556 I.getType() == I.getOperand(2)->getType()) {
1557 SDOperand LHS = getValue(I.getOperand(1));
1558 SDOperand RHS = getValue(I.getOperand(2));
1559 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1560 LHS, RHS));
1561 return;
1562 }
1563 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001564 if (I.getNumOperands() == 2 && // Basic sanity checks.
1565 I.getOperand(1)->getType()->isFloatingPoint() &&
1566 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001567 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001568 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1569 return;
1570 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001571 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001572 if (I.getNumOperands() == 2 && // Basic sanity checks.
1573 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001574 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001575 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001576 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1577 return;
1578 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001579 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001580 if (I.getNumOperands() == 2 && // Basic sanity checks.
1581 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001582 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001583 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001584 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1585 return;
1586 }
1587 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001588 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001589 } else if (isa<InlineAsm>(I.getOperand(0))) {
1590 visitInlineAsm(I);
1591 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001592 }
Misha Brukman835702a2005-04-21 22:36:52 +00001593
Chris Lattner18d2b342005-01-08 22:48:57 +00001594 SDOperand Callee;
1595 if (!RenameFn)
1596 Callee = getValue(I.getOperand(0));
1597 else
1598 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001599 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001600 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001601 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1602 Value *Arg = I.getOperand(i);
1603 SDOperand ArgNode = getValue(Arg);
1604 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1605 }
Misha Brukman835702a2005-04-21 22:36:52 +00001606
Nate Begemanf6565252005-03-26 01:29:23 +00001607 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1608 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001609
Chris Lattner1f45cd72005-01-08 19:26:18 +00001610 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001611 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001612 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001613 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001614 setValue(&I, Result.first);
1615 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001616}
1617
Chris Lattner6f87d182006-02-22 22:37:12 +00001618SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001619 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001620 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1621 Chain = Val.getValue(1);
1622 Flag = Val.getValue(2);
1623
1624 // If the result was expanded, copy from the top part.
1625 if (Regs.size() > 1) {
1626 assert(Regs.size() == 2 &&
1627 "Cannot expand to more than 2 elts yet!");
1628 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1629 Chain = Val.getValue(1);
1630 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001631 if (DAG.getTargetLoweringInfo().isLittleEndian())
1632 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1633 else
1634 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001635 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001636
Chris Lattner6f87d182006-02-22 22:37:12 +00001637 // Otherwise, if the return value was promoted, truncate it to the
1638 // appropriate type.
1639 if (RegVT == ValueVT)
1640 return Val;
1641
1642 if (MVT::isInteger(RegVT))
1643 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1644 else
1645 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1646}
1647
Chris Lattner571d9642006-02-23 19:21:04 +00001648/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1649/// specified value into the registers specified by this object. This uses
1650/// Chain/Flag as the input and updates them for the output Chain/Flag.
1651void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001652 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001653 if (Regs.size() == 1) {
1654 // If there is a single register and the types differ, this must be
1655 // a promotion.
1656 if (RegVT != ValueVT) {
1657 if (MVT::isInteger(RegVT))
1658 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1659 else
1660 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1661 }
1662 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1663 Flag = Chain.getValue(1);
1664 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001665 std::vector<unsigned> R(Regs);
1666 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1667 std::reverse(R.begin(), R.end());
1668
1669 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001670 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1671 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001672 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001673 Flag = Chain.getValue(1);
1674 }
1675 }
1676}
Chris Lattner6f87d182006-02-22 22:37:12 +00001677
Chris Lattner571d9642006-02-23 19:21:04 +00001678/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1679/// operand list. This adds the code marker and includes the number of
1680/// values added into it.
1681void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001682 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001683 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1684 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1685 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1686}
Chris Lattner6f87d182006-02-22 22:37:12 +00001687
1688/// isAllocatableRegister - If the specified register is safe to allocate,
1689/// i.e. it isn't a stack pointer or some other special register, return the
1690/// register class for the register. Otherwise, return null.
1691static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001692isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1693 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001694 MVT::ValueType FoundVT = MVT::Other;
1695 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001696 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1697 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001698 MVT::ValueType ThisVT = MVT::Other;
1699
Chris Lattnerb1124f32006-02-22 23:09:03 +00001700 const TargetRegisterClass *RC = *RCI;
1701 // If none of the the value types for this register class are valid, we
1702 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001703 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1704 I != E; ++I) {
1705 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001706 // If we have already found this register in a different register class,
1707 // choose the one with the largest VT specified. For example, on
1708 // PowerPC, we favor f64 register classes over f32.
1709 if (FoundVT == MVT::Other ||
1710 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1711 ThisVT = *I;
1712 break;
1713 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001714 }
1715 }
1716
Chris Lattnerbec582f2006-04-02 00:24:45 +00001717 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001718
Chris Lattner6f87d182006-02-22 22:37:12 +00001719 // NOTE: This isn't ideal. In particular, this might allocate the
1720 // frame pointer in functions that need it (due to them not being taken
1721 // out of allocation, because a variable sized allocation hasn't been seen
1722 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001723 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1724 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001725 if (*I == Reg) {
1726 // We found a matching register class. Keep looking at others in case
1727 // we find one with larger registers that this physreg is also in.
1728 FoundRC = RC;
1729 FoundVT = ThisVT;
1730 break;
1731 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001732 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001733 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001734}
1735
1736RegsForValue SelectionDAGLowering::
1737GetRegistersForValue(const std::string &ConstrCode,
1738 MVT::ValueType VT, bool isOutReg, bool isInReg,
1739 std::set<unsigned> &OutputRegs,
1740 std::set<unsigned> &InputRegs) {
1741 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1742 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1743 std::vector<unsigned> Regs;
1744
1745 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1746 MVT::ValueType RegVT;
1747 MVT::ValueType ValueVT = VT;
1748
1749 if (PhysReg.first) {
1750 if (VT == MVT::Other)
1751 ValueVT = *PhysReg.second->vt_begin();
1752 RegVT = VT;
1753
1754 // This is a explicit reference to a physical register.
1755 Regs.push_back(PhysReg.first);
1756
1757 // If this is an expanded reference, add the rest of the regs to Regs.
1758 if (NumRegs != 1) {
1759 RegVT = *PhysReg.second->vt_begin();
1760 TargetRegisterClass::iterator I = PhysReg.second->begin();
1761 TargetRegisterClass::iterator E = PhysReg.second->end();
1762 for (; *I != PhysReg.first; ++I)
1763 assert(I != E && "Didn't find reg!");
1764
1765 // Already added the first reg.
1766 --NumRegs; ++I;
1767 for (; NumRegs; --NumRegs, ++I) {
1768 assert(I != E && "Ran out of registers to allocate!");
1769 Regs.push_back(*I);
1770 }
1771 }
1772 return RegsForValue(Regs, RegVT, ValueVT);
1773 }
1774
1775 // This is a reference to a register class. Allocate NumRegs consecutive,
1776 // available, registers from the class.
1777 std::vector<unsigned> RegClassRegs =
1778 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1779
1780 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1781 MachineFunction &MF = *CurMBB->getParent();
1782 unsigned NumAllocated = 0;
1783 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1784 unsigned Reg = RegClassRegs[i];
1785 // See if this register is available.
1786 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1787 (isInReg && InputRegs.count(Reg))) { // Already used.
1788 // Make sure we find consecutive registers.
1789 NumAllocated = 0;
1790 continue;
1791 }
1792
1793 // Check to see if this register is allocatable (i.e. don't give out the
1794 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001795 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001796 if (!RC) {
1797 // Make sure we find consecutive registers.
1798 NumAllocated = 0;
1799 continue;
1800 }
1801
1802 // Okay, this register is good, we can use it.
1803 ++NumAllocated;
1804
1805 // If we allocated enough consecutive
1806 if (NumAllocated == NumRegs) {
1807 unsigned RegStart = (i-NumAllocated)+1;
1808 unsigned RegEnd = i+1;
1809 // Mark all of the allocated registers used.
1810 for (unsigned i = RegStart; i != RegEnd; ++i) {
1811 unsigned Reg = RegClassRegs[i];
1812 Regs.push_back(Reg);
1813 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1814 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1815 }
1816
1817 return RegsForValue(Regs, *RC->vt_begin(), VT);
1818 }
1819 }
1820
1821 // Otherwise, we couldn't allocate enough registers for this.
1822 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001823}
1824
Chris Lattner6f87d182006-02-22 22:37:12 +00001825
Chris Lattner476e67b2006-01-26 22:24:51 +00001826/// visitInlineAsm - Handle a call to an InlineAsm object.
1827///
1828void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1829 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1830
1831 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1832 MVT::Other);
1833
1834 // Note, we treat inline asms both with and without side-effects as the same.
1835 // If an inline asm doesn't have side effects and doesn't access memory, we
1836 // could not choose to not chain it.
1837 bool hasSideEffects = IA->hasSideEffects();
1838
Chris Lattner3a5ed552006-02-01 01:28:23 +00001839 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001840 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001841
1842 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1843 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1844 /// if it is a def of that register.
1845 std::vector<SDOperand> AsmNodeOperands;
1846 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1847 AsmNodeOperands.push_back(AsmStr);
1848
1849 SDOperand Chain = getRoot();
1850 SDOperand Flag;
1851
Chris Lattner1558fc62006-02-01 18:59:47 +00001852 // We fully assign registers here at isel time. This is not optimal, but
1853 // should work. For register classes that correspond to LLVM classes, we
1854 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1855 // over the constraints, collecting fixed registers that we know we can't use.
1856 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001857 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001858 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1859 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1860 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001861
Chris Lattner7ad77df2006-02-22 00:56:39 +00001862 MVT::ValueType OpVT;
1863
1864 // Compute the value type for each operand and add it to ConstraintVTs.
1865 switch (Constraints[i].Type) {
1866 case InlineAsm::isOutput:
1867 if (!Constraints[i].isIndirectOutput) {
1868 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1869 OpVT = TLI.getValueType(I.getType());
1870 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001871 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001872 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1873 OpNum++; // Consumes a call operand.
1874 }
1875 break;
1876 case InlineAsm::isInput:
1877 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1878 OpNum++; // Consumes a call operand.
1879 break;
1880 case InlineAsm::isClobber:
1881 OpVT = MVT::Other;
1882 break;
1883 }
1884
1885 ConstraintVTs.push_back(OpVT);
1886
Chris Lattner6f87d182006-02-22 22:37:12 +00001887 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1888 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001889
Chris Lattner6f87d182006-02-22 22:37:12 +00001890 // Build a list of regs that this operand uses. This always has a single
1891 // element for promoted/expanded operands.
1892 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1893 false, false,
1894 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001895
1896 switch (Constraints[i].Type) {
1897 case InlineAsm::isOutput:
1898 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001899 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001900 // If this is an early-clobber output, it cannot be assigned to the same
1901 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001902 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001903 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001904 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001905 case InlineAsm::isInput:
1906 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001907 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001908 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001909 case InlineAsm::isClobber:
1910 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001911 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1912 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001913 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001914 }
1915 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001916
Chris Lattner5c79f982006-02-21 23:12:12 +00001917 // Loop over all of the inputs, copying the operand values into the
1918 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001919 RegsForValue RetValRegs;
1920 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001921 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001922
Chris Lattner2e56e892006-01-31 02:03:41 +00001923 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001924 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1925 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001926
Chris Lattner3a5ed552006-02-01 01:28:23 +00001927 switch (Constraints[i].Type) {
1928 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001929 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1930 if (ConstraintCode.size() == 1) // not a physreg name.
1931 CTy = TLI.getConstraintType(ConstraintCode[0]);
1932
1933 if (CTy == TargetLowering::C_Memory) {
1934 // Memory output.
1935 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1936
1937 // Check that the operand (the address to store to) isn't a float.
1938 if (!MVT::isInteger(InOperandVal.getValueType()))
1939 assert(0 && "MATCH FAIL!");
1940
1941 if (!Constraints[i].isIndirectOutput)
1942 assert(0 && "MATCH FAIL!");
1943
1944 OpNum++; // Consumes a call operand.
1945
1946 // Extend/truncate to the right pointer type if needed.
1947 MVT::ValueType PtrType = TLI.getPointerTy();
1948 if (InOperandVal.getValueType() < PtrType)
1949 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1950 else if (InOperandVal.getValueType() > PtrType)
1951 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1952
1953 // Add information to the INLINEASM node to know about this output.
1954 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1955 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1956 AsmNodeOperands.push_back(InOperandVal);
1957 break;
1958 }
1959
1960 // Otherwise, this is a register output.
1961 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1962
Chris Lattner6f87d182006-02-22 22:37:12 +00001963 // If this is an early-clobber output, or if there is an input
1964 // constraint that matches this, we need to reserve the input register
1965 // so no other inputs allocate to it.
1966 bool UsesInputRegister = false;
1967 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1968 UsesInputRegister = true;
1969
1970 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001971 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001972 RegsForValue Regs =
1973 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1974 true, UsesInputRegister,
1975 OutputRegs, InputRegs);
1976 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001977
Chris Lattner3a5ed552006-02-01 01:28:23 +00001978 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001979 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001980 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001981 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001982 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001983 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001984 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1985 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001986 OpNum++; // Consumes a call operand.
1987 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001988
1989 // Add information to the INLINEASM node to know that this register is
1990 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001991 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001992 break;
1993 }
1994 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001995 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001996 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001997
Chris Lattner7f5880b2006-02-02 00:25:23 +00001998 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1999 // If this is required to match an output register we have already set,
2000 // just use its register.
2001 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002002
Chris Lattner571d9642006-02-23 19:21:04 +00002003 // Scan until we find the definition we already emitted of this operand.
2004 // When we find it, create a RegsForValue operand.
2005 unsigned CurOp = 2; // The first operand.
2006 for (; OperandNo; --OperandNo) {
2007 // Advance to the next operand.
2008 unsigned NumOps =
2009 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2010 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2011 "Skipped past definitions?");
2012 CurOp += (NumOps>>3)+1;
2013 }
2014
2015 unsigned NumOps =
2016 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2017 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2018 "Skipped past definitions?");
2019
2020 // Add NumOps>>3 registers to MatchedRegs.
2021 RegsForValue MatchedRegs;
2022 MatchedRegs.ValueVT = InOperandVal.getValueType();
2023 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2024 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2025 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2026 MatchedRegs.Regs.push_back(Reg);
2027 }
2028
2029 // Use the produced MatchedRegs object to
2030 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2031 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002032 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002033 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002034
2035 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2036 if (ConstraintCode.size() == 1) // not a physreg name.
2037 CTy = TLI.getConstraintType(ConstraintCode[0]);
2038
2039 if (CTy == TargetLowering::C_Other) {
2040 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2041 assert(0 && "MATCH FAIL!");
2042
2043 // Add information to the INLINEASM node to know about this input.
2044 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2045 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2046 AsmNodeOperands.push_back(InOperandVal);
2047 break;
2048 } else if (CTy == TargetLowering::C_Memory) {
2049 // Memory input.
2050
2051 // Check that the operand isn't a float.
2052 if (!MVT::isInteger(InOperandVal.getValueType()))
2053 assert(0 && "MATCH FAIL!");
2054
2055 // Extend/truncate to the right pointer type if needed.
2056 MVT::ValueType PtrType = TLI.getPointerTy();
2057 if (InOperandVal.getValueType() < PtrType)
2058 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2059 else if (InOperandVal.getValueType() > PtrType)
2060 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2061
2062 // Add information to the INLINEASM node to know about this input.
2063 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2064 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2065 AsmNodeOperands.push_back(InOperandVal);
2066 break;
2067 }
2068
2069 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2070
2071 // Copy the input into the appropriate registers.
2072 RegsForValue InRegs =
2073 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2074 false, true, OutputRegs, InputRegs);
2075 // FIXME: should be match fail.
2076 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2077
2078 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2079
2080 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002081 break;
2082 }
Chris Lattner571d9642006-02-23 19:21:04 +00002083 case InlineAsm::isClobber: {
2084 RegsForValue ClobberedRegs =
2085 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2086 OutputRegs, InputRegs);
2087 // Add the clobbered value to the operand list, so that the register
2088 // allocator is aware that the physreg got clobbered.
2089 if (!ClobberedRegs.Regs.empty())
2090 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002091 break;
2092 }
Chris Lattner571d9642006-02-23 19:21:04 +00002093 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002094 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002095
2096 // Finish up input operands.
2097 AsmNodeOperands[0] = Chain;
2098 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2099
2100 std::vector<MVT::ValueType> VTs;
2101 VTs.push_back(MVT::Other);
2102 VTs.push_back(MVT::Flag);
2103 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2104 Flag = Chain.getValue(1);
2105
Chris Lattner2e56e892006-01-31 02:03:41 +00002106 // If this asm returns a register value, copy the result from that register
2107 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002108 if (!RetValRegs.Regs.empty())
2109 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002110
Chris Lattner2e56e892006-01-31 02:03:41 +00002111 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2112
2113 // Process indirect outputs, first output all of the flagged copies out of
2114 // physregs.
2115 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002116 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002117 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002118 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2119 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002120 }
2121
2122 // Emit the non-flagged stores from the physregs.
2123 std::vector<SDOperand> OutChains;
2124 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2125 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2126 StoresToEmit[i].first,
2127 getValue(StoresToEmit[i].second),
2128 DAG.getSrcValue(StoresToEmit[i].second)));
2129 if (!OutChains.empty())
2130 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00002131 DAG.setRoot(Chain);
2132}
2133
2134
Chris Lattner7a60d912005-01-07 07:47:53 +00002135void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2136 SDOperand Src = getValue(I.getOperand(0));
2137
2138 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002139
2140 if (IntPtr < Src.getValueType())
2141 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2142 else if (IntPtr > Src.getValueType())
2143 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002144
2145 // Scale the source by the type size.
2146 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2147 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2148 Src, getIntPtrConstant(ElementSize));
2149
2150 std::vector<std::pair<SDOperand, const Type*> > Args;
2151 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002152
2153 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002154 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002155 DAG.getExternalSymbol("malloc", IntPtr),
2156 Args, DAG);
2157 setValue(&I, Result.first); // Pointers always fit in registers
2158 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002159}
2160
2161void SelectionDAGLowering::visitFree(FreeInst &I) {
2162 std::vector<std::pair<SDOperand, const Type*> > Args;
2163 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2164 TLI.getTargetData().getIntPtrType()));
2165 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002166 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002167 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002168 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2169 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002170}
2171
Chris Lattner13d7c252005-08-26 20:54:47 +00002172// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2173// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2174// instructions are special in various ways, which require special support to
2175// insert. The specified MachineInstr is created but not inserted into any
2176// basic blocks, and the scheduler passes ownership of it to this method.
2177MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2178 MachineBasicBlock *MBB) {
2179 std::cerr << "If a target marks an instruction with "
2180 "'usesCustomDAGSchedInserter', it must implement "
2181 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2182 abort();
2183 return 0;
2184}
2185
Chris Lattner58cfd792005-01-09 00:00:49 +00002186void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002187 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2188 getValue(I.getOperand(1)),
2189 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002190}
2191
2192void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002193 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2194 getValue(I.getOperand(0)),
2195 DAG.getSrcValue(I.getOperand(0)));
2196 setValue(&I, V);
2197 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002198}
2199
2200void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002201 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2202 getValue(I.getOperand(1)),
2203 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002204}
2205
2206void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002207 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2208 getValue(I.getOperand(1)),
2209 getValue(I.getOperand(2)),
2210 DAG.getSrcValue(I.getOperand(1)),
2211 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002212}
2213
Chris Lattner58cfd792005-01-09 00:00:49 +00002214// It is always conservatively correct for llvm.returnaddress and
2215// llvm.frameaddress to return 0.
2216std::pair<SDOperand, SDOperand>
2217TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2218 unsigned Depth, SelectionDAG &DAG) {
2219 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002220}
2221
Chris Lattner29dcc712005-05-14 05:50:48 +00002222SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002223 assert(0 && "LowerOperation not implemented for this target!");
2224 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002225 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002226}
2227
Nate Begeman595ec732006-01-28 03:14:31 +00002228SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2229 SelectionDAG &DAG) {
2230 assert(0 && "CustomPromoteOperation not implemented for this target!");
2231 abort();
2232 return SDOperand();
2233}
2234
Chris Lattner58cfd792005-01-09 00:00:49 +00002235void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2236 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2237 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002238 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002239 setValue(&I, Result.first);
2240 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002241}
2242
Evan Cheng6781b6e2006-02-15 21:59:04 +00002243/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002244/// operand.
2245static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002246 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002247 MVT::ValueType CurVT = VT;
2248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2249 uint64_t Val = C->getValue() & 255;
2250 unsigned Shift = 8;
2251 while (CurVT != MVT::i8) {
2252 Val = (Val << Shift) | Val;
2253 Shift <<= 1;
2254 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002255 }
2256 return DAG.getConstant(Val, VT);
2257 } else {
2258 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2259 unsigned Shift = 8;
2260 while (CurVT != MVT::i8) {
2261 Value =
2262 DAG.getNode(ISD::OR, VT,
2263 DAG.getNode(ISD::SHL, VT, Value,
2264 DAG.getConstant(Shift, MVT::i8)), Value);
2265 Shift <<= 1;
2266 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002267 }
2268
2269 return Value;
2270 }
2271}
2272
Evan Cheng6781b6e2006-02-15 21:59:04 +00002273/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2274/// used when a memcpy is turned into a memset when the source is a constant
2275/// string ptr.
2276static SDOperand getMemsetStringVal(MVT::ValueType VT,
2277 SelectionDAG &DAG, TargetLowering &TLI,
2278 std::string &Str, unsigned Offset) {
2279 MVT::ValueType CurVT = VT;
2280 uint64_t Val = 0;
2281 unsigned MSB = getSizeInBits(VT) / 8;
2282 if (TLI.isLittleEndian())
2283 Offset = Offset + MSB - 1;
2284 for (unsigned i = 0; i != MSB; ++i) {
2285 Val = (Val << 8) | Str[Offset];
2286 Offset += TLI.isLittleEndian() ? -1 : 1;
2287 }
2288 return DAG.getConstant(Val, VT);
2289}
2290
Evan Cheng81fcea82006-02-14 08:22:34 +00002291/// getMemBasePlusOffset - Returns base and offset node for the
2292static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2293 SelectionDAG &DAG, TargetLowering &TLI) {
2294 MVT::ValueType VT = Base.getValueType();
2295 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2296}
2297
Evan Chengdb2a7a72006-02-14 20:12:38 +00002298/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002299/// to replace the memset / memcpy is below the threshold. It also returns the
2300/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002301static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2302 unsigned Limit, uint64_t Size,
2303 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002304 MVT::ValueType VT;
2305
2306 if (TLI.allowsUnalignedMemoryAccesses()) {
2307 VT = MVT::i64;
2308 } else {
2309 switch (Align & 7) {
2310 case 0:
2311 VT = MVT::i64;
2312 break;
2313 case 4:
2314 VT = MVT::i32;
2315 break;
2316 case 2:
2317 VT = MVT::i16;
2318 break;
2319 default:
2320 VT = MVT::i8;
2321 break;
2322 }
2323 }
2324
Evan Chengd5026102006-02-14 09:11:59 +00002325 MVT::ValueType LVT = MVT::i64;
2326 while (!TLI.isTypeLegal(LVT))
2327 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2328 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002329
Evan Chengd5026102006-02-14 09:11:59 +00002330 if (VT > LVT)
2331 VT = LVT;
2332
Evan Cheng04514992006-02-14 23:05:54 +00002333 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002334 while (Size != 0) {
2335 unsigned VTSize = getSizeInBits(VT) / 8;
2336 while (VTSize > Size) {
2337 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002338 VTSize >>= 1;
2339 }
Evan Chengd5026102006-02-14 09:11:59 +00002340 assert(MVT::isInteger(VT));
2341
2342 if (++NumMemOps > Limit)
2343 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002344 MemOps.push_back(VT);
2345 Size -= VTSize;
2346 }
Evan Chengd5026102006-02-14 09:11:59 +00002347
2348 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002349}
2350
Chris Lattner875def92005-01-11 05:56:49 +00002351void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002352 SDOperand Op1 = getValue(I.getOperand(1));
2353 SDOperand Op2 = getValue(I.getOperand(2));
2354 SDOperand Op3 = getValue(I.getOperand(3));
2355 SDOperand Op4 = getValue(I.getOperand(4));
2356 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2357 if (Align == 0) Align = 1;
2358
2359 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2360 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002361
2362 // Expand memset / memcpy to a series of load / store ops
2363 // if the size operand falls below a certain threshold.
2364 std::vector<SDOperand> OutChains;
2365 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002366 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002367 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002368 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2369 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002370 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002371 unsigned Offset = 0;
2372 for (unsigned i = 0; i < NumMemOps; i++) {
2373 MVT::ValueType VT = MemOps[i];
2374 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002375 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002376 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2377 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002378 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2379 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002380 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002381 Offset += VTSize;
2382 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002383 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002384 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002385 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002386 case ISD::MEMCPY: {
2387 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2388 Size->getValue(), Align, TLI)) {
2389 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002390 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002391 GlobalAddressSDNode *G = NULL;
2392 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002393 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002394
2395 if (Op2.getOpcode() == ISD::GlobalAddress)
2396 G = cast<GlobalAddressSDNode>(Op2);
2397 else if (Op2.getOpcode() == ISD::ADD &&
2398 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2399 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2400 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002401 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002402 }
2403 if (G) {
2404 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002405 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002406 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002407 if (!Str.empty()) {
2408 CopyFromStr = true;
2409 SrcOff += SrcDelta;
2410 }
2411 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002412 }
2413
Evan Chenge2038bd2006-02-15 01:54:51 +00002414 for (unsigned i = 0; i < NumMemOps; i++) {
2415 MVT::ValueType VT = MemOps[i];
2416 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002417 SDOperand Value, Chain, Store;
2418
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002419 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002420 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2421 Chain = getRoot();
2422 Store =
2423 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2424 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2425 DAG.getSrcValue(I.getOperand(1), DstOff));
2426 } else {
2427 Value = DAG.getLoad(VT, getRoot(),
2428 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2429 DAG.getSrcValue(I.getOperand(2), SrcOff));
2430 Chain = Value.getValue(1);
2431 Store =
2432 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2433 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2434 DAG.getSrcValue(I.getOperand(1), DstOff));
2435 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002436 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002437 SrcOff += VTSize;
2438 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002439 }
2440 }
2441 break;
2442 }
2443 }
2444
2445 if (!OutChains.empty()) {
2446 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2447 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002448 }
2449 }
2450
Chris Lattner875def92005-01-11 05:56:49 +00002451 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002452 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002453 Ops.push_back(Op1);
2454 Ops.push_back(Op2);
2455 Ops.push_back(Op3);
2456 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002457 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002458}
2459
Chris Lattner875def92005-01-11 05:56:49 +00002460//===----------------------------------------------------------------------===//
2461// SelectionDAGISel code
2462//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002463
2464unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2465 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2466}
2467
Chris Lattnerc9950c12005-08-17 06:37:43 +00002468void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002469 // FIXME: we only modify the CFG to split critical edges. This
2470 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002471}
Chris Lattner7a60d912005-01-07 07:47:53 +00002472
Chris Lattner35397782005-12-05 07:10:48 +00002473
2474/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2475/// casting to the type of GEPI.
2476static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2477 Value *Ptr, Value *PtrOffset) {
2478 if (V) return V; // Already computed.
2479
2480 BasicBlock::iterator InsertPt;
2481 if (BB == GEPI->getParent()) {
2482 // If insert into the GEP's block, insert right after the GEP.
2483 InsertPt = GEPI;
2484 ++InsertPt;
2485 } else {
2486 // Otherwise, insert at the top of BB, after any PHI nodes
2487 InsertPt = BB->begin();
2488 while (isa<PHINode>(InsertPt)) ++InsertPt;
2489 }
2490
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002491 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2492 // BB so that there is only one value live across basic blocks (the cast
2493 // operand).
2494 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2495 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2496 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2497
Chris Lattner35397782005-12-05 07:10:48 +00002498 // Add the offset, cast it to the right type.
2499 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2500 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2501 return V = Ptr;
2502}
2503
2504
2505/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2506/// selection, we want to be a bit careful about some things. In particular, if
2507/// we have a GEP instruction that is used in a different block than it is
2508/// defined, the addressing expression of the GEP cannot be folded into loads or
2509/// stores that use it. In this case, decompose the GEP and move constant
2510/// indices into blocks that use it.
2511static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2512 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002513 // If this GEP is only used inside the block it is defined in, there is no
2514 // need to rewrite it.
2515 bool isUsedOutsideDefBB = false;
2516 BasicBlock *DefBB = GEPI->getParent();
2517 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2518 UI != E; ++UI) {
2519 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2520 isUsedOutsideDefBB = true;
2521 break;
2522 }
2523 }
2524 if (!isUsedOutsideDefBB) return;
2525
2526 // If this GEP has no non-zero constant indices, there is nothing we can do,
2527 // ignore it.
2528 bool hasConstantIndex = false;
2529 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2530 E = GEPI->op_end(); OI != E; ++OI) {
2531 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2532 if (CI->getRawValue()) {
2533 hasConstantIndex = true;
2534 break;
2535 }
2536 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002537 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2538 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002539
2540 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2541 // constant offset (which we now know is non-zero) and deal with it later.
2542 uint64_t ConstantOffset = 0;
2543 const Type *UIntPtrTy = TD.getIntPtrType();
2544 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2545 const Type *Ty = GEPI->getOperand(0)->getType();
2546
2547 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2548 E = GEPI->op_end(); OI != E; ++OI) {
2549 Value *Idx = *OI;
2550 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2551 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2552 if (Field)
2553 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2554 Ty = StTy->getElementType(Field);
2555 } else {
2556 Ty = cast<SequentialType>(Ty)->getElementType();
2557
2558 // Handle constant subscripts.
2559 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2560 if (CI->getRawValue() == 0) continue;
2561
2562 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2563 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2564 else
2565 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2566 continue;
2567 }
2568
2569 // Ptr = Ptr + Idx * ElementSize;
2570
2571 // Cast Idx to UIntPtrTy if needed.
2572 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2573
2574 uint64_t ElementSize = TD.getTypeSize(Ty);
2575 // Mask off bits that should not be set.
2576 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2577 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2578
2579 // Multiply by the element size and add to the base.
2580 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2581 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2582 }
2583 }
2584
2585 // Make sure that the offset fits in uintptr_t.
2586 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2587 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2588
2589 // Okay, we have now emitted all of the variable index parts to the BB that
2590 // the GEP is defined in. Loop over all of the using instructions, inserting
2591 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002592 // instruction to use the newly computed value, making GEPI dead. When the
2593 // user is a load or store instruction address, we emit the add into the user
2594 // block, otherwise we use a canonical version right next to the gep (these
2595 // won't be foldable as addresses, so we might as well share the computation).
2596
Chris Lattner35397782005-12-05 07:10:48 +00002597 std::map<BasicBlock*,Value*> InsertedExprs;
2598 while (!GEPI->use_empty()) {
2599 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002600
2601 // If this use is not foldable into the addressing mode, use a version
2602 // emitted in the GEP block.
2603 Value *NewVal;
2604 if (!isa<LoadInst>(User) &&
2605 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2606 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2607 Ptr, PtrOffset);
2608 } else {
2609 // Otherwise, insert the code in the User's block so it can be folded into
2610 // any users in that block.
2611 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002612 User->getParent(), GEPI,
2613 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002614 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002615 User->replaceUsesOfWith(GEPI, NewVal);
2616 }
Chris Lattner35397782005-12-05 07:10:48 +00002617
2618 // Finally, the GEP is dead, remove it.
2619 GEPI->eraseFromParent();
2620}
2621
Chris Lattner7a60d912005-01-07 07:47:53 +00002622bool SelectionDAGISel::runOnFunction(Function &Fn) {
2623 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2624 RegMap = MF.getSSARegMap();
2625 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2626
Chris Lattner35397782005-12-05 07:10:48 +00002627 // First, split all critical edges for PHI nodes with incoming values that are
2628 // constants, this way the load of the constant into a vreg will not be placed
2629 // into MBBs that are used some other way.
2630 //
2631 // In this pass we also look for GEP instructions that are used across basic
2632 // blocks and rewrites them to improve basic-block-at-a-time selection.
2633 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002634 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2635 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002636 BasicBlock::iterator BBI;
2637 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002638 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2639 if (isa<Constant>(PN->getIncomingValue(i)))
2640 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002641
2642 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2643 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2644 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002645 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002646
Chris Lattner7a60d912005-01-07 07:47:53 +00002647 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2648
2649 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2650 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002651
Chris Lattner7a60d912005-01-07 07:47:53 +00002652 return true;
2653}
2654
2655
Chris Lattner718b5c22005-01-13 17:59:43 +00002656SDOperand SelectionDAGISel::
2657CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002658 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002659 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002660 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002661 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002662
2663 // If this type is not legal, we must make sure to not create an invalid
2664 // register use.
2665 MVT::ValueType SrcVT = Op.getValueType();
2666 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2667 SelectionDAG &DAG = SDL.DAG;
2668 if (SrcVT == DestVT) {
2669 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002670 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00002671 // Handle copies from generic vectors to registers.
2672 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2673 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2674 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00002675
Chris Lattner5fe1f542006-03-31 02:06:56 +00002676 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2677 // MVT::Vector type.
2678 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2679 DAG.getConstant(NE, MVT::i32),
2680 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00002681
Chris Lattner5fe1f542006-03-31 02:06:56 +00002682 // Loop over all of the elements of the resultant vector,
2683 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2684 // copying them into output registers.
2685 std::vector<SDOperand> OutChains;
2686 SDOperand Root = SDL.getRoot();
2687 for (unsigned i = 0; i != NE; ++i) {
2688 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2689 Op, DAG.getConstant(i, MVT::i32));
2690 if (PTyElementVT == PTyLegalElementVT) {
2691 // Elements are legal.
2692 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2693 } else if (PTyLegalElementVT > PTyElementVT) {
2694 // Elements are promoted.
2695 if (MVT::isFloatingPoint(PTyLegalElementVT))
2696 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2697 else
2698 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2699 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2700 } else {
2701 // Elements are expanded.
2702 // The src value is expanded into multiple registers.
2703 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2704 Elt, DAG.getConstant(0, MVT::i32));
2705 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2706 Elt, DAG.getConstant(1, MVT::i32));
2707 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2708 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2709 }
Chris Lattner672a42d2006-03-21 19:20:37 +00002710 }
Chris Lattner5fe1f542006-03-31 02:06:56 +00002711 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner33182322005-08-16 21:55:35 +00002712 } else if (SrcVT < DestVT) {
2713 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002714 if (MVT::isFloatingPoint(SrcVT))
2715 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2716 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002717 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002718 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2719 } else {
2720 // The src value is expanded into multiple registers.
2721 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2722 Op, DAG.getConstant(0, MVT::i32));
2723 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2724 Op, DAG.getConstant(1, MVT::i32));
2725 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2726 return DAG.getCopyToReg(Op, Reg+1, Hi);
2727 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002728}
2729
Chris Lattner16f64df2005-01-17 17:15:02 +00002730void SelectionDAGISel::
2731LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2732 std::vector<SDOperand> &UnorderedChains) {
2733 // If this is the entry block, emit arguments.
2734 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002735 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002736 SDOperand OldRoot = SDL.DAG.getRoot();
2737 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002738
Chris Lattner6871b232005-10-30 19:42:35 +00002739 unsigned a = 0;
2740 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2741 AI != E; ++AI, ++a)
2742 if (!AI->use_empty()) {
2743 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002744
Chris Lattner6871b232005-10-30 19:42:35 +00002745 // If this argument is live outside of the entry block, insert a copy from
2746 // whereever we got it to the vreg that other BB's will reference it as.
2747 if (FuncInfo.ValueMap.count(AI)) {
2748 SDOperand Copy =
2749 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2750 UnorderedChains.push_back(Copy);
2751 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002752 }
Chris Lattner6871b232005-10-30 19:42:35 +00002753
2754 // Next, if the function has live ins that need to be copied into vregs,
2755 // emit the copies now, into the top of the block.
2756 MachineFunction &MF = SDL.DAG.getMachineFunction();
2757 if (MF.livein_begin() != MF.livein_end()) {
2758 SSARegMap *RegMap = MF.getSSARegMap();
2759 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2760 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2761 E = MF.livein_end(); LI != E; ++LI)
2762 if (LI->second)
2763 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2764 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002765 }
Chris Lattner6871b232005-10-30 19:42:35 +00002766
2767 // Finally, if the target has anything special to do, allow it to do so.
2768 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002769}
2770
2771
Chris Lattner7a60d912005-01-07 07:47:53 +00002772void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2773 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00002774 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00002775 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002776
2777 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002778
Chris Lattner6871b232005-10-30 19:42:35 +00002779 // Lower any arguments needed in this block if this is the entry block.
2780 if (LLVMBB == &LLVMBB->getParent()->front())
2781 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002782
2783 BB = FuncInfo.MBBMap[LLVMBB];
2784 SDL.setCurrentBasicBlock(BB);
2785
2786 // Lower all of the non-terminator instructions.
2787 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2788 I != E; ++I)
2789 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00002790
Chris Lattner7a60d912005-01-07 07:47:53 +00002791 // Ensure that all instructions which are used outside of their defining
2792 // blocks are available as virtual registers.
2793 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002794 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002795 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002796 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002797 UnorderedChains.push_back(
2798 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002799 }
2800
2801 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2802 // ensure constants are generated when needed. Remember the virtual registers
2803 // that need to be added to the Machine PHI nodes as input. We cannot just
2804 // directly add them, because expansion might result in multiple MBB's for one
2805 // BB. As such, the start of the BB might correspond to a different MBB than
2806 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002807 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002808
2809 // Emit constants only once even if used by multiple PHI nodes.
2810 std::map<Constant*, unsigned> ConstantsOut;
2811
2812 // Check successor nodes PHI nodes that expect a constant to be available from
2813 // this block.
2814 TerminatorInst *TI = LLVMBB->getTerminator();
2815 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2816 BasicBlock *SuccBB = TI->getSuccessor(succ);
2817 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2818 PHINode *PN;
2819
2820 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2821 // nodes and Machine PHI nodes, but the incoming operands have not been
2822 // emitted yet.
2823 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002824 (PN = dyn_cast<PHINode>(I)); ++I)
2825 if (!PN->use_empty()) {
2826 unsigned Reg;
2827 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2828 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2829 unsigned &RegOut = ConstantsOut[C];
2830 if (RegOut == 0) {
2831 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002832 UnorderedChains.push_back(
2833 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002834 }
2835 Reg = RegOut;
2836 } else {
2837 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002838 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002839 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002840 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2841 "Didn't codegen value into a register!??");
2842 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002843 UnorderedChains.push_back(
2844 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002845 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002846 }
Misha Brukman835702a2005-04-21 22:36:52 +00002847
Chris Lattner8ea875f2005-01-07 21:34:19 +00002848 // Remember that this register needs to added to the machine PHI node as
2849 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00002850 MVT::ValueType VT = TLI.getValueType(PN->getType());
2851 unsigned NumElements;
2852 if (VT != MVT::Vector)
2853 NumElements = TLI.getNumElements(VT);
2854 else {
2855 MVT::ValueType VT1,VT2;
2856 NumElements =
2857 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
2858 VT1, VT2);
2859 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00002860 for (unsigned i = 0, e = NumElements; i != e; ++i)
2861 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002862 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002863 }
2864 ConstantsOut.clear();
2865
Chris Lattner718b5c22005-01-13 17:59:43 +00002866 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002867 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002868 SDOperand Root = SDL.getRoot();
2869 if (Root.getOpcode() != ISD::EntryToken) {
2870 unsigned i = 0, e = UnorderedChains.size();
2871 for (; i != e; ++i) {
2872 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2873 if (UnorderedChains[i].Val->getOperand(0) == Root)
2874 break; // Don't add the root if we already indirectly depend on it.
2875 }
2876
2877 if (i == e)
2878 UnorderedChains.push_back(Root);
2879 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002880 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2881 }
2882
Chris Lattner7a60d912005-01-07 07:47:53 +00002883 // Lower the terminator after the copies are emitted.
2884 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002885
Nate Begemaned728c12006-03-27 01:32:24 +00002886 // Copy over any CaseBlock records that may now exist due to SwitchInst
2887 // lowering.
2888 SwitchCases.clear();
2889 SwitchCases = SDL.SwitchCases;
2890
Chris Lattner4108bb02005-01-17 19:43:36 +00002891 // Make sure the root of the DAG is up-to-date.
2892 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002893}
2894
Nate Begemaned728c12006-03-27 01:32:24 +00002895void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002896 // Run the DAG combiner in pre-legalize mode.
2897 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002898
Chris Lattner7a60d912005-01-07 07:47:53 +00002899 DEBUG(std::cerr << "Lowered selection DAG:\n");
2900 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002901
Chris Lattner7a60d912005-01-07 07:47:53 +00002902 // Second step, hack on the DAG until it only uses operations and types that
2903 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002904 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00002905
Chris Lattner7a60d912005-01-07 07:47:53 +00002906 DEBUG(std::cerr << "Legalized selection DAG:\n");
2907 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002908
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002909 // Run the DAG combiner in post-legalize mode.
2910 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002911
Evan Cheng739a6a42006-01-21 02:32:06 +00002912 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002913
Chris Lattner5ca31d92005-03-30 01:10:47 +00002914 // Third, instruction select all of the operations to machine code, adding the
2915 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002916 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00002917
Chris Lattner7a60d912005-01-07 07:47:53 +00002918 DEBUG(std::cerr << "Selected machine code:\n");
2919 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00002920}
Chris Lattner7a60d912005-01-07 07:47:53 +00002921
Nate Begemaned728c12006-03-27 01:32:24 +00002922void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2923 FunctionLoweringInfo &FuncInfo) {
2924 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2925 {
2926 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2927 CurDAG = &DAG;
2928
2929 // First step, lower LLVM code to some DAG. This DAG may use operations and
2930 // types that are not supported by the target.
2931 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2932
2933 // Second step, emit the lowered DAG as machine code.
2934 CodeGenAndEmitDAG(DAG);
2935 }
2936
Chris Lattner5ca31d92005-03-30 01:10:47 +00002937 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002938 // PHI nodes in successors.
Nate Begemaned728c12006-03-27 01:32:24 +00002939 if (SwitchCases.empty()) {
2940 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2941 MachineInstr *PHI = PHINodesToUpdate[i].first;
2942 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2943 "This is not a machine PHI node that we are updating!");
2944 PHI->addRegOperand(PHINodesToUpdate[i].second);
2945 PHI->addMachineBasicBlockOperand(BB);
2946 }
2947 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002948 }
Nate Begemaned728c12006-03-27 01:32:24 +00002949
2950 // If we generated any switch lowering information, build and codegen any
2951 // additional DAGs necessary.
2952 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2953 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2954 CurDAG = &SDAG;
2955 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2956 // Set the current basic block to the mbb we wish to insert the code into
2957 BB = SwitchCases[i].ThisBB;
2958 SDL.setCurrentBasicBlock(BB);
2959 // Emit the code
2960 SDL.visitSwitchCase(SwitchCases[i]);
2961 SDAG.setRoot(SDL.getRoot());
2962 CodeGenAndEmitDAG(SDAG);
2963 // Iterate over the phi nodes, if there is a phi node in a successor of this
2964 // block (for instance, the default block), then add a pair of operands to
2965 // the phi node for this block, as if we were coming from the original
2966 // BB before switch expansion.
2967 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2968 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2969 MachineBasicBlock *PHIBB = PHI->getParent();
2970 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2971 "This is not a machine PHI node that we are updating!");
2972 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2973 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2974 PHI->addMachineBasicBlockOperand(BB);
2975 }
2976 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002977 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002978}
Evan Cheng739a6a42006-01-21 02:32:06 +00002979
2980//===----------------------------------------------------------------------===//
2981/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2982/// target node in the graph.
2983void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2984 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002985 ScheduleDAG *SL = NULL;
2986
2987 switch (ISHeuristic) {
2988 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002989 case defaultScheduling:
2990 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2991 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2992 else /* TargetLowering::SchedulingForRegPressure */
2993 SL = createBURRListDAGScheduler(DAG, BB);
2994 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002995 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002996 SL = createBFS_DAGScheduler(DAG, BB);
2997 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002998 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002999 SL = createSimpleDAGScheduler(false, DAG, BB);
3000 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003001 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00003002 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00003003 break;
Evan Cheng31272342006-01-23 08:26:10 +00003004 case listSchedulingBURR:
3005 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00003006 break;
Chris Lattner47639db2006-03-06 00:22:00 +00003007 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00003008 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00003009 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003010 }
Chris Lattnere23928c2006-01-21 19:12:11 +00003011 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003012 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003013}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003014
Chris Lattner543832d2006-03-08 04:25:59 +00003015HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3016 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00003017}
3018
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003019/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3020/// by tblgen. Others should not call it.
3021void SelectionDAGISel::
3022SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3023 std::vector<SDOperand> InOps;
3024 std::swap(InOps, Ops);
3025
3026 Ops.push_back(InOps[0]); // input chain.
3027 Ops.push_back(InOps[1]); // input asm string.
3028
3029 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
3030 unsigned i = 2, e = InOps.size();
3031 if (InOps[e-1].getValueType() == MVT::Flag)
3032 --e; // Don't process a flag operand if it is here.
3033
3034 while (i != e) {
3035 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3036 if ((Flags & 7) != 4 /*MEM*/) {
3037 // Just skip over this operand, copying the operands verbatim.
3038 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3039 i += (Flags >> 3) + 1;
3040 } else {
3041 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3042 // Otherwise, this is a memory operand. Ask the target to select it.
3043 std::vector<SDOperand> SelOps;
3044 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3045 std::cerr << "Could not match memory address. Inline asm failure!\n";
3046 exit(1);
3047 }
3048
3049 // Add this to the output node.
3050 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3051 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3052 i += 2;
3053 }
3054 }
3055
3056 // Add the flag input back if present.
3057 if (e != InOps.size())
3058 Ops.push_back(InOps.back());
3059}