blob: 96a81e0938340be41ee9ab33c0feeaa8adba7d0e [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 Lattner098c01e2006-04-08 04:15:24 +0000519 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000520
Chris Lattner7a60d912005-01-07 07:47:53 +0000521 void visitGetElementPtr(User &I);
522 void visitCast(User &I);
523 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000524
525 void visitMalloc(MallocInst &I);
526 void visitFree(FreeInst &I);
527 void visitAlloca(AllocaInst &I);
528 void visitLoad(LoadInst &I);
529 void visitStore(StoreInst &I);
530 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
531 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000532 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000533 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000534 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000535
Chris Lattner7a60d912005-01-07 07:47:53 +0000536 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000537 void visitVAArg(VAArgInst &I);
538 void visitVAEnd(CallInst &I);
539 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000540 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000541
Chris Lattner875def92005-01-11 05:56:49 +0000542 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
544 void visitUserOp1(Instruction &I) {
545 assert(0 && "UserOp1 should not exist at instruction selection time!");
546 abort();
547 }
548 void visitUserOp2(Instruction &I) {
549 assert(0 && "UserOp2 should not exist at instruction selection time!");
550 abort();
551 }
552};
553} // end namespace llvm
554
Chris Lattner8471b152006-03-16 19:57:50 +0000555SDOperand SelectionDAGLowering::getValue(const Value *V) {
556 SDOperand &N = NodeMap[V];
557 if (N.Val) return N;
558
559 const Type *VTy = V->getType();
560 MVT::ValueType VT = TLI.getValueType(VTy);
561 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
562 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
563 visit(CE->getOpcode(), *CE);
564 assert(N.Val && "visit didn't populate the ValueMap!");
565 return N;
566 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
567 return N = DAG.getGlobalAddress(GV, VT);
568 } else if (isa<ConstantPointerNull>(C)) {
569 return N = DAG.getConstant(0, TLI.getPointerTy());
570 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000571 if (!isa<PackedType>(VTy))
572 return N = DAG.getNode(ISD::UNDEF, VT);
573
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000574 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000575 const PackedType *PTy = cast<PackedType>(VTy);
576 unsigned NumElements = PTy->getNumElements();
577 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
578
579 std::vector<SDOperand> Ops;
580 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
581
582 // Create a VConstant node with generic Vector type.
583 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
584 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000585 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000586 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
587 return N = DAG.getConstantFP(CFP->getValue(), VT);
588 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
589 unsigned NumElements = PTy->getNumElements();
590 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000591
592 // Now that we know the number and type of the elements, push a
593 // Constant or ConstantFP node onto the ops list for each element of
594 // the packed constant.
595 std::vector<SDOperand> Ops;
596 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000597 for (unsigned i = 0; i != NumElements; ++i)
598 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000599 } else {
600 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
601 SDOperand Op;
602 if (MVT::isFloatingPoint(PVT))
603 Op = DAG.getConstantFP(0, PVT);
604 else
605 Op = DAG.getConstant(0, PVT);
606 Ops.assign(NumElements, Op);
607 }
608
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000609 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000613 } else {
614 // Canonicalize all constant ints to be unsigned.
615 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
616 }
617 }
618
619 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
620 std::map<const AllocaInst*, int>::iterator SI =
621 FuncInfo.StaticAllocaMap.find(AI);
622 if (SI != FuncInfo.StaticAllocaMap.end())
623 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
624 }
625
626 std::map<const Value*, unsigned>::const_iterator VMI =
627 FuncInfo.ValueMap.find(V);
628 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
629
630 unsigned InReg = VMI->second;
631
632 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000633 if (VT != MVT::Vector) {
634 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000635
Chris Lattner5fe1f542006-03-31 02:06:56 +0000636 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
637 if (DestVT < VT) {
638 // Source must be expanded. This input value is actually coming from the
639 // register pair VMI->second and VMI->second+1.
640 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
641 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
642 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000643 if (MVT::isFloatingPoint(VT))
644 N = DAG.getNode(ISD::FP_ROUND, VT, N);
645 else
646 N = DAG.getNode(ISD::TRUNCATE, VT, N);
647 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000648 } else {
649 // Otherwise, if this is a vector, make it available as a generic vector
650 // here.
651 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000652 const PackedType *PTy = cast<PackedType>(VTy);
653 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000654 PTyLegalElementVT);
655
656 // Build a VBUILD_VECTOR with the input registers.
657 std::vector<SDOperand> Ops;
658 if (PTyElementVT == PTyLegalElementVT) {
659 // If the value types are legal, just VBUILD the CopyFromReg nodes.
660 for (unsigned i = 0; i != NE; ++i)
661 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
662 PTyElementVT));
663 } else if (PTyElementVT < PTyLegalElementVT) {
664 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
665 for (unsigned i = 0; i != NE; ++i) {
666 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
667 PTyElementVT);
668 if (MVT::isFloatingPoint(PTyElementVT))
669 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
670 else
671 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
672 Ops.push_back(Op);
673 }
674 } else {
675 // If the register was expanded, use BUILD_PAIR.
676 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
677 for (unsigned i = 0; i != NE/2; ++i) {
678 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
679 PTyElementVT);
680 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
681 PTyElementVT);
682 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
683 }
684 }
685
686 Ops.push_back(DAG.getConstant(NE, MVT::i32));
687 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
688 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner4a2413a2006-04-05 06:54:42 +0000689
690 // Finally, use a VBIT_CONVERT to make this available as the appropriate
691 // vector type.
692 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
693 DAG.getConstant(PTy->getNumElements(),
694 MVT::i32),
695 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000696 }
697
698 return N;
699}
700
701
Chris Lattner7a60d912005-01-07 07:47:53 +0000702void SelectionDAGLowering::visitRet(ReturnInst &I) {
703 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000704 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000705 return;
706 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000707 std::vector<SDOperand> NewValues;
708 NewValues.push_back(getRoot());
709 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
710 SDOperand RetOp = getValue(I.getOperand(i));
711
712 // If this is an integer return value, we need to promote it ourselves to
713 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
714 // than sign/zero.
715 if (MVT::isInteger(RetOp.getValueType()) &&
716 RetOp.getValueType() < MVT::i64) {
717 MVT::ValueType TmpVT;
718 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
719 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
720 else
721 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000722
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000723 if (I.getOperand(i)->getType()->isSigned())
724 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
725 else
726 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
727 }
728 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000729 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000730 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000731}
732
733void SelectionDAGLowering::visitBr(BranchInst &I) {
734 // Update machine-CFG edges.
735 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000736 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000737
738 // Figure out which block is immediately after the current one.
739 MachineBasicBlock *NextBlock = 0;
740 MachineFunction::iterator BBI = CurMBB;
741 if (++BBI != CurMBB->getParent()->end())
742 NextBlock = BBI;
743
744 if (I.isUnconditional()) {
745 // If this is not a fall-through branch, emit the branch.
746 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000747 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000748 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000749 } else {
750 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000751 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000752
753 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000754 if (Succ1MBB == NextBlock) {
755 // If the condition is false, fall through. This means we should branch
756 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000757 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000758 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000759 } else if (Succ0MBB == NextBlock) {
760 // If the condition is true, fall through. This means we should branch if
761 // the condition is false to Succ #1. Invert the condition first.
762 SDOperand True = DAG.getConstant(1, Cond.getValueType());
763 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000764 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000765 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000766 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000767 std::vector<SDOperand> Ops;
768 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000769 // If the false case is the current basic block, then this is a self
770 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
771 // adds an extra instruction in the loop. Instead, invert the
772 // condition and emit "Loop: ... br!cond Loop; br Out.
773 if (CurMBB == Succ1MBB) {
774 std::swap(Succ0MBB, Succ1MBB);
775 SDOperand True = DAG.getConstant(1, Cond.getValueType());
776 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
777 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000778 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
779 DAG.getBasicBlock(Succ0MBB));
780 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
781 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 }
783 }
784}
785
Nate Begemaned728c12006-03-27 01:32:24 +0000786/// visitSwitchCase - Emits the necessary code to represent a single node in
787/// the binary search tree resulting from lowering a switch instruction.
788void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
789 SDOperand SwitchOp = getValue(CB.SwitchV);
790 SDOperand CaseOp = getValue(CB.CaseC);
791 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
792
793 // Set NextBlock to be the MBB immediately after the current one, if any.
794 // This is used to avoid emitting unnecessary branches to the next block.
795 MachineBasicBlock *NextBlock = 0;
796 MachineFunction::iterator BBI = CurMBB;
797 if (++BBI != CurMBB->getParent()->end())
798 NextBlock = BBI;
799
800 // If the lhs block is the next block, invert the condition so that we can
801 // fall through to the lhs instead of the rhs block.
802 if (CB.LHSBB == NextBlock) {
803 std::swap(CB.LHSBB, CB.RHSBB);
804 SDOperand True = DAG.getConstant(1, Cond.getValueType());
805 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
806 }
807 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
808 DAG.getBasicBlock(CB.LHSBB));
809 if (CB.RHSBB == NextBlock)
810 DAG.setRoot(BrCond);
811 else
812 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
813 DAG.getBasicBlock(CB.RHSBB)));
814 // Update successor info
815 CurMBB->addSuccessor(CB.LHSBB);
816 CurMBB->addSuccessor(CB.RHSBB);
817}
818
819void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
820 // Figure out which block is immediately after the current one.
821 MachineBasicBlock *NextBlock = 0;
822 MachineFunction::iterator BBI = CurMBB;
823 if (++BBI != CurMBB->getParent()->end())
824 NextBlock = BBI;
825
826 // If there is only the default destination, branch to it if it is not the
827 // next basic block. Otherwise, just fall through.
828 if (I.getNumOperands() == 2) {
829 // Update machine-CFG edges.
830 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
831 // If this is not a fall-through branch, emit the branch.
832 if (DefaultMBB != NextBlock)
833 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
834 DAG.getBasicBlock(DefaultMBB)));
835 return;
836 }
837
838 // If there are any non-default case statements, create a vector of Cases
839 // representing each one, and sort the vector so that we can efficiently
840 // create a binary search tree from them.
841 std::vector<Case> Cases;
842 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
843 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
844 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
845 }
846 std::sort(Cases.begin(), Cases.end(), CaseCmp());
847
848 // Get the Value to be switched on and default basic blocks, which will be
849 // inserted into CaseBlock records, representing basic blocks in the binary
850 // search tree.
851 Value *SV = I.getOperand(0);
852 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
853
854 // Get the current MachineFunction and LLVM basic block, for use in creating
855 // and inserting new MBBs during the creation of the binary search tree.
856 MachineFunction *CurMF = CurMBB->getParent();
857 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
858
859 // Push the initial CaseRec onto the worklist
860 std::vector<CaseRec> CaseVec;
861 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
862
863 while (!CaseVec.empty()) {
864 // Grab a record representing a case range to process off the worklist
865 CaseRec CR = CaseVec.back();
866 CaseVec.pop_back();
867
868 // Size is the number of Cases represented by this range. If Size is 1,
869 // then we are processing a leaf of the binary search tree. Otherwise,
870 // we need to pick a pivot, and push left and right ranges onto the
871 // worklist.
872 unsigned Size = CR.Range.second - CR.Range.first;
873
874 if (Size == 1) {
875 // Create a CaseBlock record representing a conditional branch to
876 // the Case's target mbb if the value being switched on SV is equal
877 // to C. Otherwise, branch to default.
878 Constant *C = CR.Range.first->first;
879 MachineBasicBlock *Target = CR.Range.first->second;
880 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
881 CR.CaseBB);
882 // If the MBB representing the leaf node is the current MBB, then just
883 // call visitSwitchCase to emit the code into the current block.
884 // Otherwise, push the CaseBlock onto the vector to be later processed
885 // by SDISel, and insert the node's MBB before the next MBB.
886 if (CR.CaseBB == CurMBB)
887 visitSwitchCase(CB);
888 else {
889 SwitchCases.push_back(CB);
890 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
891 }
892 } else {
893 // split case range at pivot
894 CaseItr Pivot = CR.Range.first + (Size / 2);
895 CaseRange LHSR(CR.Range.first, Pivot);
896 CaseRange RHSR(Pivot, CR.Range.second);
897 Constant *C = Pivot->first;
898 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
899 // We know that we branch to the LHS if the Value being switched on is
900 // less than the Pivot value, C. We use this to optimize our binary
901 // tree a bit, by recognizing that if SV is greater than or equal to the
902 // LHS's Case Value, and that Case Value is exactly one less than the
903 // Pivot's Value, then we can branch directly to the LHS's Target,
904 // rather than creating a leaf node for it.
905 if ((LHSR.second - LHSR.first) == 1 &&
906 LHSR.first->first == CR.GE &&
907 cast<ConstantIntegral>(C)->getRawValue() ==
908 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
909 LHSBB = LHSR.first->second;
910 } else {
911 LHSBB = new MachineBasicBlock(LLVMBB);
912 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
913 }
914 // Similar to the optimization above, if the Value being switched on is
915 // known to be less than the Constant CR.LT, and the current Case Value
916 // is CR.LT - 1, then we can branch directly to the target block for
917 // the current Case Value, rather than emitting a RHS leaf node for it.
918 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
919 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
920 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
921 RHSBB = RHSR.first->second;
922 } else {
923 RHSBB = new MachineBasicBlock(LLVMBB);
924 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
925 }
926 // Create a CaseBlock record representing a conditional branch to
927 // the LHS node if the value being switched on SV is less than C.
928 // Otherwise, branch to LHS.
929 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
930 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
931 if (CR.CaseBB == CurMBB)
932 visitSwitchCase(CB);
933 else {
934 SwitchCases.push_back(CB);
935 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
936 }
937 }
938 }
939}
940
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000941void SelectionDAGLowering::visitSub(User &I) {
942 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000943 if (I.getType()->isFloatingPoint()) {
944 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
945 if (CFP->isExactlyValue(-0.0)) {
946 SDOperand Op2 = getValue(I.getOperand(1));
947 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
948 return;
949 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000950 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000951 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000952}
953
Nate Begemanb2e089c2005-11-19 00:36:38 +0000954void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
955 unsigned VecOp) {
956 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000957 SDOperand Op1 = getValue(I.getOperand(0));
958 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000959
Chris Lattner19baba62005-11-19 18:40:42 +0000960 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000961 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
962 } else if (Ty->isFloatingPoint()) {
963 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
964 } else {
965 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000966 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
967 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
968 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000969 }
Nate Begeman127321b2005-11-18 07:42:56 +0000970}
Chris Lattner96c26752005-01-19 22:31:21 +0000971
Nate Begeman127321b2005-11-18 07:42:56 +0000972void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
973 SDOperand Op1 = getValue(I.getOperand(0));
974 SDOperand Op2 = getValue(I.getOperand(1));
975
976 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
977
Chris Lattner7a60d912005-01-07 07:47:53 +0000978 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
979}
980
981void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
982 ISD::CondCode UnsignedOpcode) {
983 SDOperand Op1 = getValue(I.getOperand(0));
984 SDOperand Op2 = getValue(I.getOperand(1));
985 ISD::CondCode Opcode = SignedOpcode;
986 if (I.getOperand(0)->getType()->isUnsigned())
987 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000988 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000989}
990
991void SelectionDAGLowering::visitSelect(User &I) {
992 SDOperand Cond = getValue(I.getOperand(0));
993 SDOperand TrueVal = getValue(I.getOperand(1));
994 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +0000995 if (!isa<PackedType>(I.getType())) {
996 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
997 TrueVal, FalseVal));
998 } else {
999 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1000 *(TrueVal.Val->op_end()-2),
1001 *(TrueVal.Val->op_end()-1)));
1002 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001003}
1004
1005void SelectionDAGLowering::visitCast(User &I) {
1006 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001007 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001008 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001009
Chris Lattner2f4119a2006-03-22 20:09:35 +00001010 if (DestVT == MVT::Vector) {
1011 // This is a cast to a vector from something else. This is always a bit
1012 // convert. Get information about the input vector.
1013 const PackedType *DestTy = cast<PackedType>(I.getType());
1014 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1015 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1016 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1017 DAG.getValueType(EltVT)));
1018 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001019 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001020 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001021 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001022 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001023 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001024 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001025 } else if (isInteger(SrcVT)) {
1026 if (isInteger(DestVT)) { // Int -> Int cast
1027 if (DestVT < SrcVT) // Truncating cast?
1028 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001029 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001030 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001031 else
Chris Lattner4024c002006-03-15 22:19:46 +00001032 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001033 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001034 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001035 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001036 else
Chris Lattner4024c002006-03-15 22:19:46 +00001037 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001038 } else {
1039 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001040 }
Chris Lattner4024c002006-03-15 22:19:46 +00001041 } else if (isFloatingPoint(SrcVT)) {
1042 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1043 if (DestVT < SrcVT) // Rounding cast?
1044 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001045 else
Chris Lattner4024c002006-03-15 22:19:46 +00001046 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001047 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001048 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001049 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001050 else
Chris Lattner4024c002006-03-15 22:19:46 +00001051 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001052 } else {
1053 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001054 }
1055 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001056 assert(SrcVT == MVT::Vector && "Unknown cast!");
1057 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1058 // This is a cast from a vector to something else. This is always a bit
1059 // convert. Get information about the input vector.
1060 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001061 }
1062}
1063
Chris Lattner67271862006-03-29 00:11:43 +00001064void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001065 SDOperand InVec = getValue(I.getOperand(0));
1066 SDOperand InVal = getValue(I.getOperand(1));
1067 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1068 getValue(I.getOperand(2)));
1069
Chris Lattner29b23012006-03-19 01:17:20 +00001070 SDOperand Num = *(InVec.Val->op_end()-2);
1071 SDOperand Typ = *(InVec.Val->op_end()-1);
1072 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1073 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001074}
1075
Chris Lattner67271862006-03-29 00:11:43 +00001076void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001077 SDOperand InVec = getValue(I.getOperand(0));
1078 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1079 getValue(I.getOperand(1)));
1080 SDOperand Typ = *(InVec.Val->op_end()-1);
1081 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1082 TLI.getValueType(I.getType()), InVec, InIdx));
1083}
Chris Lattner32206f52006-03-18 01:44:44 +00001084
Chris Lattner098c01e2006-04-08 04:15:24 +00001085void SelectionDAGLowering::visitShuffleVector(User &I) {
1086 SDOperand V1 = getValue(I.getOperand(0));
1087 SDOperand V2 = getValue(I.getOperand(1));
1088 SDOperand Mask = getValue(I.getOperand(2));
1089
1090 SDOperand Num = *(V1.Val->op_end()-2);
1091 SDOperand Typ = *(V2.Val->op_end()-1);
1092 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1093 V1, V2, Mask, Num, Typ));
1094}
1095
1096
Chris Lattner7a60d912005-01-07 07:47:53 +00001097void SelectionDAGLowering::visitGetElementPtr(User &I) {
1098 SDOperand N = getValue(I.getOperand(0));
1099 const Type *Ty = I.getOperand(0)->getType();
1100 const Type *UIntPtrTy = TD.getIntPtrType();
1101
1102 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1103 OI != E; ++OI) {
1104 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001105 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001106 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1107 if (Field) {
1108 // N = N + Offset
1109 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1110 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001111 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001112 }
1113 Ty = StTy->getElementType(Field);
1114 } else {
1115 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001116
Chris Lattner43535a12005-11-09 04:45:33 +00001117 // If this is a constant subscript, handle it quickly.
1118 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1119 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001120
Chris Lattner43535a12005-11-09 04:45:33 +00001121 uint64_t Offs;
1122 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1123 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1124 else
1125 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1126 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1127 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001128 }
Chris Lattner43535a12005-11-09 04:45:33 +00001129
1130 // N = N + Idx * ElementSize;
1131 uint64_t ElementSize = TD.getTypeSize(Ty);
1132 SDOperand IdxN = getValue(Idx);
1133
1134 // If the index is smaller or larger than intptr_t, truncate or extend
1135 // it.
1136 if (IdxN.getValueType() < N.getValueType()) {
1137 if (Idx->getType()->isSigned())
1138 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1139 else
1140 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1141 } else if (IdxN.getValueType() > N.getValueType())
1142 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1143
1144 // If this is a multiply by a power of two, turn it into a shl
1145 // immediately. This is a very common case.
1146 if (isPowerOf2_64(ElementSize)) {
1147 unsigned Amt = Log2_64(ElementSize);
1148 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001149 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001150 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1151 continue;
1152 }
1153
1154 SDOperand Scale = getIntPtrConstant(ElementSize);
1155 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1156 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001157 }
1158 }
1159 setValue(&I, N);
1160}
1161
1162void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1163 // If this is a fixed sized alloca in the entry block of the function,
1164 // allocate it statically on the stack.
1165 if (FuncInfo.StaticAllocaMap.count(&I))
1166 return; // getValue will auto-populate this.
1167
1168 const Type *Ty = I.getAllocatedType();
1169 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +00001170 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1171 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001172
1173 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001174 MVT::ValueType IntPtr = TLI.getPointerTy();
1175 if (IntPtr < AllocSize.getValueType())
1176 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1177 else if (IntPtr > AllocSize.getValueType())
1178 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001179
Chris Lattnereccb73d2005-01-22 23:04:37 +00001180 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001181 getIntPtrConstant(TySize));
1182
1183 // Handle alignment. If the requested alignment is less than or equal to the
1184 // stack alignment, ignore it and round the size of the allocation up to the
1185 // stack alignment size. If the size is greater than the stack alignment, we
1186 // note this in the DYNAMIC_STACKALLOC node.
1187 unsigned StackAlign =
1188 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1189 if (Align <= StackAlign) {
1190 Align = 0;
1191 // Add SA-1 to the size.
1192 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1193 getIntPtrConstant(StackAlign-1));
1194 // Mask out the low bits for alignment purposes.
1195 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1196 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1197 }
1198
Chris Lattner96c262e2005-05-14 07:29:57 +00001199 std::vector<MVT::ValueType> VTs;
1200 VTs.push_back(AllocSize.getValueType());
1201 VTs.push_back(MVT::Other);
1202 std::vector<SDOperand> Ops;
1203 Ops.push_back(getRoot());
1204 Ops.push_back(AllocSize);
1205 Ops.push_back(getIntPtrConstant(Align));
1206 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +00001207 DAG.setRoot(setValue(&I, DSA).getValue(1));
1208
1209 // Inform the Frame Information that we have just allocated a variable-sized
1210 // object.
1211 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1212}
1213
Chris Lattner7a60d912005-01-07 07:47:53 +00001214void SelectionDAGLowering::visitLoad(LoadInst &I) {
1215 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001216
Chris Lattner4d9651c2005-01-17 22:19:26 +00001217 SDOperand Root;
1218 if (I.isVolatile())
1219 Root = getRoot();
1220 else {
1221 // Do not serialize non-volatile loads against each other.
1222 Root = DAG.getRoot();
1223 }
Chris Lattner4024c002006-03-15 22:19:46 +00001224
1225 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1226 Root, I.isVolatile()));
1227}
1228
1229SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1230 SDOperand SrcValue, SDOperand Root,
1231 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001232 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001233 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001234 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001235 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001236 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001237 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001238 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001239
Chris Lattner4024c002006-03-15 22:19:46 +00001240 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001241 DAG.setRoot(L.getValue(1));
1242 else
1243 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001244
1245 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001246}
1247
1248
1249void SelectionDAGLowering::visitStore(StoreInst &I) {
1250 Value *SrcV = I.getOperand(0);
1251 SDOperand Src = getValue(SrcV);
1252 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001253 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001254 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001255}
1256
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001257/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1258/// access memory and has no other side effects at all.
1259static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1260#define GET_NO_MEMORY_INTRINSICS
1261#include "llvm/Intrinsics.gen"
1262#undef GET_NO_MEMORY_INTRINSICS
1263 return false;
1264}
1265
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001266// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1267// have any side-effects or if it only reads memory.
1268static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1269#define GET_SIDE_EFFECT_INFO
1270#include "llvm/Intrinsics.gen"
1271#undef GET_SIDE_EFFECT_INFO
1272 return false;
1273}
1274
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001275/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1276/// node.
1277void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1278 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001279 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001280 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001281
1282 // Build the operand list.
1283 std::vector<SDOperand> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001284 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1285 if (OnlyLoad) {
1286 // We don't need to serialize loads against other loads.
1287 Ops.push_back(DAG.getRoot());
1288 } else {
1289 Ops.push_back(getRoot());
1290 }
1291 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001292
1293 // Add the intrinsic ID as an integer operand.
1294 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1295
1296 // Add all operands of the call to the operand list.
1297 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1298 SDOperand Op = getValue(I.getOperand(i));
1299
1300 // If this is a vector type, force it to the right packed type.
1301 if (Op.getValueType() == MVT::Vector) {
1302 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1303 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1304
1305 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1306 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1307 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1308 }
1309
1310 assert(TLI.isTypeLegal(Op.getValueType()) &&
1311 "Intrinsic uses a non-legal type?");
1312 Ops.push_back(Op);
1313 }
1314
1315 std::vector<MVT::ValueType> VTs;
1316 if (I.getType() != Type::VoidTy) {
1317 MVT::ValueType VT = TLI.getValueType(I.getType());
1318 if (VT == MVT::Vector) {
1319 const PackedType *DestTy = cast<PackedType>(I.getType());
1320 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1321
1322 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1323 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1324 }
1325
1326 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1327 VTs.push_back(VT);
1328 }
1329 if (HasChain)
1330 VTs.push_back(MVT::Other);
1331
1332 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001333 SDOperand Result;
1334 if (!HasChain)
1335 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1336 else if (I.getType() != Type::VoidTy)
1337 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1338 else
1339 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1340
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001341 if (HasChain) {
1342 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1343 if (OnlyLoad)
1344 PendingLoads.push_back(Chain);
1345 else
1346 DAG.setRoot(Chain);
1347 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001348 if (I.getType() != Type::VoidTy) {
1349 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1350 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1351 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1352 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1353 DAG.getValueType(EVT));
1354 }
1355 setValue(&I, Result);
1356 }
1357}
1358
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001359/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1360/// we want to emit this as a call to a named external function, return the name
1361/// otherwise lower it and return null.
1362const char *
1363SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1364 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001365 default:
1366 // By default, turn this into a target intrinsic node.
1367 visitTargetIntrinsic(I, Intrinsic);
1368 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001369 case Intrinsic::vastart: visitVAStart(I); return 0;
1370 case Intrinsic::vaend: visitVAEnd(I); return 0;
1371 case Intrinsic::vacopy: visitVACopy(I); return 0;
1372 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1373 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1374 case Intrinsic::setjmp:
1375 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1376 break;
1377 case Intrinsic::longjmp:
1378 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1379 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001380 case Intrinsic::memcpy_i32:
1381 case Intrinsic::memcpy_i64:
1382 visitMemIntrinsic(I, ISD::MEMCPY);
1383 return 0;
1384 case Intrinsic::memset_i32:
1385 case Intrinsic::memset_i64:
1386 visitMemIntrinsic(I, ISD::MEMSET);
1387 return 0;
1388 case Intrinsic::memmove_i32:
1389 case Intrinsic::memmove_i64:
1390 visitMemIntrinsic(I, ISD::MEMMOVE);
1391 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001392
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001393 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001394 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001395 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001396 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001397 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001398
Jim Laskey5995d012006-02-11 01:01:30 +00001399 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001400 Ops.push_back(getValue(SPI.getLineValue()));
1401 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001402
Jim Laskeya8bdac82006-03-23 18:06:46 +00001403 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001404 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001405 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1406
Jim Laskey5995d012006-02-11 01:01:30 +00001407 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1408 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1409
Jim Laskeya8bdac82006-03-23 18:06:46 +00001410 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001411 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001412
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001413 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001414 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001415 case Intrinsic::dbg_region_start: {
1416 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1417 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001418 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001419 std::vector<SDOperand> Ops;
1420
1421 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1422
1423 Ops.push_back(getRoot());
1424 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1425
1426 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1427 }
1428
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001429 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001430 }
1431 case Intrinsic::dbg_region_end: {
1432 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1433 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001434 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001435 std::vector<SDOperand> Ops;
1436
1437 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1438
1439 Ops.push_back(getRoot());
1440 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1441
1442 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1443 }
1444
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001445 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001446 }
1447 case Intrinsic::dbg_func_start: {
1448 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1449 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001450 if (DebugInfo && FSI.getSubprogram() &&
1451 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001452 std::vector<SDOperand> Ops;
1453
1454 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1455
1456 Ops.push_back(getRoot());
1457 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1458
1459 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1460 }
1461
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001462 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001463 }
1464 case Intrinsic::dbg_declare: {
1465 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1466 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001467 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001468 std::vector<SDOperand> Ops;
1469
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001470 SDOperand AddressOp = getValue(DI.getAddress());
1471 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001472 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1473 }
1474 }
1475
1476 return 0;
1477 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001478
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001479 case Intrinsic::isunordered_f32:
1480 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001481 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1482 getValue(I.getOperand(2)), ISD::SETUO));
1483 return 0;
1484
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001485 case Intrinsic::sqrt_f32:
1486 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001487 setValue(&I, DAG.getNode(ISD::FSQRT,
1488 getValue(I.getOperand(1)).getValueType(),
1489 getValue(I.getOperand(1))));
1490 return 0;
1491 case Intrinsic::pcmarker: {
1492 SDOperand Tmp = getValue(I.getOperand(1));
1493 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1494 return 0;
1495 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001496 case Intrinsic::readcyclecounter: {
1497 std::vector<MVT::ValueType> VTs;
1498 VTs.push_back(MVT::i64);
1499 VTs.push_back(MVT::Other);
1500 std::vector<SDOperand> Ops;
1501 Ops.push_back(getRoot());
1502 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1503 setValue(&I, Tmp);
1504 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001505 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001506 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001507 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001508 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001509 case Intrinsic::bswap_i64:
1510 setValue(&I, DAG.getNode(ISD::BSWAP,
1511 getValue(I.getOperand(1)).getValueType(),
1512 getValue(I.getOperand(1))));
1513 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001514 case Intrinsic::cttz_i8:
1515 case Intrinsic::cttz_i16:
1516 case Intrinsic::cttz_i32:
1517 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001518 setValue(&I, DAG.getNode(ISD::CTTZ,
1519 getValue(I.getOperand(1)).getValueType(),
1520 getValue(I.getOperand(1))));
1521 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001522 case Intrinsic::ctlz_i8:
1523 case Intrinsic::ctlz_i16:
1524 case Intrinsic::ctlz_i32:
1525 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001526 setValue(&I, DAG.getNode(ISD::CTLZ,
1527 getValue(I.getOperand(1)).getValueType(),
1528 getValue(I.getOperand(1))));
1529 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001530 case Intrinsic::ctpop_i8:
1531 case Intrinsic::ctpop_i16:
1532 case Intrinsic::ctpop_i32:
1533 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001534 setValue(&I, DAG.getNode(ISD::CTPOP,
1535 getValue(I.getOperand(1)).getValueType(),
1536 getValue(I.getOperand(1))));
1537 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001538 case Intrinsic::stacksave: {
1539 std::vector<MVT::ValueType> VTs;
1540 VTs.push_back(TLI.getPointerTy());
1541 VTs.push_back(MVT::Other);
1542 std::vector<SDOperand> Ops;
1543 Ops.push_back(getRoot());
1544 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1545 setValue(&I, Tmp);
1546 DAG.setRoot(Tmp.getValue(1));
1547 return 0;
1548 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001549 case Intrinsic::stackrestore: {
1550 SDOperand Tmp = getValue(I.getOperand(1));
1551 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001552 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001553 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001554 case Intrinsic::prefetch:
1555 // FIXME: Currently discarding prefetches.
1556 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001557 }
1558}
1559
1560
Chris Lattner7a60d912005-01-07 07:47:53 +00001561void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001562 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001563 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001564 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001565 if (unsigned IID = F->getIntrinsicID()) {
1566 RenameFn = visitIntrinsicCall(I, IID);
1567 if (!RenameFn)
1568 return;
1569 } else { // Not an LLVM intrinsic.
1570 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001571 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1572 if (I.getNumOperands() == 3 && // Basic sanity checks.
1573 I.getOperand(1)->getType()->isFloatingPoint() &&
1574 I.getType() == I.getOperand(1)->getType() &&
1575 I.getType() == I.getOperand(2)->getType()) {
1576 SDOperand LHS = getValue(I.getOperand(1));
1577 SDOperand RHS = getValue(I.getOperand(2));
1578 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1579 LHS, RHS));
1580 return;
1581 }
1582 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001583 if (I.getNumOperands() == 2 && // Basic sanity checks.
1584 I.getOperand(1)->getType()->isFloatingPoint() &&
1585 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001586 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001587 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1588 return;
1589 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001590 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001591 if (I.getNumOperands() == 2 && // Basic sanity checks.
1592 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001593 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001594 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001595 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1596 return;
1597 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001598 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001599 if (I.getNumOperands() == 2 && // Basic sanity checks.
1600 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001601 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001602 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001603 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1604 return;
1605 }
1606 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001607 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001608 } else if (isa<InlineAsm>(I.getOperand(0))) {
1609 visitInlineAsm(I);
1610 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001611 }
Misha Brukman835702a2005-04-21 22:36:52 +00001612
Chris Lattner18d2b342005-01-08 22:48:57 +00001613 SDOperand Callee;
1614 if (!RenameFn)
1615 Callee = getValue(I.getOperand(0));
1616 else
1617 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001618 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001619 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001620 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1621 Value *Arg = I.getOperand(i);
1622 SDOperand ArgNode = getValue(Arg);
1623 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1624 }
Misha Brukman835702a2005-04-21 22:36:52 +00001625
Nate Begemanf6565252005-03-26 01:29:23 +00001626 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1627 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001628
Chris Lattner1f45cd72005-01-08 19:26:18 +00001629 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001630 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001631 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001632 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001633 setValue(&I, Result.first);
1634 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001635}
1636
Chris Lattner6f87d182006-02-22 22:37:12 +00001637SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001638 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001639 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1640 Chain = Val.getValue(1);
1641 Flag = Val.getValue(2);
1642
1643 // If the result was expanded, copy from the top part.
1644 if (Regs.size() > 1) {
1645 assert(Regs.size() == 2 &&
1646 "Cannot expand to more than 2 elts yet!");
1647 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1648 Chain = Val.getValue(1);
1649 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001650 if (DAG.getTargetLoweringInfo().isLittleEndian())
1651 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1652 else
1653 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001654 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001655
Chris Lattner6f87d182006-02-22 22:37:12 +00001656 // Otherwise, if the return value was promoted, truncate it to the
1657 // appropriate type.
1658 if (RegVT == ValueVT)
1659 return Val;
1660
1661 if (MVT::isInteger(RegVT))
1662 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1663 else
1664 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1665}
1666
Chris Lattner571d9642006-02-23 19:21:04 +00001667/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1668/// specified value into the registers specified by this object. This uses
1669/// Chain/Flag as the input and updates them for the output Chain/Flag.
1670void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001671 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001672 if (Regs.size() == 1) {
1673 // If there is a single register and the types differ, this must be
1674 // a promotion.
1675 if (RegVT != ValueVT) {
1676 if (MVT::isInteger(RegVT))
1677 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1678 else
1679 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1680 }
1681 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1682 Flag = Chain.getValue(1);
1683 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001684 std::vector<unsigned> R(Regs);
1685 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1686 std::reverse(R.begin(), R.end());
1687
1688 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001689 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1690 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001691 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001692 Flag = Chain.getValue(1);
1693 }
1694 }
1695}
Chris Lattner6f87d182006-02-22 22:37:12 +00001696
Chris Lattner571d9642006-02-23 19:21:04 +00001697/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1698/// operand list. This adds the code marker and includes the number of
1699/// values added into it.
1700void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001701 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001702 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1703 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1704 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1705}
Chris Lattner6f87d182006-02-22 22:37:12 +00001706
1707/// isAllocatableRegister - If the specified register is safe to allocate,
1708/// i.e. it isn't a stack pointer or some other special register, return the
1709/// register class for the register. Otherwise, return null.
1710static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001711isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1712 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001713 MVT::ValueType FoundVT = MVT::Other;
1714 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001715 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1716 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001717 MVT::ValueType ThisVT = MVT::Other;
1718
Chris Lattnerb1124f32006-02-22 23:09:03 +00001719 const TargetRegisterClass *RC = *RCI;
1720 // If none of the the value types for this register class are valid, we
1721 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001722 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1723 I != E; ++I) {
1724 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001725 // If we have already found this register in a different register class,
1726 // choose the one with the largest VT specified. For example, on
1727 // PowerPC, we favor f64 register classes over f32.
1728 if (FoundVT == MVT::Other ||
1729 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1730 ThisVT = *I;
1731 break;
1732 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001733 }
1734 }
1735
Chris Lattnerbec582f2006-04-02 00:24:45 +00001736 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001737
Chris Lattner6f87d182006-02-22 22:37:12 +00001738 // NOTE: This isn't ideal. In particular, this might allocate the
1739 // frame pointer in functions that need it (due to them not being taken
1740 // out of allocation, because a variable sized allocation hasn't been seen
1741 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001742 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1743 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001744 if (*I == Reg) {
1745 // We found a matching register class. Keep looking at others in case
1746 // we find one with larger registers that this physreg is also in.
1747 FoundRC = RC;
1748 FoundVT = ThisVT;
1749 break;
1750 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001751 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001752 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001753}
1754
1755RegsForValue SelectionDAGLowering::
1756GetRegistersForValue(const std::string &ConstrCode,
1757 MVT::ValueType VT, bool isOutReg, bool isInReg,
1758 std::set<unsigned> &OutputRegs,
1759 std::set<unsigned> &InputRegs) {
1760 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1761 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1762 std::vector<unsigned> Regs;
1763
1764 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1765 MVT::ValueType RegVT;
1766 MVT::ValueType ValueVT = VT;
1767
1768 if (PhysReg.first) {
1769 if (VT == MVT::Other)
1770 ValueVT = *PhysReg.second->vt_begin();
1771 RegVT = VT;
1772
1773 // This is a explicit reference to a physical register.
1774 Regs.push_back(PhysReg.first);
1775
1776 // If this is an expanded reference, add the rest of the regs to Regs.
1777 if (NumRegs != 1) {
1778 RegVT = *PhysReg.second->vt_begin();
1779 TargetRegisterClass::iterator I = PhysReg.second->begin();
1780 TargetRegisterClass::iterator E = PhysReg.second->end();
1781 for (; *I != PhysReg.first; ++I)
1782 assert(I != E && "Didn't find reg!");
1783
1784 // Already added the first reg.
1785 --NumRegs; ++I;
1786 for (; NumRegs; --NumRegs, ++I) {
1787 assert(I != E && "Ran out of registers to allocate!");
1788 Regs.push_back(*I);
1789 }
1790 }
1791 return RegsForValue(Regs, RegVT, ValueVT);
1792 }
1793
1794 // This is a reference to a register class. Allocate NumRegs consecutive,
1795 // available, registers from the class.
1796 std::vector<unsigned> RegClassRegs =
1797 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1798
1799 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1800 MachineFunction &MF = *CurMBB->getParent();
1801 unsigned NumAllocated = 0;
1802 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1803 unsigned Reg = RegClassRegs[i];
1804 // See if this register is available.
1805 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1806 (isInReg && InputRegs.count(Reg))) { // Already used.
1807 // Make sure we find consecutive registers.
1808 NumAllocated = 0;
1809 continue;
1810 }
1811
1812 // Check to see if this register is allocatable (i.e. don't give out the
1813 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001814 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001815 if (!RC) {
1816 // Make sure we find consecutive registers.
1817 NumAllocated = 0;
1818 continue;
1819 }
1820
1821 // Okay, this register is good, we can use it.
1822 ++NumAllocated;
1823
1824 // If we allocated enough consecutive
1825 if (NumAllocated == NumRegs) {
1826 unsigned RegStart = (i-NumAllocated)+1;
1827 unsigned RegEnd = i+1;
1828 // Mark all of the allocated registers used.
1829 for (unsigned i = RegStart; i != RegEnd; ++i) {
1830 unsigned Reg = RegClassRegs[i];
1831 Regs.push_back(Reg);
1832 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1833 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1834 }
1835
1836 return RegsForValue(Regs, *RC->vt_begin(), VT);
1837 }
1838 }
1839
1840 // Otherwise, we couldn't allocate enough registers for this.
1841 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001842}
1843
Chris Lattner6f87d182006-02-22 22:37:12 +00001844
Chris Lattner476e67b2006-01-26 22:24:51 +00001845/// visitInlineAsm - Handle a call to an InlineAsm object.
1846///
1847void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1848 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1849
1850 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1851 MVT::Other);
1852
1853 // Note, we treat inline asms both with and without side-effects as the same.
1854 // If an inline asm doesn't have side effects and doesn't access memory, we
1855 // could not choose to not chain it.
1856 bool hasSideEffects = IA->hasSideEffects();
1857
Chris Lattner3a5ed552006-02-01 01:28:23 +00001858 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001859 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001860
1861 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1862 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1863 /// if it is a def of that register.
1864 std::vector<SDOperand> AsmNodeOperands;
1865 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1866 AsmNodeOperands.push_back(AsmStr);
1867
1868 SDOperand Chain = getRoot();
1869 SDOperand Flag;
1870
Chris Lattner1558fc62006-02-01 18:59:47 +00001871 // We fully assign registers here at isel time. This is not optimal, but
1872 // should work. For register classes that correspond to LLVM classes, we
1873 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1874 // over the constraints, collecting fixed registers that we know we can't use.
1875 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001876 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001877 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1878 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1879 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001880
Chris Lattner7ad77df2006-02-22 00:56:39 +00001881 MVT::ValueType OpVT;
1882
1883 // Compute the value type for each operand and add it to ConstraintVTs.
1884 switch (Constraints[i].Type) {
1885 case InlineAsm::isOutput:
1886 if (!Constraints[i].isIndirectOutput) {
1887 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1888 OpVT = TLI.getValueType(I.getType());
1889 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001890 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001891 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1892 OpNum++; // Consumes a call operand.
1893 }
1894 break;
1895 case InlineAsm::isInput:
1896 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1897 OpNum++; // Consumes a call operand.
1898 break;
1899 case InlineAsm::isClobber:
1900 OpVT = MVT::Other;
1901 break;
1902 }
1903
1904 ConstraintVTs.push_back(OpVT);
1905
Chris Lattner6f87d182006-02-22 22:37:12 +00001906 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1907 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001908
Chris Lattner6f87d182006-02-22 22:37:12 +00001909 // Build a list of regs that this operand uses. This always has a single
1910 // element for promoted/expanded operands.
1911 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1912 false, false,
1913 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001914
1915 switch (Constraints[i].Type) {
1916 case InlineAsm::isOutput:
1917 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001918 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001919 // If this is an early-clobber output, it cannot be assigned to the same
1920 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001921 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001922 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001923 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001924 case InlineAsm::isInput:
1925 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001926 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001927 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001928 case InlineAsm::isClobber:
1929 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001930 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1931 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001932 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001933 }
1934 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001935
Chris Lattner5c79f982006-02-21 23:12:12 +00001936 // Loop over all of the inputs, copying the operand values into the
1937 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001938 RegsForValue RetValRegs;
1939 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001940 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001941
Chris Lattner2e56e892006-01-31 02:03:41 +00001942 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001943 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1944 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001945
Chris Lattner3a5ed552006-02-01 01:28:23 +00001946 switch (Constraints[i].Type) {
1947 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001948 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1949 if (ConstraintCode.size() == 1) // not a physreg name.
1950 CTy = TLI.getConstraintType(ConstraintCode[0]);
1951
1952 if (CTy == TargetLowering::C_Memory) {
1953 // Memory output.
1954 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1955
1956 // Check that the operand (the address to store to) isn't a float.
1957 if (!MVT::isInteger(InOperandVal.getValueType()))
1958 assert(0 && "MATCH FAIL!");
1959
1960 if (!Constraints[i].isIndirectOutput)
1961 assert(0 && "MATCH FAIL!");
1962
1963 OpNum++; // Consumes a call operand.
1964
1965 // Extend/truncate to the right pointer type if needed.
1966 MVT::ValueType PtrType = TLI.getPointerTy();
1967 if (InOperandVal.getValueType() < PtrType)
1968 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1969 else if (InOperandVal.getValueType() > PtrType)
1970 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1971
1972 // Add information to the INLINEASM node to know about this output.
1973 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1974 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1975 AsmNodeOperands.push_back(InOperandVal);
1976 break;
1977 }
1978
1979 // Otherwise, this is a register output.
1980 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1981
Chris Lattner6f87d182006-02-22 22:37:12 +00001982 // If this is an early-clobber output, or if there is an input
1983 // constraint that matches this, we need to reserve the input register
1984 // so no other inputs allocate to it.
1985 bool UsesInputRegister = false;
1986 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1987 UsesInputRegister = true;
1988
1989 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001990 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001991 RegsForValue Regs =
1992 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1993 true, UsesInputRegister,
1994 OutputRegs, InputRegs);
1995 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001996
Chris Lattner3a5ed552006-02-01 01:28:23 +00001997 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001998 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001999 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002000 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002001 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002002 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002003 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2004 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002005 OpNum++; // Consumes a call operand.
2006 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002007
2008 // Add information to the INLINEASM node to know that this register is
2009 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002010 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002011 break;
2012 }
2013 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002014 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002015 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002016
Chris Lattner7f5880b2006-02-02 00:25:23 +00002017 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2018 // If this is required to match an output register we have already set,
2019 // just use its register.
2020 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002021
Chris Lattner571d9642006-02-23 19:21:04 +00002022 // Scan until we find the definition we already emitted of this operand.
2023 // When we find it, create a RegsForValue operand.
2024 unsigned CurOp = 2; // The first operand.
2025 for (; OperandNo; --OperandNo) {
2026 // Advance to the next operand.
2027 unsigned NumOps =
2028 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2029 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2030 "Skipped past definitions?");
2031 CurOp += (NumOps>>3)+1;
2032 }
2033
2034 unsigned NumOps =
2035 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2036 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2037 "Skipped past definitions?");
2038
2039 // Add NumOps>>3 registers to MatchedRegs.
2040 RegsForValue MatchedRegs;
2041 MatchedRegs.ValueVT = InOperandVal.getValueType();
2042 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2043 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2044 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2045 MatchedRegs.Regs.push_back(Reg);
2046 }
2047
2048 // Use the produced MatchedRegs object to
2049 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2050 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002051 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002052 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002053
2054 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2055 if (ConstraintCode.size() == 1) // not a physreg name.
2056 CTy = TLI.getConstraintType(ConstraintCode[0]);
2057
2058 if (CTy == TargetLowering::C_Other) {
2059 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2060 assert(0 && "MATCH FAIL!");
2061
2062 // Add information to the INLINEASM node to know about this input.
2063 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2064 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2065 AsmNodeOperands.push_back(InOperandVal);
2066 break;
2067 } else if (CTy == TargetLowering::C_Memory) {
2068 // Memory input.
2069
2070 // Check that the operand isn't a float.
2071 if (!MVT::isInteger(InOperandVal.getValueType()))
2072 assert(0 && "MATCH FAIL!");
2073
2074 // Extend/truncate to the right pointer type if needed.
2075 MVT::ValueType PtrType = TLI.getPointerTy();
2076 if (InOperandVal.getValueType() < PtrType)
2077 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2078 else if (InOperandVal.getValueType() > PtrType)
2079 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2080
2081 // Add information to the INLINEASM node to know about this input.
2082 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2083 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2084 AsmNodeOperands.push_back(InOperandVal);
2085 break;
2086 }
2087
2088 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2089
2090 // Copy the input into the appropriate registers.
2091 RegsForValue InRegs =
2092 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2093 false, true, OutputRegs, InputRegs);
2094 // FIXME: should be match fail.
2095 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2096
2097 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2098
2099 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002100 break;
2101 }
Chris Lattner571d9642006-02-23 19:21:04 +00002102 case InlineAsm::isClobber: {
2103 RegsForValue ClobberedRegs =
2104 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2105 OutputRegs, InputRegs);
2106 // Add the clobbered value to the operand list, so that the register
2107 // allocator is aware that the physreg got clobbered.
2108 if (!ClobberedRegs.Regs.empty())
2109 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002110 break;
2111 }
Chris Lattner571d9642006-02-23 19:21:04 +00002112 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002113 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002114
2115 // Finish up input operands.
2116 AsmNodeOperands[0] = Chain;
2117 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2118
2119 std::vector<MVT::ValueType> VTs;
2120 VTs.push_back(MVT::Other);
2121 VTs.push_back(MVT::Flag);
2122 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2123 Flag = Chain.getValue(1);
2124
Chris Lattner2e56e892006-01-31 02:03:41 +00002125 // If this asm returns a register value, copy the result from that register
2126 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002127 if (!RetValRegs.Regs.empty())
2128 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002129
Chris Lattner2e56e892006-01-31 02:03:41 +00002130 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2131
2132 // Process indirect outputs, first output all of the flagged copies out of
2133 // physregs.
2134 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002135 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002136 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002137 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2138 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002139 }
2140
2141 // Emit the non-flagged stores from the physregs.
2142 std::vector<SDOperand> OutChains;
2143 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2144 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2145 StoresToEmit[i].first,
2146 getValue(StoresToEmit[i].second),
2147 DAG.getSrcValue(StoresToEmit[i].second)));
2148 if (!OutChains.empty())
2149 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00002150 DAG.setRoot(Chain);
2151}
2152
2153
Chris Lattner7a60d912005-01-07 07:47:53 +00002154void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2155 SDOperand Src = getValue(I.getOperand(0));
2156
2157 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002158
2159 if (IntPtr < Src.getValueType())
2160 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2161 else if (IntPtr > Src.getValueType())
2162 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002163
2164 // Scale the source by the type size.
2165 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2166 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2167 Src, getIntPtrConstant(ElementSize));
2168
2169 std::vector<std::pair<SDOperand, const Type*> > Args;
2170 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002171
2172 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002173 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002174 DAG.getExternalSymbol("malloc", IntPtr),
2175 Args, DAG);
2176 setValue(&I, Result.first); // Pointers always fit in registers
2177 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002178}
2179
2180void SelectionDAGLowering::visitFree(FreeInst &I) {
2181 std::vector<std::pair<SDOperand, const Type*> > Args;
2182 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2183 TLI.getTargetData().getIntPtrType()));
2184 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002185 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002186 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002187 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2188 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002189}
2190
Chris Lattner13d7c252005-08-26 20:54:47 +00002191// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2192// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2193// instructions are special in various ways, which require special support to
2194// insert. The specified MachineInstr is created but not inserted into any
2195// basic blocks, and the scheduler passes ownership of it to this method.
2196MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2197 MachineBasicBlock *MBB) {
2198 std::cerr << "If a target marks an instruction with "
2199 "'usesCustomDAGSchedInserter', it must implement "
2200 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2201 abort();
2202 return 0;
2203}
2204
Chris Lattner58cfd792005-01-09 00:00:49 +00002205void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002206 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2207 getValue(I.getOperand(1)),
2208 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002209}
2210
2211void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002212 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2213 getValue(I.getOperand(0)),
2214 DAG.getSrcValue(I.getOperand(0)));
2215 setValue(&I, V);
2216 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002217}
2218
2219void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002220 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2221 getValue(I.getOperand(1)),
2222 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002223}
2224
2225void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002226 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2227 getValue(I.getOperand(1)),
2228 getValue(I.getOperand(2)),
2229 DAG.getSrcValue(I.getOperand(1)),
2230 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002231}
2232
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002233/// TargetLowering::LowerArguments - This is the default LowerArguments
2234/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2235/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be removed.
2236std::vector<SDOperand>
2237TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2238 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2239 std::vector<SDOperand> Ops;
2240 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2241 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2242
2243 // Add one result value for each formal argument.
2244 std::vector<MVT::ValueType> RetVals;
2245 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2246 MVT::ValueType VT = getValueType(I->getType());
2247
2248 switch (getTypeAction(VT)) {
2249 default: assert(0 && "Unknown type action!");
2250 case Legal:
2251 RetVals.push_back(VT);
2252 break;
2253 case Promote:
2254 RetVals.push_back(getTypeToTransformTo(VT));
2255 break;
2256 case Expand:
2257 if (VT != MVT::Vector) {
2258 // If this is a large integer, it needs to be broken up into small
2259 // integers. Figure out what the destination type is and how many small
2260 // integers it turns into.
2261 MVT::ValueType NVT = getTypeToTransformTo(VT);
2262 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2263 for (unsigned i = 0; i != NumVals; ++i)
2264 RetVals.push_back(NVT);
2265 } else {
2266 // Otherwise, this is a vector type. We only support legal vectors
2267 // right now.
2268 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2269 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2270
2271 // Figure out if there is a Packed type corresponding to this Vector
2272 // type. If so, convert to the packed type.
2273 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2274 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2275 RetVals.push_back(TVT);
2276 } else {
2277 assert(0 && "Don't support illegal by-val vector arguments yet!");
2278 }
2279 }
2280 break;
2281 }
2282 }
2283
2284 // Create the node.
2285 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2286
2287 // Set up the return result vector.
2288 Ops.clear();
2289 unsigned i = 0;
2290 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2291 MVT::ValueType VT = getValueType(I->getType());
2292
2293 switch (getTypeAction(VT)) {
2294 default: assert(0 && "Unknown type action!");
2295 case Legal:
2296 Ops.push_back(SDOperand(Result, i++));
2297 break;
2298 case Promote: {
2299 SDOperand Op(Result, i++);
2300 if (MVT::isInteger(VT)) {
2301 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2302 : ISD::AssertZext;
2303 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2304 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2305 } else {
2306 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2307 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2308 }
2309 Ops.push_back(Op);
2310 break;
2311 }
2312 case Expand:
2313 if (VT != MVT::Vector) {
2314 // If this is a large integer, it needs to be reassembled from small
2315 // integers. Figure out what the source elt type is and how many small
2316 // integers it is.
2317 MVT::ValueType NVT = getTypeToTransformTo(VT);
2318 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2319 if (NumVals == 2) {
2320 SDOperand Lo = SDOperand(Result, i++);
2321 SDOperand Hi = SDOperand(Result, i++);
2322
2323 if (!isLittleEndian())
2324 std::swap(Lo, Hi);
2325
2326 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2327 } else {
2328 // Value scalarized into many values. Unimp for now.
2329 assert(0 && "Cannot expand i64 -> i16 yet!");
2330 }
2331 } else {
2332 // Otherwise, this is a vector type. We only support legal vectors
2333 // right now.
2334 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2335 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2336
2337 // Figure out if there is a Packed type corresponding to this Vector
2338 // type. If so, convert to the packed type.
2339 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2340 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2341 Ops.push_back(SDOperand(Result, i++));
2342 } else {
2343 assert(0 && "Don't support illegal by-val vector arguments yet!");
2344 }
2345 }
2346 break;
2347 }
2348 }
2349 return Ops;
2350}
2351
Chris Lattner58cfd792005-01-09 00:00:49 +00002352// It is always conservatively correct for llvm.returnaddress and
2353// llvm.frameaddress to return 0.
2354std::pair<SDOperand, SDOperand>
2355TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2356 unsigned Depth, SelectionDAG &DAG) {
2357 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002358}
2359
Chris Lattner29dcc712005-05-14 05:50:48 +00002360SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002361 assert(0 && "LowerOperation not implemented for this target!");
2362 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002363 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002364}
2365
Nate Begeman595ec732006-01-28 03:14:31 +00002366SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2367 SelectionDAG &DAG) {
2368 assert(0 && "CustomPromoteOperation not implemented for this target!");
2369 abort();
2370 return SDOperand();
2371}
2372
Chris Lattner58cfd792005-01-09 00:00:49 +00002373void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2374 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2375 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002376 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002377 setValue(&I, Result.first);
2378 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002379}
2380
Evan Cheng6781b6e2006-02-15 21:59:04 +00002381/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002382/// operand.
2383static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002384 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002385 MVT::ValueType CurVT = VT;
2386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2387 uint64_t Val = C->getValue() & 255;
2388 unsigned Shift = 8;
2389 while (CurVT != MVT::i8) {
2390 Val = (Val << Shift) | Val;
2391 Shift <<= 1;
2392 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002393 }
2394 return DAG.getConstant(Val, VT);
2395 } else {
2396 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2397 unsigned Shift = 8;
2398 while (CurVT != MVT::i8) {
2399 Value =
2400 DAG.getNode(ISD::OR, VT,
2401 DAG.getNode(ISD::SHL, VT, Value,
2402 DAG.getConstant(Shift, MVT::i8)), Value);
2403 Shift <<= 1;
2404 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002405 }
2406
2407 return Value;
2408 }
2409}
2410
Evan Cheng6781b6e2006-02-15 21:59:04 +00002411/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2412/// used when a memcpy is turned into a memset when the source is a constant
2413/// string ptr.
2414static SDOperand getMemsetStringVal(MVT::ValueType VT,
2415 SelectionDAG &DAG, TargetLowering &TLI,
2416 std::string &Str, unsigned Offset) {
2417 MVT::ValueType CurVT = VT;
2418 uint64_t Val = 0;
2419 unsigned MSB = getSizeInBits(VT) / 8;
2420 if (TLI.isLittleEndian())
2421 Offset = Offset + MSB - 1;
2422 for (unsigned i = 0; i != MSB; ++i) {
2423 Val = (Val << 8) | Str[Offset];
2424 Offset += TLI.isLittleEndian() ? -1 : 1;
2425 }
2426 return DAG.getConstant(Val, VT);
2427}
2428
Evan Cheng81fcea82006-02-14 08:22:34 +00002429/// getMemBasePlusOffset - Returns base and offset node for the
2430static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2431 SelectionDAG &DAG, TargetLowering &TLI) {
2432 MVT::ValueType VT = Base.getValueType();
2433 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2434}
2435
Evan Chengdb2a7a72006-02-14 20:12:38 +00002436/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002437/// to replace the memset / memcpy is below the threshold. It also returns the
2438/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002439static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2440 unsigned Limit, uint64_t Size,
2441 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002442 MVT::ValueType VT;
2443
2444 if (TLI.allowsUnalignedMemoryAccesses()) {
2445 VT = MVT::i64;
2446 } else {
2447 switch (Align & 7) {
2448 case 0:
2449 VT = MVT::i64;
2450 break;
2451 case 4:
2452 VT = MVT::i32;
2453 break;
2454 case 2:
2455 VT = MVT::i16;
2456 break;
2457 default:
2458 VT = MVT::i8;
2459 break;
2460 }
2461 }
2462
Evan Chengd5026102006-02-14 09:11:59 +00002463 MVT::ValueType LVT = MVT::i64;
2464 while (!TLI.isTypeLegal(LVT))
2465 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2466 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002467
Evan Chengd5026102006-02-14 09:11:59 +00002468 if (VT > LVT)
2469 VT = LVT;
2470
Evan Cheng04514992006-02-14 23:05:54 +00002471 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002472 while (Size != 0) {
2473 unsigned VTSize = getSizeInBits(VT) / 8;
2474 while (VTSize > Size) {
2475 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002476 VTSize >>= 1;
2477 }
Evan Chengd5026102006-02-14 09:11:59 +00002478 assert(MVT::isInteger(VT));
2479
2480 if (++NumMemOps > Limit)
2481 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002482 MemOps.push_back(VT);
2483 Size -= VTSize;
2484 }
Evan Chengd5026102006-02-14 09:11:59 +00002485
2486 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002487}
2488
Chris Lattner875def92005-01-11 05:56:49 +00002489void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002490 SDOperand Op1 = getValue(I.getOperand(1));
2491 SDOperand Op2 = getValue(I.getOperand(2));
2492 SDOperand Op3 = getValue(I.getOperand(3));
2493 SDOperand Op4 = getValue(I.getOperand(4));
2494 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2495 if (Align == 0) Align = 1;
2496
2497 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2498 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002499
2500 // Expand memset / memcpy to a series of load / store ops
2501 // if the size operand falls below a certain threshold.
2502 std::vector<SDOperand> OutChains;
2503 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002504 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002505 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002506 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2507 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002508 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002509 unsigned Offset = 0;
2510 for (unsigned i = 0; i < NumMemOps; i++) {
2511 MVT::ValueType VT = MemOps[i];
2512 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002513 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002514 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2515 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002516 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2517 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002518 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002519 Offset += VTSize;
2520 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002521 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002522 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002523 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002524 case ISD::MEMCPY: {
2525 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2526 Size->getValue(), Align, TLI)) {
2527 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002528 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002529 GlobalAddressSDNode *G = NULL;
2530 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002531 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002532
2533 if (Op2.getOpcode() == ISD::GlobalAddress)
2534 G = cast<GlobalAddressSDNode>(Op2);
2535 else if (Op2.getOpcode() == ISD::ADD &&
2536 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2537 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2538 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002539 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002540 }
2541 if (G) {
2542 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002543 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002544 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002545 if (!Str.empty()) {
2546 CopyFromStr = true;
2547 SrcOff += SrcDelta;
2548 }
2549 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002550 }
2551
Evan Chenge2038bd2006-02-15 01:54:51 +00002552 for (unsigned i = 0; i < NumMemOps; i++) {
2553 MVT::ValueType VT = MemOps[i];
2554 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002555 SDOperand Value, Chain, Store;
2556
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002557 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002558 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2559 Chain = getRoot();
2560 Store =
2561 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2562 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2563 DAG.getSrcValue(I.getOperand(1), DstOff));
2564 } else {
2565 Value = DAG.getLoad(VT, getRoot(),
2566 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2567 DAG.getSrcValue(I.getOperand(2), SrcOff));
2568 Chain = Value.getValue(1);
2569 Store =
2570 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2571 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2572 DAG.getSrcValue(I.getOperand(1), DstOff));
2573 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002574 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002575 SrcOff += VTSize;
2576 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002577 }
2578 }
2579 break;
2580 }
2581 }
2582
2583 if (!OutChains.empty()) {
2584 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2585 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002586 }
2587 }
2588
Chris Lattner875def92005-01-11 05:56:49 +00002589 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002590 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002591 Ops.push_back(Op1);
2592 Ops.push_back(Op2);
2593 Ops.push_back(Op3);
2594 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002595 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002596}
2597
Chris Lattner875def92005-01-11 05:56:49 +00002598//===----------------------------------------------------------------------===//
2599// SelectionDAGISel code
2600//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002601
2602unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2603 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2604}
2605
Chris Lattnerc9950c12005-08-17 06:37:43 +00002606void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002607 // FIXME: we only modify the CFG to split critical edges. This
2608 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002609}
Chris Lattner7a60d912005-01-07 07:47:53 +00002610
Chris Lattner35397782005-12-05 07:10:48 +00002611
2612/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2613/// casting to the type of GEPI.
2614static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2615 Value *Ptr, Value *PtrOffset) {
2616 if (V) return V; // Already computed.
2617
2618 BasicBlock::iterator InsertPt;
2619 if (BB == GEPI->getParent()) {
2620 // If insert into the GEP's block, insert right after the GEP.
2621 InsertPt = GEPI;
2622 ++InsertPt;
2623 } else {
2624 // Otherwise, insert at the top of BB, after any PHI nodes
2625 InsertPt = BB->begin();
2626 while (isa<PHINode>(InsertPt)) ++InsertPt;
2627 }
2628
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002629 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2630 // BB so that there is only one value live across basic blocks (the cast
2631 // operand).
2632 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2633 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2634 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2635
Chris Lattner35397782005-12-05 07:10:48 +00002636 // Add the offset, cast it to the right type.
2637 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2638 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2639 return V = Ptr;
2640}
2641
2642
2643/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2644/// selection, we want to be a bit careful about some things. In particular, if
2645/// we have a GEP instruction that is used in a different block than it is
2646/// defined, the addressing expression of the GEP cannot be folded into loads or
2647/// stores that use it. In this case, decompose the GEP and move constant
2648/// indices into blocks that use it.
2649static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2650 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002651 // If this GEP is only used inside the block it is defined in, there is no
2652 // need to rewrite it.
2653 bool isUsedOutsideDefBB = false;
2654 BasicBlock *DefBB = GEPI->getParent();
2655 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2656 UI != E; ++UI) {
2657 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2658 isUsedOutsideDefBB = true;
2659 break;
2660 }
2661 }
2662 if (!isUsedOutsideDefBB) return;
2663
2664 // If this GEP has no non-zero constant indices, there is nothing we can do,
2665 // ignore it.
2666 bool hasConstantIndex = false;
2667 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2668 E = GEPI->op_end(); OI != E; ++OI) {
2669 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2670 if (CI->getRawValue()) {
2671 hasConstantIndex = true;
2672 break;
2673 }
2674 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002675 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2676 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002677
2678 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2679 // constant offset (which we now know is non-zero) and deal with it later.
2680 uint64_t ConstantOffset = 0;
2681 const Type *UIntPtrTy = TD.getIntPtrType();
2682 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2683 const Type *Ty = GEPI->getOperand(0)->getType();
2684
2685 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2686 E = GEPI->op_end(); OI != E; ++OI) {
2687 Value *Idx = *OI;
2688 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2689 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2690 if (Field)
2691 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2692 Ty = StTy->getElementType(Field);
2693 } else {
2694 Ty = cast<SequentialType>(Ty)->getElementType();
2695
2696 // Handle constant subscripts.
2697 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2698 if (CI->getRawValue() == 0) continue;
2699
2700 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2701 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2702 else
2703 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2704 continue;
2705 }
2706
2707 // Ptr = Ptr + Idx * ElementSize;
2708
2709 // Cast Idx to UIntPtrTy if needed.
2710 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2711
2712 uint64_t ElementSize = TD.getTypeSize(Ty);
2713 // Mask off bits that should not be set.
2714 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2715 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2716
2717 // Multiply by the element size and add to the base.
2718 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2719 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2720 }
2721 }
2722
2723 // Make sure that the offset fits in uintptr_t.
2724 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2725 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2726
2727 // Okay, we have now emitted all of the variable index parts to the BB that
2728 // the GEP is defined in. Loop over all of the using instructions, inserting
2729 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002730 // instruction to use the newly computed value, making GEPI dead. When the
2731 // user is a load or store instruction address, we emit the add into the user
2732 // block, otherwise we use a canonical version right next to the gep (these
2733 // won't be foldable as addresses, so we might as well share the computation).
2734
Chris Lattner35397782005-12-05 07:10:48 +00002735 std::map<BasicBlock*,Value*> InsertedExprs;
2736 while (!GEPI->use_empty()) {
2737 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002738
2739 // If this use is not foldable into the addressing mode, use a version
2740 // emitted in the GEP block.
2741 Value *NewVal;
2742 if (!isa<LoadInst>(User) &&
2743 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2744 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2745 Ptr, PtrOffset);
2746 } else {
2747 // Otherwise, insert the code in the User's block so it can be folded into
2748 // any users in that block.
2749 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002750 User->getParent(), GEPI,
2751 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002752 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002753 User->replaceUsesOfWith(GEPI, NewVal);
2754 }
Chris Lattner35397782005-12-05 07:10:48 +00002755
2756 // Finally, the GEP is dead, remove it.
2757 GEPI->eraseFromParent();
2758}
2759
Chris Lattner7a60d912005-01-07 07:47:53 +00002760bool SelectionDAGISel::runOnFunction(Function &Fn) {
2761 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2762 RegMap = MF.getSSARegMap();
2763 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2764
Chris Lattner35397782005-12-05 07:10:48 +00002765 // First, split all critical edges for PHI nodes with incoming values that are
2766 // constants, this way the load of the constant into a vreg will not be placed
2767 // into MBBs that are used some other way.
2768 //
2769 // In this pass we also look for GEP instructions that are used across basic
2770 // blocks and rewrites them to improve basic-block-at-a-time selection.
2771 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002772 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2773 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002774 BasicBlock::iterator BBI;
2775 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002776 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2777 if (isa<Constant>(PN->getIncomingValue(i)))
2778 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002779
2780 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2781 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2782 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002783 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002784
Chris Lattner7a60d912005-01-07 07:47:53 +00002785 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2786
2787 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2788 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002789
Chris Lattner7a60d912005-01-07 07:47:53 +00002790 return true;
2791}
2792
2793
Chris Lattner718b5c22005-01-13 17:59:43 +00002794SDOperand SelectionDAGISel::
2795CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002796 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002797 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002798 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002799 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002800
2801 // If this type is not legal, we must make sure to not create an invalid
2802 // register use.
2803 MVT::ValueType SrcVT = Op.getValueType();
2804 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2805 SelectionDAG &DAG = SDL.DAG;
2806 if (SrcVT == DestVT) {
2807 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002808 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00002809 // Handle copies from generic vectors to registers.
2810 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2811 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2812 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00002813
Chris Lattner5fe1f542006-03-31 02:06:56 +00002814 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2815 // MVT::Vector type.
2816 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2817 DAG.getConstant(NE, MVT::i32),
2818 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00002819
Chris Lattner5fe1f542006-03-31 02:06:56 +00002820 // Loop over all of the elements of the resultant vector,
2821 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2822 // copying them into output registers.
2823 std::vector<SDOperand> OutChains;
2824 SDOperand Root = SDL.getRoot();
2825 for (unsigned i = 0; i != NE; ++i) {
2826 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2827 Op, DAG.getConstant(i, MVT::i32));
2828 if (PTyElementVT == PTyLegalElementVT) {
2829 // Elements are legal.
2830 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2831 } else if (PTyLegalElementVT > PTyElementVT) {
2832 // Elements are promoted.
2833 if (MVT::isFloatingPoint(PTyLegalElementVT))
2834 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2835 else
2836 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2837 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2838 } else {
2839 // Elements are expanded.
2840 // The src value is expanded into multiple registers.
2841 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2842 Elt, DAG.getConstant(0, MVT::i32));
2843 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2844 Elt, DAG.getConstant(1, MVT::i32));
2845 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2846 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2847 }
Chris Lattner672a42d2006-03-21 19:20:37 +00002848 }
Chris Lattner5fe1f542006-03-31 02:06:56 +00002849 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner33182322005-08-16 21:55:35 +00002850 } else if (SrcVT < DestVT) {
2851 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002852 if (MVT::isFloatingPoint(SrcVT))
2853 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2854 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002855 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002856 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2857 } else {
2858 // The src value is expanded into multiple registers.
2859 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2860 Op, DAG.getConstant(0, MVT::i32));
2861 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2862 Op, DAG.getConstant(1, MVT::i32));
2863 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2864 return DAG.getCopyToReg(Op, Reg+1, Hi);
2865 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002866}
2867
Chris Lattner16f64df2005-01-17 17:15:02 +00002868void SelectionDAGISel::
2869LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2870 std::vector<SDOperand> &UnorderedChains) {
2871 // If this is the entry block, emit arguments.
2872 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002873 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002874 SDOperand OldRoot = SDL.DAG.getRoot();
2875 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002876
Chris Lattner6871b232005-10-30 19:42:35 +00002877 unsigned a = 0;
2878 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2879 AI != E; ++AI, ++a)
2880 if (!AI->use_empty()) {
2881 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002882
Chris Lattner6871b232005-10-30 19:42:35 +00002883 // If this argument is live outside of the entry block, insert a copy from
2884 // whereever we got it to the vreg that other BB's will reference it as.
2885 if (FuncInfo.ValueMap.count(AI)) {
2886 SDOperand Copy =
2887 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2888 UnorderedChains.push_back(Copy);
2889 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002890 }
Chris Lattner6871b232005-10-30 19:42:35 +00002891
2892 // Next, if the function has live ins that need to be copied into vregs,
2893 // emit the copies now, into the top of the block.
2894 MachineFunction &MF = SDL.DAG.getMachineFunction();
2895 if (MF.livein_begin() != MF.livein_end()) {
2896 SSARegMap *RegMap = MF.getSSARegMap();
2897 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2898 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2899 E = MF.livein_end(); LI != E; ++LI)
2900 if (LI->second)
2901 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2902 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002903 }
Chris Lattner6871b232005-10-30 19:42:35 +00002904
2905 // Finally, if the target has anything special to do, allow it to do so.
2906 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002907}
2908
2909
Chris Lattner7a60d912005-01-07 07:47:53 +00002910void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2911 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00002912 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00002913 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002914
2915 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002916
Chris Lattner6871b232005-10-30 19:42:35 +00002917 // Lower any arguments needed in this block if this is the entry block.
2918 if (LLVMBB == &LLVMBB->getParent()->front())
2919 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002920
2921 BB = FuncInfo.MBBMap[LLVMBB];
2922 SDL.setCurrentBasicBlock(BB);
2923
2924 // Lower all of the non-terminator instructions.
2925 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2926 I != E; ++I)
2927 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00002928
Chris Lattner7a60d912005-01-07 07:47:53 +00002929 // Ensure that all instructions which are used outside of their defining
2930 // blocks are available as virtual registers.
2931 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002932 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002933 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002934 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002935 UnorderedChains.push_back(
2936 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002937 }
2938
2939 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2940 // ensure constants are generated when needed. Remember the virtual registers
2941 // that need to be added to the Machine PHI nodes as input. We cannot just
2942 // directly add them, because expansion might result in multiple MBB's for one
2943 // BB. As such, the start of the BB might correspond to a different MBB than
2944 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002945 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002946
2947 // Emit constants only once even if used by multiple PHI nodes.
2948 std::map<Constant*, unsigned> ConstantsOut;
2949
2950 // Check successor nodes PHI nodes that expect a constant to be available from
2951 // this block.
2952 TerminatorInst *TI = LLVMBB->getTerminator();
2953 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2954 BasicBlock *SuccBB = TI->getSuccessor(succ);
2955 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2956 PHINode *PN;
2957
2958 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2959 // nodes and Machine PHI nodes, but the incoming operands have not been
2960 // emitted yet.
2961 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002962 (PN = dyn_cast<PHINode>(I)); ++I)
2963 if (!PN->use_empty()) {
2964 unsigned Reg;
2965 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2966 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2967 unsigned &RegOut = ConstantsOut[C];
2968 if (RegOut == 0) {
2969 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002970 UnorderedChains.push_back(
2971 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002972 }
2973 Reg = RegOut;
2974 } else {
2975 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002976 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002977 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002978 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2979 "Didn't codegen value into a register!??");
2980 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002981 UnorderedChains.push_back(
2982 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002983 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002984 }
Misha Brukman835702a2005-04-21 22:36:52 +00002985
Chris Lattner8ea875f2005-01-07 21:34:19 +00002986 // Remember that this register needs to added to the machine PHI node as
2987 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00002988 MVT::ValueType VT = TLI.getValueType(PN->getType());
2989 unsigned NumElements;
2990 if (VT != MVT::Vector)
2991 NumElements = TLI.getNumElements(VT);
2992 else {
2993 MVT::ValueType VT1,VT2;
2994 NumElements =
2995 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
2996 VT1, VT2);
2997 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00002998 for (unsigned i = 0, e = NumElements; i != e; ++i)
2999 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003000 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003001 }
3002 ConstantsOut.clear();
3003
Chris Lattner718b5c22005-01-13 17:59:43 +00003004 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003005 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003006 SDOperand Root = SDL.getRoot();
3007 if (Root.getOpcode() != ISD::EntryToken) {
3008 unsigned i = 0, e = UnorderedChains.size();
3009 for (; i != e; ++i) {
3010 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3011 if (UnorderedChains[i].Val->getOperand(0) == Root)
3012 break; // Don't add the root if we already indirectly depend on it.
3013 }
3014
3015 if (i == e)
3016 UnorderedChains.push_back(Root);
3017 }
Chris Lattner718b5c22005-01-13 17:59:43 +00003018 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3019 }
3020
Chris Lattner7a60d912005-01-07 07:47:53 +00003021 // Lower the terminator after the copies are emitted.
3022 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003023
Nate Begemaned728c12006-03-27 01:32:24 +00003024 // Copy over any CaseBlock records that may now exist due to SwitchInst
3025 // lowering.
3026 SwitchCases.clear();
3027 SwitchCases = SDL.SwitchCases;
3028
Chris Lattner4108bb02005-01-17 19:43:36 +00003029 // Make sure the root of the DAG is up-to-date.
3030 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003031}
3032
Nate Begemaned728c12006-03-27 01:32:24 +00003033void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003034 // Run the DAG combiner in pre-legalize mode.
3035 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00003036
Chris Lattner7a60d912005-01-07 07:47:53 +00003037 DEBUG(std::cerr << "Lowered selection DAG:\n");
3038 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003039
Chris Lattner7a60d912005-01-07 07:47:53 +00003040 // Second step, hack on the DAG until it only uses operations and types that
3041 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003042 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003043
Chris Lattner7a60d912005-01-07 07:47:53 +00003044 DEBUG(std::cerr << "Legalized selection DAG:\n");
3045 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003046
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003047 // Run the DAG combiner in post-legalize mode.
3048 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00003049
Evan Cheng739a6a42006-01-21 02:32:06 +00003050 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00003051
Chris Lattner5ca31d92005-03-30 01:10:47 +00003052 // Third, instruction select all of the operations to machine code, adding the
3053 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003054 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003055
Chris Lattner7a60d912005-01-07 07:47:53 +00003056 DEBUG(std::cerr << "Selected machine code:\n");
3057 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003058}
Chris Lattner7a60d912005-01-07 07:47:53 +00003059
Nate Begemaned728c12006-03-27 01:32:24 +00003060void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3061 FunctionLoweringInfo &FuncInfo) {
3062 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3063 {
3064 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3065 CurDAG = &DAG;
3066
3067 // First step, lower LLVM code to some DAG. This DAG may use operations and
3068 // types that are not supported by the target.
3069 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3070
3071 // Second step, emit the lowered DAG as machine code.
3072 CodeGenAndEmitDAG(DAG);
3073 }
3074
Chris Lattner5ca31d92005-03-30 01:10:47 +00003075 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003076 // PHI nodes in successors.
Nate Begemaned728c12006-03-27 01:32:24 +00003077 if (SwitchCases.empty()) {
3078 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3079 MachineInstr *PHI = PHINodesToUpdate[i].first;
3080 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3081 "This is not a machine PHI node that we are updating!");
3082 PHI->addRegOperand(PHINodesToUpdate[i].second);
3083 PHI->addMachineBasicBlockOperand(BB);
3084 }
3085 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003086 }
Nate Begemaned728c12006-03-27 01:32:24 +00003087
3088 // If we generated any switch lowering information, build and codegen any
3089 // additional DAGs necessary.
3090 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3091 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3092 CurDAG = &SDAG;
3093 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3094 // Set the current basic block to the mbb we wish to insert the code into
3095 BB = SwitchCases[i].ThisBB;
3096 SDL.setCurrentBasicBlock(BB);
3097 // Emit the code
3098 SDL.visitSwitchCase(SwitchCases[i]);
3099 SDAG.setRoot(SDL.getRoot());
3100 CodeGenAndEmitDAG(SDAG);
3101 // Iterate over the phi nodes, if there is a phi node in a successor of this
3102 // block (for instance, the default block), then add a pair of operands to
3103 // the phi node for this block, as if we were coming from the original
3104 // BB before switch expansion.
3105 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3106 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3107 MachineBasicBlock *PHIBB = PHI->getParent();
3108 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3109 "This is not a machine PHI node that we are updating!");
3110 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3111 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3112 PHI->addMachineBasicBlockOperand(BB);
3113 }
3114 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00003115 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003116}
Evan Cheng739a6a42006-01-21 02:32:06 +00003117
3118//===----------------------------------------------------------------------===//
3119/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3120/// target node in the graph.
3121void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3122 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003123 ScheduleDAG *SL = NULL;
3124
3125 switch (ISHeuristic) {
3126 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00003127 case defaultScheduling:
3128 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
Chris Lattnerb21d3bf2006-04-21 17:16:16 +00003129 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3130 else {
3131 assert(TLI.getSchedulingPreference() ==
3132 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Evan Chenga6eff8a2006-01-25 09:12:57 +00003133 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnerb21d3bf2006-04-21 17:16:16 +00003134 }
Evan Chenga6eff8a2006-01-25 09:12:57 +00003135 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003136 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00003137 SL = createBFS_DAGScheduler(DAG, BB);
3138 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003139 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00003140 SL = createSimpleDAGScheduler(false, DAG, BB);
3141 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003142 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00003143 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00003144 break;
Evan Cheng31272342006-01-23 08:26:10 +00003145 case listSchedulingBURR:
3146 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00003147 break;
Chris Lattner47639db2006-03-06 00:22:00 +00003148 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00003149 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00003150 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00003151 }
Chris Lattnere23928c2006-01-21 19:12:11 +00003152 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003153 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003154}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003155
Chris Lattner543832d2006-03-08 04:25:59 +00003156HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3157 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00003158}
3159
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003160/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3161/// by tblgen. Others should not call it.
3162void SelectionDAGISel::
3163SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3164 std::vector<SDOperand> InOps;
3165 std::swap(InOps, Ops);
3166
3167 Ops.push_back(InOps[0]); // input chain.
3168 Ops.push_back(InOps[1]); // input asm string.
3169
3170 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
3171 unsigned i = 2, e = InOps.size();
3172 if (InOps[e-1].getValueType() == MVT::Flag)
3173 --e; // Don't process a flag operand if it is here.
3174
3175 while (i != e) {
3176 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3177 if ((Flags & 7) != 4 /*MEM*/) {
3178 // Just skip over this operand, copying the operands verbatim.
3179 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3180 i += (Flags >> 3) + 1;
3181 } else {
3182 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3183 // Otherwise, this is a memory operand. Ask the target to select it.
3184 std::vector<SDOperand> SelOps;
3185 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3186 std::cerr << "Could not match memory address. Inline asm failure!\n";
3187 exit(1);
3188 }
3189
3190 // Add this to the output node.
3191 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3192 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3193 i += 2;
3194 }
3195 }
3196
3197 // Add the flag input back if present.
3198 if (e != InOps.size())
3199 Ops.push_back(InOps.back());
3200}