blob: 5a95ff0bc5386956697b66e1bf3eb024ed7c0562 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/SelectionDAG.h"
32#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000033#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetFrameInfo.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000040#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
43#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000044#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattnerda8abb02005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000051ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
53static cl::opt<bool>
54ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000056#else
Chris Lattner5e46a192006-04-02 03:07:27 +000057static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Chris Lattner20a49212006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Cheng4ef10862006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000076 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner03fc53c2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Cheng4ef10862006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner864635a2006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000141 };
142}
Evan Cheng4ef10862006-01-23 07:01:07 +0000143
Chris Lattner1c08c712005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000173
Chris Lattner3c384492006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner1c08c712005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000185/// PHI nodes or outside of the basic block that defines it, or used by a
186/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000187static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
188 if (isa<PHINode>(I)) return true;
189 BasicBlock *BB = I->getParent();
190 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000191 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
192 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 return true;
194 return false;
195}
196
Chris Lattnerbf209482005-10-30 19:42:35 +0000197/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000198/// entry block, return true. This includes arguments used by switches, since
199/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000200static bool isOnlyUsedInEntryBlock(Argument *A) {
201 BasicBlock *Entry = A->getParent()->begin();
202 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000203 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000204 return false; // Use not in entry block.
205 return true;
206}
207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000209 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000210 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
211
Chris Lattnerbf209482005-10-30 19:42:35 +0000212 // Create a vreg for each argument register that is not dead and is used
213 // outside of the entry block for the function.
214 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
215 AI != E; ++AI)
216 if (!isOnlyUsedInEntryBlock(AI))
217 InitializeRegForValue(AI);
218
Chris Lattner1c08c712005-01-07 07:47:53 +0000219 // Initialize the mapping of values to registers. This is only set up for
220 // instruction values that are used outside of the block that defines
221 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000222 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000223 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
224 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
225 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
226 const Type *Ty = AI->getAllocatedType();
227 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000228 unsigned Align =
229 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
230 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000231
232 // If the alignment of the value is smaller than the size of the value,
233 // and if the size of the value is particularly small (<= 8 bytes),
234 // round up to the size of the value for potentially better performance.
235 //
236 // FIXME: This could be made better with a preferred alignment hook in
237 // TargetData. It serves primarily to 8-byte align doubles for X86.
238 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000239 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000240 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000242 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000243 }
244
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000245 for (; BB != EB; ++BB)
246 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
248 if (!isa<AllocaInst>(I) ||
249 !StaticAllocaMap.count(cast<AllocaInst>(I)))
250 InitializeRegForValue(I);
251
252 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
253 // also creates the initial PHI MachineInstrs, though none of the input
254 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000255 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000256 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
257 MBBMap[BB] = MBB;
258 MF.getBasicBlockList().push_back(MBB);
259
260 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
261 // appropriate.
262 PHINode *PN;
263 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000264 (PN = dyn_cast<PHINode>(I)); ++I)
265 if (!PN->use_empty()) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000266 MVT::ValueType VT = TLI.getValueType(PN->getType());
267 unsigned NumElements;
268 if (VT != MVT::Vector)
269 NumElements = TLI.getNumElements(VT);
270 else {
271 MVT::ValueType VT1,VT2;
272 NumElements =
273 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
274 VT1, VT2);
275 }
Chris Lattnerf44fd882005-01-07 21:34:19 +0000276 unsigned PHIReg = ValueMap[PN];
277 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
278 for (unsigned i = 0; i != NumElements; ++i)
279 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
280 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000281 }
282}
283
Chris Lattner3c384492006-03-16 19:51:18 +0000284/// CreateRegForValue - Allocate the appropriate number of virtual registers of
285/// the correctly promoted or expanded types. Assign these registers
286/// consecutive vreg numbers and return the first assigned number.
287unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
288 MVT::ValueType VT = TLI.getValueType(V->getType());
289
290 // The number of multiples of registers that we need, to, e.g., split up
291 // a <2 x int64> -> 4 x i32 registers.
292 unsigned NumVectorRegs = 1;
293
294 // If this is a packed type, figure out what type it will decompose into
295 // and how many of the elements it will use.
296 if (VT == MVT::Vector) {
297 const PackedType *PTy = cast<PackedType>(V->getType());
298 unsigned NumElts = PTy->getNumElements();
299 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
300
301 // Divide the input until we get to a supported size. This will always
302 // end with a scalar if the target doesn't support vectors.
303 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
304 NumElts >>= 1;
305 NumVectorRegs <<= 1;
306 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000307 if (NumElts == 1)
308 VT = EltTy;
309 else
310 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000311 }
312
313 // The common case is that we will only create one register for this
314 // value. If we have that case, create and return the virtual register.
315 unsigned NV = TLI.getNumElements(VT);
316 if (NV == 1) {
317 // If we are promoting this value, pick the next largest supported type.
318 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
319 unsigned Reg = MakeReg(PromotedType);
320 // If this is a vector of supported or promoted types (e.g. 4 x i16),
321 // create all of the registers.
322 for (unsigned i = 1; i != NumVectorRegs; ++i)
323 MakeReg(PromotedType);
324 return Reg;
325 }
326
327 // If this value is represented with multiple target registers, make sure
328 // to create enough consecutive registers of the right (smaller) type.
329 unsigned NT = VT-1; // Find the type to use.
330 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
331 --NT;
332
333 unsigned R = MakeReg((MVT::ValueType)NT);
334 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
335 MakeReg((MVT::ValueType)NT);
336 return R;
337}
Chris Lattner1c08c712005-01-07 07:47:53 +0000338
339//===----------------------------------------------------------------------===//
340/// SelectionDAGLowering - This is the common target-independent lowering
341/// implementation that is parameterized by a TargetLowering object.
342/// Also, targets can overload any lowering method.
343///
344namespace llvm {
345class SelectionDAGLowering {
346 MachineBasicBlock *CurMBB;
347
348 std::map<const Value*, SDOperand> NodeMap;
349
Chris Lattnerd3948112005-01-17 22:19:26 +0000350 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
351 /// them up and then emit token factor nodes when possible. This allows us to
352 /// get simple disambiguation between loads without worrying about alias
353 /// analysis.
354 std::vector<SDOperand> PendingLoads;
355
Nate Begemanf15485a2006-03-27 01:32:24 +0000356 /// Case - A pair of values to record the Value for a switch case, and the
357 /// case's target basic block.
358 typedef std::pair<Constant*, MachineBasicBlock*> Case;
359 typedef std::vector<Case>::iterator CaseItr;
360 typedef std::pair<CaseItr, CaseItr> CaseRange;
361
362 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
363 /// of conditional branches.
364 struct CaseRec {
365 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
366 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
367
368 /// CaseBB - The MBB in which to emit the compare and branch
369 MachineBasicBlock *CaseBB;
370 /// LT, GE - If nonzero, we know the current case value must be less-than or
371 /// greater-than-or-equal-to these Constants.
372 Constant *LT;
373 Constant *GE;
374 /// Range - A pair of iterators representing the range of case values to be
375 /// processed at this point in the binary search tree.
376 CaseRange Range;
377 };
378
379 /// The comparison function for sorting Case values.
380 struct CaseCmp {
381 bool operator () (const Case& C1, const Case& C2) {
382 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
383 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
384
385 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
386 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
387 }
388 };
389
Chris Lattner1c08c712005-01-07 07:47:53 +0000390public:
391 // TLI - This is information that describes the available target features we
392 // need for lowering. This indicates when operations are unavailable,
393 // implemented with a libcall, etc.
394 TargetLowering &TLI;
395 SelectionDAG &DAG;
396 const TargetData &TD;
397
Nate Begemanf15485a2006-03-27 01:32:24 +0000398 /// SwitchCases - Vector of CaseBlock structures used to communicate
399 /// SwitchInst code generation information.
400 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
401
Chris Lattner1c08c712005-01-07 07:47:53 +0000402 /// FuncInfo - Information about the function as a whole.
403 ///
404 FunctionLoweringInfo &FuncInfo;
405
406 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000407 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000408 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
409 FuncInfo(funcinfo) {
410 }
411
Chris Lattnera651cf62005-01-17 19:43:36 +0000412 /// getRoot - Return the current virtual root of the Selection DAG.
413 ///
414 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000415 if (PendingLoads.empty())
416 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000417
Chris Lattnerd3948112005-01-17 22:19:26 +0000418 if (PendingLoads.size() == 1) {
419 SDOperand Root = PendingLoads[0];
420 DAG.setRoot(Root);
421 PendingLoads.clear();
422 return Root;
423 }
424
425 // Otherwise, we have to make a token factor node.
426 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
427 PendingLoads.clear();
428 DAG.setRoot(Root);
429 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000430 }
431
Chris Lattner1c08c712005-01-07 07:47:53 +0000432 void visit(Instruction &I) { visit(I.getOpcode(), I); }
433
434 void visit(unsigned Opcode, User &I) {
435 switch (Opcode) {
436 default: assert(0 && "Unknown instruction type encountered!");
437 abort();
438 // Build the switch statement using the Instruction.def file.
439#define HANDLE_INST(NUM, OPCODE, CLASS) \
440 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
441#include "llvm/Instruction.def"
442 }
443 }
444
445 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
446
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000447 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
448 SDOperand SrcValue, SDOperand Root,
449 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000450
451 SDOperand getIntPtrConstant(uint64_t Val) {
452 return DAG.getConstant(Val, TLI.getPointerTy());
453 }
454
Chris Lattner199862b2006-03-16 19:57:50 +0000455 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000456
457 const SDOperand &setValue(const Value *V, SDOperand NewN) {
458 SDOperand &N = NodeMap[V];
459 assert(N.Val == 0 && "Already set a value for this node!");
460 return N = NewN;
461 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000462
Chris Lattner864635a2006-02-22 22:37:12 +0000463 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
464 MVT::ValueType VT,
465 bool OutReg, bool InReg,
466 std::set<unsigned> &OutputRegs,
467 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000468
Chris Lattner1c08c712005-01-07 07:47:53 +0000469 // Terminator instructions.
470 void visitRet(ReturnInst &I);
471 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000472 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
Nate Begemanf15485a2006-03-27 01:32:24 +0000475 // Helper for visitSwitch
476 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
477
Chris Lattner1c08c712005-01-07 07:47:53 +0000478 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000482 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000483 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000484 void visitAdd(User &I) {
485 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000486 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000487 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000488 void visitMul(User &I) {
489 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000490 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000491 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000492 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000493 visitBinary(I,
494 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
495 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000496 }
497 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000500 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000501 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
502 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
503 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000504 void visitShl(User &I) { visitShift(I, ISD::SHL); }
505 void visitShr(User &I) {
506 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000507 }
508
509 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
510 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
511 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
512 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
513 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
514 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
515 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
516
Chris Lattner2bbd8102006-03-29 00:11:43 +0000517 void visitExtractElement(User &I);
518 void visitInsertElement(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000519
Chris Lattner1c08c712005-01-07 07:47:53 +0000520 void visitGetElementPtr(User &I);
521 void visitCast(User &I);
522 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000523
524 void visitMalloc(MallocInst &I);
525 void visitFree(FreeInst &I);
526 void visitAlloca(AllocaInst &I);
527 void visitLoad(LoadInst &I);
528 void visitStore(StoreInst &I);
529 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
530 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000531 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000532 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000533 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000534
Chris Lattner1c08c712005-01-07 07:47:53 +0000535 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000536 void visitVAArg(VAArgInst &I);
537 void visitVAEnd(CallInst &I);
538 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000539 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000540
Chris Lattner7041ee32005-01-11 05:56:49 +0000541 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000542
543 void visitUserOp1(Instruction &I) {
544 assert(0 && "UserOp1 should not exist at instruction selection time!");
545 abort();
546 }
547 void visitUserOp2(Instruction &I) {
548 assert(0 && "UserOp2 should not exist at instruction selection time!");
549 abort();
550 }
551};
552} // end namespace llvm
553
Chris Lattner199862b2006-03-16 19:57:50 +0000554SDOperand SelectionDAGLowering::getValue(const Value *V) {
555 SDOperand &N = NodeMap[V];
556 if (N.Val) return N;
557
558 const Type *VTy = V->getType();
559 MVT::ValueType VT = TLI.getValueType(VTy);
560 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
561 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
562 visit(CE->getOpcode(), *CE);
563 assert(N.Val && "visit didn't populate the ValueMap!");
564 return N;
565 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
566 return N = DAG.getGlobalAddress(GV, VT);
567 } else if (isa<ConstantPointerNull>(C)) {
568 return N = DAG.getConstant(0, TLI.getPointerTy());
569 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000570 if (!isa<PackedType>(VTy))
571 return N = DAG.getNode(ISD::UNDEF, VT);
572
Chris Lattnerb2827b02006-03-19 00:52:58 +0000573 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000574 const PackedType *PTy = cast<PackedType>(VTy);
575 unsigned NumElements = PTy->getNumElements();
576 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
577
578 std::vector<SDOperand> Ops;
579 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
580
581 // Create a VConstant node with generic Vector type.
582 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
583 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerb2827b02006-03-19 00:52:58 +0000584 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000585 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
586 return N = DAG.getConstantFP(CFP->getValue(), VT);
587 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
588 unsigned NumElements = PTy->getNumElements();
589 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000590
591 // Now that we know the number and type of the elements, push a
592 // Constant or ConstantFP node onto the ops list for each element of
593 // the packed constant.
594 std::vector<SDOperand> Ops;
595 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000596 for (unsigned i = 0; i != NumElements; ++i)
597 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000598 } else {
599 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
600 SDOperand Op;
601 if (MVT::isFloatingPoint(PVT))
602 Op = DAG.getConstantFP(0, PVT);
603 else
604 Op = DAG.getConstant(0, PVT);
605 Ops.assign(NumElements, Op);
606 }
607
Chris Lattnerb2827b02006-03-19 00:52:58 +0000608 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000609 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
610 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerb2827b02006-03-19 00:52:58 +0000611 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000612 } else {
613 // Canonicalize all constant ints to be unsigned.
614 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
615 }
616 }
617
618 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
619 std::map<const AllocaInst*, int>::iterator SI =
620 FuncInfo.StaticAllocaMap.find(AI);
621 if (SI != FuncInfo.StaticAllocaMap.end())
622 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
623 }
624
625 std::map<const Value*, unsigned>::const_iterator VMI =
626 FuncInfo.ValueMap.find(V);
627 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
628
629 unsigned InReg = VMI->second;
630
631 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000632 if (VT != MVT::Vector) {
633 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000634
Chris Lattner70c2a612006-03-31 02:06:56 +0000635 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
636 if (DestVT < VT) {
637 // Source must be expanded. This input value is actually coming from the
638 // register pair VMI->second and VMI->second+1.
639 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
640 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
641 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000642 if (MVT::isFloatingPoint(VT))
643 N = DAG.getNode(ISD::FP_ROUND, VT, N);
644 else
645 N = DAG.getNode(ISD::TRUNCATE, VT, N);
646 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000647 } else {
648 // Otherwise, if this is a vector, make it available as a generic vector
649 // here.
650 MVT::ValueType PTyElementVT, PTyLegalElementVT;
651 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(VTy),PTyElementVT,
652 PTyLegalElementVT);
653
654 // Build a VBUILD_VECTOR with the input registers.
655 std::vector<SDOperand> Ops;
656 if (PTyElementVT == PTyLegalElementVT) {
657 // If the value types are legal, just VBUILD the CopyFromReg nodes.
658 for (unsigned i = 0; i != NE; ++i)
659 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
660 PTyElementVT));
661 } else if (PTyElementVT < PTyLegalElementVT) {
662 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
663 for (unsigned i = 0; i != NE; ++i) {
664 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
665 PTyElementVT);
666 if (MVT::isFloatingPoint(PTyElementVT))
667 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
668 else
669 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
670 Ops.push_back(Op);
671 }
672 } else {
673 // If the register was expanded, use BUILD_PAIR.
674 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
675 for (unsigned i = 0; i != NE/2; ++i) {
676 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
677 PTyElementVT);
678 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
679 PTyElementVT);
680 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
681 }
682 }
683
684 Ops.push_back(DAG.getConstant(NE, MVT::i32));
685 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
686 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner199862b2006-03-16 19:57:50 +0000687 }
688
689 return N;
690}
691
692
Chris Lattner1c08c712005-01-07 07:47:53 +0000693void SelectionDAGLowering::visitRet(ReturnInst &I) {
694 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000695 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000696 return;
697 }
Nate Begemanee625572006-01-27 21:09:22 +0000698 std::vector<SDOperand> NewValues;
699 NewValues.push_back(getRoot());
700 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
701 SDOperand RetOp = getValue(I.getOperand(i));
702
703 // If this is an integer return value, we need to promote it ourselves to
704 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
705 // than sign/zero.
706 if (MVT::isInteger(RetOp.getValueType()) &&
707 RetOp.getValueType() < MVT::i64) {
708 MVT::ValueType TmpVT;
709 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
710 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
711 else
712 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000713
Nate Begemanee625572006-01-27 21:09:22 +0000714 if (I.getOperand(i)->getType()->isSigned())
715 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
716 else
717 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
718 }
719 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 }
Nate Begemanee625572006-01-27 21:09:22 +0000721 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000722}
723
724void SelectionDAGLowering::visitBr(BranchInst &I) {
725 // Update machine-CFG edges.
726 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemanf15485a2006-03-27 01:32:24 +0000727 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000728
729 // Figure out which block is immediately after the current one.
730 MachineBasicBlock *NextBlock = 0;
731 MachineFunction::iterator BBI = CurMBB;
732 if (++BBI != CurMBB->getParent()->end())
733 NextBlock = BBI;
734
735 if (I.isUnconditional()) {
736 // If this is not a fall-through branch, emit the branch.
737 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000738 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000739 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000740 } else {
741 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemanf15485a2006-03-27 01:32:24 +0000742 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000743
744 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000745 if (Succ1MBB == NextBlock) {
746 // If the condition is false, fall through. This means we should branch
747 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000748 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000749 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000750 } else if (Succ0MBB == NextBlock) {
751 // If the condition is true, fall through. This means we should branch if
752 // the condition is false to Succ #1. Invert the condition first.
753 SDOperand True = DAG.getConstant(1, Cond.getValueType());
754 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000755 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000756 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000757 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000758 std::vector<SDOperand> Ops;
759 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000760 // If the false case is the current basic block, then this is a self
761 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
762 // adds an extra instruction in the loop. Instead, invert the
763 // condition and emit "Loop: ... br!cond Loop; br Out.
764 if (CurMBB == Succ1MBB) {
765 std::swap(Succ0MBB, Succ1MBB);
766 SDOperand True = DAG.getConstant(1, Cond.getValueType());
767 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
768 }
Nate Begeman81e80972006-03-17 01:40:33 +0000769 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
770 DAG.getBasicBlock(Succ0MBB));
771 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
772 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000773 }
774 }
775}
776
Nate Begemanf15485a2006-03-27 01:32:24 +0000777/// visitSwitchCase - Emits the necessary code to represent a single node in
778/// the binary search tree resulting from lowering a switch instruction.
779void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
780 SDOperand SwitchOp = getValue(CB.SwitchV);
781 SDOperand CaseOp = getValue(CB.CaseC);
782 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
783
784 // Set NextBlock to be the MBB immediately after the current one, if any.
785 // This is used to avoid emitting unnecessary branches to the next block.
786 MachineBasicBlock *NextBlock = 0;
787 MachineFunction::iterator BBI = CurMBB;
788 if (++BBI != CurMBB->getParent()->end())
789 NextBlock = BBI;
790
791 // If the lhs block is the next block, invert the condition so that we can
792 // fall through to the lhs instead of the rhs block.
793 if (CB.LHSBB == NextBlock) {
794 std::swap(CB.LHSBB, CB.RHSBB);
795 SDOperand True = DAG.getConstant(1, Cond.getValueType());
796 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
797 }
798 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
799 DAG.getBasicBlock(CB.LHSBB));
800 if (CB.RHSBB == NextBlock)
801 DAG.setRoot(BrCond);
802 else
803 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
804 DAG.getBasicBlock(CB.RHSBB)));
805 // Update successor info
806 CurMBB->addSuccessor(CB.LHSBB);
807 CurMBB->addSuccessor(CB.RHSBB);
808}
809
810void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
811 // Figure out which block is immediately after the current one.
812 MachineBasicBlock *NextBlock = 0;
813 MachineFunction::iterator BBI = CurMBB;
814 if (++BBI != CurMBB->getParent()->end())
815 NextBlock = BBI;
816
817 // If there is only the default destination, branch to it if it is not the
818 // next basic block. Otherwise, just fall through.
819 if (I.getNumOperands() == 2) {
820 // Update machine-CFG edges.
821 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
822 // If this is not a fall-through branch, emit the branch.
823 if (DefaultMBB != NextBlock)
824 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
825 DAG.getBasicBlock(DefaultMBB)));
826 return;
827 }
828
829 // If there are any non-default case statements, create a vector of Cases
830 // representing each one, and sort the vector so that we can efficiently
831 // create a binary search tree from them.
832 std::vector<Case> Cases;
833 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
834 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
835 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
836 }
837 std::sort(Cases.begin(), Cases.end(), CaseCmp());
838
839 // Get the Value to be switched on and default basic blocks, which will be
840 // inserted into CaseBlock records, representing basic blocks in the binary
841 // search tree.
842 Value *SV = I.getOperand(0);
843 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
844
845 // Get the current MachineFunction and LLVM basic block, for use in creating
846 // and inserting new MBBs during the creation of the binary search tree.
847 MachineFunction *CurMF = CurMBB->getParent();
848 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
849
850 // Push the initial CaseRec onto the worklist
851 std::vector<CaseRec> CaseVec;
852 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
853
854 while (!CaseVec.empty()) {
855 // Grab a record representing a case range to process off the worklist
856 CaseRec CR = CaseVec.back();
857 CaseVec.pop_back();
858
859 // Size is the number of Cases represented by this range. If Size is 1,
860 // then we are processing a leaf of the binary search tree. Otherwise,
861 // we need to pick a pivot, and push left and right ranges onto the
862 // worklist.
863 unsigned Size = CR.Range.second - CR.Range.first;
864
865 if (Size == 1) {
866 // Create a CaseBlock record representing a conditional branch to
867 // the Case's target mbb if the value being switched on SV is equal
868 // to C. Otherwise, branch to default.
869 Constant *C = CR.Range.first->first;
870 MachineBasicBlock *Target = CR.Range.first->second;
871 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
872 CR.CaseBB);
873 // If the MBB representing the leaf node is the current MBB, then just
874 // call visitSwitchCase to emit the code into the current block.
875 // Otherwise, push the CaseBlock onto the vector to be later processed
876 // by SDISel, and insert the node's MBB before the next MBB.
877 if (CR.CaseBB == CurMBB)
878 visitSwitchCase(CB);
879 else {
880 SwitchCases.push_back(CB);
881 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
882 }
883 } else {
884 // split case range at pivot
885 CaseItr Pivot = CR.Range.first + (Size / 2);
886 CaseRange LHSR(CR.Range.first, Pivot);
887 CaseRange RHSR(Pivot, CR.Range.second);
888 Constant *C = Pivot->first;
889 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
890 // We know that we branch to the LHS if the Value being switched on is
891 // less than the Pivot value, C. We use this to optimize our binary
892 // tree a bit, by recognizing that if SV is greater than or equal to the
893 // LHS's Case Value, and that Case Value is exactly one less than the
894 // Pivot's Value, then we can branch directly to the LHS's Target,
895 // rather than creating a leaf node for it.
896 if ((LHSR.second - LHSR.first) == 1 &&
897 LHSR.first->first == CR.GE &&
898 cast<ConstantIntegral>(C)->getRawValue() ==
899 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
900 LHSBB = LHSR.first->second;
901 } else {
902 LHSBB = new MachineBasicBlock(LLVMBB);
903 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
904 }
905 // Similar to the optimization above, if the Value being switched on is
906 // known to be less than the Constant CR.LT, and the current Case Value
907 // is CR.LT - 1, then we can branch directly to the target block for
908 // the current Case Value, rather than emitting a RHS leaf node for it.
909 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
910 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
911 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
912 RHSBB = RHSR.first->second;
913 } else {
914 RHSBB = new MachineBasicBlock(LLVMBB);
915 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
916 }
917 // Create a CaseBlock record representing a conditional branch to
918 // the LHS node if the value being switched on SV is less than C.
919 // Otherwise, branch to LHS.
920 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
921 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
922 if (CR.CaseBB == CurMBB)
923 visitSwitchCase(CB);
924 else {
925 SwitchCases.push_back(CB);
926 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
927 }
928 }
929 }
930}
931
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000932void SelectionDAGLowering::visitSub(User &I) {
933 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000934 if (I.getType()->isFloatingPoint()) {
935 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
936 if (CFP->isExactlyValue(-0.0)) {
937 SDOperand Op2 = getValue(I.getOperand(1));
938 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
939 return;
940 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000941 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000942 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000943}
944
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000945void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
946 unsigned VecOp) {
947 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000948 SDOperand Op1 = getValue(I.getOperand(0));
949 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000950
Chris Lattnerb67eb912005-11-19 18:40:42 +0000951 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000952 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
953 } else if (Ty->isFloatingPoint()) {
954 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
955 } else {
956 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattnerc7029802006-03-18 01:44:44 +0000957 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
958 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
959 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000960 }
Nate Begemane21ea612005-11-18 07:42:56 +0000961}
Chris Lattner2c49f272005-01-19 22:31:21 +0000962
Nate Begemane21ea612005-11-18 07:42:56 +0000963void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
964 SDOperand Op1 = getValue(I.getOperand(0));
965 SDOperand Op2 = getValue(I.getOperand(1));
966
967 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
968
Chris Lattner1c08c712005-01-07 07:47:53 +0000969 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
970}
971
972void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
973 ISD::CondCode UnsignedOpcode) {
974 SDOperand Op1 = getValue(I.getOperand(0));
975 SDOperand Op2 = getValue(I.getOperand(1));
976 ISD::CondCode Opcode = SignedOpcode;
977 if (I.getOperand(0)->getType()->isUnsigned())
978 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000979 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000980}
981
982void SelectionDAGLowering::visitSelect(User &I) {
983 SDOperand Cond = getValue(I.getOperand(0));
984 SDOperand TrueVal = getValue(I.getOperand(1));
985 SDOperand FalseVal = getValue(I.getOperand(2));
986 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
987 TrueVal, FalseVal));
988}
989
990void SelectionDAGLowering::visitCast(User &I) {
991 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +0000992 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000993 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +0000994
Chris Lattnere25ca692006-03-22 20:09:35 +0000995 if (DestVT == MVT::Vector) {
996 // This is a cast to a vector from something else. This is always a bit
997 // convert. Get information about the input vector.
998 const PackedType *DestTy = cast<PackedType>(I.getType());
999 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1000 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1001 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1002 DAG.getValueType(EltVT)));
1003 } else if (SrcVT == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001004 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001005 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +00001006 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001007 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +00001008 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001009 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001010 } else if (isInteger(SrcVT)) {
1011 if (isInteger(DestVT)) { // Int -> Int cast
1012 if (DestVT < SrcVT) // Truncating cast?
1013 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001014 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001015 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001016 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001017 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner7e358902006-03-22 22:20:49 +00001018 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001019 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001020 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001021 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001022 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001023 } else {
1024 assert(0 && "Unknown cast!");
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001025 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001026 } else if (isFloatingPoint(SrcVT)) {
1027 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1028 if (DestVT < SrcVT) // Rounding cast?
1029 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001030 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001031 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001032 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001033 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001034 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001035 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001036 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001037 } else {
1038 assert(0 && "Unknown cast!");
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001039 }
1040 } else {
Chris Lattnere25ca692006-03-22 20:09:35 +00001041 assert(SrcVT == MVT::Vector && "Unknown cast!");
1042 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1043 // This is a cast from a vector to something else. This is always a bit
1044 // convert. Get information about the input vector.
1045 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner1c08c712005-01-07 07:47:53 +00001046 }
1047}
1048
Chris Lattner2bbd8102006-03-29 00:11:43 +00001049void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001050 SDOperand InVec = getValue(I.getOperand(0));
1051 SDOperand InVal = getValue(I.getOperand(1));
1052 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1053 getValue(I.getOperand(2)));
1054
Chris Lattner2332b9f2006-03-19 01:17:20 +00001055 SDOperand Num = *(InVec.Val->op_end()-2);
1056 SDOperand Typ = *(InVec.Val->op_end()-1);
1057 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1058 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001059}
1060
Chris Lattner2bbd8102006-03-29 00:11:43 +00001061void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001062 SDOperand InVec = getValue(I.getOperand(0));
1063 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1064 getValue(I.getOperand(1)));
1065 SDOperand Typ = *(InVec.Val->op_end()-1);
1066 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1067 TLI.getValueType(I.getType()), InVec, InIdx));
1068}
Chris Lattnerc7029802006-03-18 01:44:44 +00001069
Chris Lattner1c08c712005-01-07 07:47:53 +00001070void SelectionDAGLowering::visitGetElementPtr(User &I) {
1071 SDOperand N = getValue(I.getOperand(0));
1072 const Type *Ty = I.getOperand(0)->getType();
1073 const Type *UIntPtrTy = TD.getIntPtrType();
1074
1075 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1076 OI != E; ++OI) {
1077 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001078 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001079 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1080 if (Field) {
1081 // N = N + Offset
1082 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1083 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001084 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001085 }
1086 Ty = StTy->getElementType(Field);
1087 } else {
1088 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001089
Chris Lattner7c0104b2005-11-09 04:45:33 +00001090 // If this is a constant subscript, handle it quickly.
1091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1092 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +00001093
Chris Lattner7c0104b2005-11-09 04:45:33 +00001094 uint64_t Offs;
1095 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1096 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1097 else
1098 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1099 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1100 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001101 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001102
1103 // N = N + Idx * ElementSize;
1104 uint64_t ElementSize = TD.getTypeSize(Ty);
1105 SDOperand IdxN = getValue(Idx);
1106
1107 // If the index is smaller or larger than intptr_t, truncate or extend
1108 // it.
1109 if (IdxN.getValueType() < N.getValueType()) {
1110 if (Idx->getType()->isSigned())
1111 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1112 else
1113 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1114 } else if (IdxN.getValueType() > N.getValueType())
1115 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1116
1117 // If this is a multiply by a power of two, turn it into a shl
1118 // immediately. This is a very common case.
1119 if (isPowerOf2_64(ElementSize)) {
1120 unsigned Amt = Log2_64(ElementSize);
1121 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001122 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001123 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1124 continue;
1125 }
1126
1127 SDOperand Scale = getIntPtrConstant(ElementSize);
1128 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1129 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001130 }
1131 }
1132 setValue(&I, N);
1133}
1134
1135void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1136 // If this is a fixed sized alloca in the entry block of the function,
1137 // allocate it statically on the stack.
1138 if (FuncInfo.StaticAllocaMap.count(&I))
1139 return; // getValue will auto-populate this.
1140
1141 const Type *Ty = I.getAllocatedType();
1142 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +00001143 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1144 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001145
1146 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001147 MVT::ValueType IntPtr = TLI.getPointerTy();
1148 if (IntPtr < AllocSize.getValueType())
1149 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1150 else if (IntPtr > AllocSize.getValueType())
1151 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001152
Chris Lattner68cd65e2005-01-22 23:04:37 +00001153 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001154 getIntPtrConstant(TySize));
1155
1156 // Handle alignment. If the requested alignment is less than or equal to the
1157 // stack alignment, ignore it and round the size of the allocation up to the
1158 // stack alignment size. If the size is greater than the stack alignment, we
1159 // note this in the DYNAMIC_STACKALLOC node.
1160 unsigned StackAlign =
1161 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1162 if (Align <= StackAlign) {
1163 Align = 0;
1164 // Add SA-1 to the size.
1165 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1166 getIntPtrConstant(StackAlign-1));
1167 // Mask out the low bits for alignment purposes.
1168 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1169 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1170 }
1171
Chris Lattneradf6c2a2005-05-14 07:29:57 +00001172 std::vector<MVT::ValueType> VTs;
1173 VTs.push_back(AllocSize.getValueType());
1174 VTs.push_back(MVT::Other);
1175 std::vector<SDOperand> Ops;
1176 Ops.push_back(getRoot());
1177 Ops.push_back(AllocSize);
1178 Ops.push_back(getIntPtrConstant(Align));
1179 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +00001180 DAG.setRoot(setValue(&I, DSA).getValue(1));
1181
1182 // Inform the Frame Information that we have just allocated a variable-sized
1183 // object.
1184 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1185}
1186
Chris Lattner1c08c712005-01-07 07:47:53 +00001187void SelectionDAGLowering::visitLoad(LoadInst &I) {
1188 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001189
Chris Lattnerd3948112005-01-17 22:19:26 +00001190 SDOperand Root;
1191 if (I.isVolatile())
1192 Root = getRoot();
1193 else {
1194 // Do not serialize non-volatile loads against each other.
1195 Root = DAG.getRoot();
1196 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001197
1198 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1199 Root, I.isVolatile()));
1200}
1201
1202SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1203 SDOperand SrcValue, SDOperand Root,
1204 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001205 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001206 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001207 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattnerc7029802006-03-18 01:44:44 +00001208 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001209 } else {
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001210 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001211 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001212
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001213 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001214 DAG.setRoot(L.getValue(1));
1215 else
1216 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001217
1218 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001219}
1220
1221
1222void SelectionDAGLowering::visitStore(StoreInst &I) {
1223 Value *SrcV = I.getOperand(0);
1224 SDOperand Src = getValue(SrcV);
1225 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +00001226 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +00001227 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001228}
1229
Chris Lattner0eade312006-03-24 02:22:33 +00001230/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1231/// access memory and has no other side effects at all.
1232static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1233#define GET_NO_MEMORY_INTRINSICS
1234#include "llvm/Intrinsics.gen"
1235#undef GET_NO_MEMORY_INTRINSICS
1236 return false;
1237}
1238
1239/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1240/// node.
1241void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1242 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001243 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001244
1245 // Build the operand list.
1246 std::vector<SDOperand> Ops;
1247 if (HasChain) // If this intrinsic has side-effects, chainify it.
1248 Ops.push_back(getRoot());
1249
1250 // Add the intrinsic ID as an integer operand.
1251 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1252
1253 // Add all operands of the call to the operand list.
1254 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1255 SDOperand Op = getValue(I.getOperand(i));
1256
1257 // If this is a vector type, force it to the right packed type.
1258 if (Op.getValueType() == MVT::Vector) {
1259 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1260 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1261
1262 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1263 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1264 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1265 }
1266
1267 assert(TLI.isTypeLegal(Op.getValueType()) &&
1268 "Intrinsic uses a non-legal type?");
1269 Ops.push_back(Op);
1270 }
1271
1272 std::vector<MVT::ValueType> VTs;
1273 if (I.getType() != Type::VoidTy) {
1274 MVT::ValueType VT = TLI.getValueType(I.getType());
1275 if (VT == MVT::Vector) {
1276 const PackedType *DestTy = cast<PackedType>(I.getType());
1277 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1278
1279 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1280 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1281 }
1282
1283 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1284 VTs.push_back(VT);
1285 }
1286 if (HasChain)
1287 VTs.push_back(MVT::Other);
1288
1289 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001290 SDOperand Result;
1291 if (!HasChain)
1292 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1293 else if (I.getType() != Type::VoidTy)
1294 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1295 else
1296 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1297
Chris Lattner0eade312006-03-24 02:22:33 +00001298 if (HasChain)
1299 DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1300 if (I.getType() != Type::VoidTy) {
1301 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1302 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1303 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1304 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1305 DAG.getValueType(EVT));
1306 }
1307 setValue(&I, Result);
1308 }
1309}
1310
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001311/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1312/// we want to emit this as a call to a named external function, return the name
1313/// otherwise lower it and return null.
1314const char *
1315SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1316 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001317 default:
1318 // By default, turn this into a target intrinsic node.
1319 visitTargetIntrinsic(I, Intrinsic);
1320 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001321 case Intrinsic::vastart: visitVAStart(I); return 0;
1322 case Intrinsic::vaend: visitVAEnd(I); return 0;
1323 case Intrinsic::vacopy: visitVACopy(I); return 0;
1324 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1325 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1326 case Intrinsic::setjmp:
1327 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1328 break;
1329 case Intrinsic::longjmp:
1330 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1331 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001332 case Intrinsic::memcpy_i32:
1333 case Intrinsic::memcpy_i64:
1334 visitMemIntrinsic(I, ISD::MEMCPY);
1335 return 0;
1336 case Intrinsic::memset_i32:
1337 case Intrinsic::memset_i64:
1338 visitMemIntrinsic(I, ISD::MEMSET);
1339 return 0;
1340 case Intrinsic::memmove_i32:
1341 case Intrinsic::memmove_i64:
1342 visitMemIntrinsic(I, ISD::MEMMOVE);
1343 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001344
Chris Lattner86cb6432005-12-13 17:40:33 +00001345 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001346 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001347 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001348 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskeyce72b172006-02-11 01:01:30 +00001349 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +00001350
Jim Laskeyce72b172006-02-11 01:01:30 +00001351 Ops.push_back(getRoot());
Jim Laskey43970fe2006-03-23 18:06:46 +00001352 Ops.push_back(getValue(SPI.getLineValue()));
1353 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner36ce6912005-11-29 06:21:05 +00001354
Jim Laskey43970fe2006-03-23 18:06:46 +00001355 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001356 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001357 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1358
Jim Laskeyce72b172006-02-11 01:01:30 +00001359 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1360 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1361
Jim Laskey43970fe2006-03-23 18:06:46 +00001362 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +00001363 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001364
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001365 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001366 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001367 case Intrinsic::dbg_region_start: {
1368 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1369 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001370 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001371 std::vector<SDOperand> Ops;
1372
1373 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1374
1375 Ops.push_back(getRoot());
1376 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1377
1378 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1379 }
1380
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001381 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001382 }
1383 case Intrinsic::dbg_region_end: {
1384 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1385 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001386 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001387 std::vector<SDOperand> Ops;
1388
1389 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1390
1391 Ops.push_back(getRoot());
1392 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1393
1394 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1395 }
1396
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001397 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001398 }
1399 case Intrinsic::dbg_func_start: {
1400 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1401 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001402 if (DebugInfo && FSI.getSubprogram() &&
1403 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001404 std::vector<SDOperand> Ops;
1405
1406 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1407
1408 Ops.push_back(getRoot());
1409 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1410
1411 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1412 }
1413
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001414 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001415 }
1416 case Intrinsic::dbg_declare: {
1417 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1418 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00001419 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001420 std::vector<SDOperand> Ops;
1421
Jim Laskey0892cee2006-03-24 09:50:27 +00001422 SDOperand AddressOp = getValue(DI.getAddress());
1423 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001424 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1425 }
1426 }
1427
1428 return 0;
1429 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001430
Reid Spencer0b118202006-01-16 21:12:35 +00001431 case Intrinsic::isunordered_f32:
1432 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001433 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1434 getValue(I.getOperand(2)), ISD::SETUO));
1435 return 0;
1436
Reid Spencer0b118202006-01-16 21:12:35 +00001437 case Intrinsic::sqrt_f32:
1438 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001439 setValue(&I, DAG.getNode(ISD::FSQRT,
1440 getValue(I.getOperand(1)).getValueType(),
1441 getValue(I.getOperand(1))));
1442 return 0;
1443 case Intrinsic::pcmarker: {
1444 SDOperand Tmp = getValue(I.getOperand(1));
1445 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1446 return 0;
1447 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001448 case Intrinsic::readcyclecounter: {
1449 std::vector<MVT::ValueType> VTs;
1450 VTs.push_back(MVT::i64);
1451 VTs.push_back(MVT::Other);
1452 std::vector<SDOperand> Ops;
1453 Ops.push_back(getRoot());
1454 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1455 setValue(&I, Tmp);
1456 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001457 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001458 }
Nate Begemand88fc032006-01-14 03:14:10 +00001459 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001460 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001461 case Intrinsic::bswap_i64:
1462 setValue(&I, DAG.getNode(ISD::BSWAP,
1463 getValue(I.getOperand(1)).getValueType(),
1464 getValue(I.getOperand(1))));
1465 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001466 case Intrinsic::cttz_i8:
1467 case Intrinsic::cttz_i16:
1468 case Intrinsic::cttz_i32:
1469 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001470 setValue(&I, DAG.getNode(ISD::CTTZ,
1471 getValue(I.getOperand(1)).getValueType(),
1472 getValue(I.getOperand(1))));
1473 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001474 case Intrinsic::ctlz_i8:
1475 case Intrinsic::ctlz_i16:
1476 case Intrinsic::ctlz_i32:
1477 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001478 setValue(&I, DAG.getNode(ISD::CTLZ,
1479 getValue(I.getOperand(1)).getValueType(),
1480 getValue(I.getOperand(1))));
1481 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001482 case Intrinsic::ctpop_i8:
1483 case Intrinsic::ctpop_i16:
1484 case Intrinsic::ctpop_i32:
1485 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001486 setValue(&I, DAG.getNode(ISD::CTPOP,
1487 getValue(I.getOperand(1)).getValueType(),
1488 getValue(I.getOperand(1))));
1489 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001490 case Intrinsic::stacksave: {
1491 std::vector<MVT::ValueType> VTs;
1492 VTs.push_back(TLI.getPointerTy());
1493 VTs.push_back(MVT::Other);
1494 std::vector<SDOperand> Ops;
1495 Ops.push_back(getRoot());
1496 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1497 setValue(&I, Tmp);
1498 DAG.setRoot(Tmp.getValue(1));
1499 return 0;
1500 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001501 case Intrinsic::stackrestore: {
1502 SDOperand Tmp = getValue(I.getOperand(1));
1503 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001504 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001505 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001506 case Intrinsic::prefetch:
1507 // FIXME: Currently discarding prefetches.
1508 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001509 }
1510}
1511
1512
Chris Lattner1c08c712005-01-07 07:47:53 +00001513void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001514 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001515 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001516 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001517 if (unsigned IID = F->getIntrinsicID()) {
1518 RenameFn = visitIntrinsicCall(I, IID);
1519 if (!RenameFn)
1520 return;
1521 } else { // Not an LLVM intrinsic.
1522 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001523 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1524 if (I.getNumOperands() == 3 && // Basic sanity checks.
1525 I.getOperand(1)->getType()->isFloatingPoint() &&
1526 I.getType() == I.getOperand(1)->getType() &&
1527 I.getType() == I.getOperand(2)->getType()) {
1528 SDOperand LHS = getValue(I.getOperand(1));
1529 SDOperand RHS = getValue(I.getOperand(2));
1530 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1531 LHS, RHS));
1532 return;
1533 }
1534 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001535 if (I.getNumOperands() == 2 && // Basic sanity checks.
1536 I.getOperand(1)->getType()->isFloatingPoint() &&
1537 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001538 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001539 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1540 return;
1541 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001542 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001543 if (I.getNumOperands() == 2 && // Basic sanity checks.
1544 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001545 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001546 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001547 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1548 return;
1549 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001550 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001551 if (I.getNumOperands() == 2 && // Basic sanity checks.
1552 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001553 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001554 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001555 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1556 return;
1557 }
1558 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001559 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001560 } else if (isa<InlineAsm>(I.getOperand(0))) {
1561 visitInlineAsm(I);
1562 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001563 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001564
Chris Lattner64e14b12005-01-08 22:48:57 +00001565 SDOperand Callee;
1566 if (!RenameFn)
1567 Callee = getValue(I.getOperand(0));
1568 else
1569 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001570 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001571 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001572 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1573 Value *Arg = I.getOperand(i);
1574 SDOperand ArgNode = getValue(Arg);
1575 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1576 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001577
Nate Begeman8e21e712005-03-26 01:29:23 +00001578 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1579 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001580
Chris Lattnercf5734d2005-01-08 19:26:18 +00001581 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001582 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001583 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001584 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001585 setValue(&I, Result.first);
1586 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001587}
1588
Chris Lattner864635a2006-02-22 22:37:12 +00001589SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001590 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001591 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1592 Chain = Val.getValue(1);
1593 Flag = Val.getValue(2);
1594
1595 // If the result was expanded, copy from the top part.
1596 if (Regs.size() > 1) {
1597 assert(Regs.size() == 2 &&
1598 "Cannot expand to more than 2 elts yet!");
1599 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1600 Chain = Val.getValue(1);
1601 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001602 if (DAG.getTargetLoweringInfo().isLittleEndian())
1603 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1604 else
1605 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001606 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001607
Chris Lattner864635a2006-02-22 22:37:12 +00001608 // Otherwise, if the return value was promoted, truncate it to the
1609 // appropriate type.
1610 if (RegVT == ValueVT)
1611 return Val;
1612
1613 if (MVT::isInteger(RegVT))
1614 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1615 else
1616 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1617}
1618
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001619/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1620/// specified value into the registers specified by this object. This uses
1621/// Chain/Flag as the input and updates them for the output Chain/Flag.
1622void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001623 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001624 if (Regs.size() == 1) {
1625 // If there is a single register and the types differ, this must be
1626 // a promotion.
1627 if (RegVT != ValueVT) {
1628 if (MVT::isInteger(RegVT))
1629 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1630 else
1631 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1632 }
1633 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1634 Flag = Chain.getValue(1);
1635 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001636 std::vector<unsigned> R(Regs);
1637 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1638 std::reverse(R.begin(), R.end());
1639
1640 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001641 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1642 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001643 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001644 Flag = Chain.getValue(1);
1645 }
1646 }
1647}
Chris Lattner864635a2006-02-22 22:37:12 +00001648
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001649/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1650/// operand list. This adds the code marker and includes the number of
1651/// values added into it.
1652void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001653 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001654 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1655 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1656 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1657}
Chris Lattner864635a2006-02-22 22:37:12 +00001658
1659/// isAllocatableRegister - If the specified register is safe to allocate,
1660/// i.e. it isn't a stack pointer or some other special register, return the
1661/// register class for the register. Otherwise, return null.
1662static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001663isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1664 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001665 MVT::ValueType FoundVT = MVT::Other;
1666 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001667 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1668 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001669 MVT::ValueType ThisVT = MVT::Other;
1670
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001671 const TargetRegisterClass *RC = *RCI;
1672 // If none of the the value types for this register class are valid, we
1673 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001674 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1675 I != E; ++I) {
1676 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001677 // If we have already found this register in a different register class,
1678 // choose the one with the largest VT specified. For example, on
1679 // PowerPC, we favor f64 register classes over f32.
1680 if (FoundVT == MVT::Other ||
1681 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1682 ThisVT = *I;
1683 break;
1684 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001685 }
1686 }
1687
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001688 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001689
Chris Lattner864635a2006-02-22 22:37:12 +00001690 // NOTE: This isn't ideal. In particular, this might allocate the
1691 // frame pointer in functions that need it (due to them not being taken
1692 // out of allocation, because a variable sized allocation hasn't been seen
1693 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001694 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1695 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001696 if (*I == Reg) {
1697 // We found a matching register class. Keep looking at others in case
1698 // we find one with larger registers that this physreg is also in.
1699 FoundRC = RC;
1700 FoundVT = ThisVT;
1701 break;
1702 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001703 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001704 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00001705}
1706
1707RegsForValue SelectionDAGLowering::
1708GetRegistersForValue(const std::string &ConstrCode,
1709 MVT::ValueType VT, bool isOutReg, bool isInReg,
1710 std::set<unsigned> &OutputRegs,
1711 std::set<unsigned> &InputRegs) {
1712 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1713 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1714 std::vector<unsigned> Regs;
1715
1716 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1717 MVT::ValueType RegVT;
1718 MVT::ValueType ValueVT = VT;
1719
1720 if (PhysReg.first) {
1721 if (VT == MVT::Other)
1722 ValueVT = *PhysReg.second->vt_begin();
1723 RegVT = VT;
1724
1725 // This is a explicit reference to a physical register.
1726 Regs.push_back(PhysReg.first);
1727
1728 // If this is an expanded reference, add the rest of the regs to Regs.
1729 if (NumRegs != 1) {
1730 RegVT = *PhysReg.second->vt_begin();
1731 TargetRegisterClass::iterator I = PhysReg.second->begin();
1732 TargetRegisterClass::iterator E = PhysReg.second->end();
1733 for (; *I != PhysReg.first; ++I)
1734 assert(I != E && "Didn't find reg!");
1735
1736 // Already added the first reg.
1737 --NumRegs; ++I;
1738 for (; NumRegs; --NumRegs, ++I) {
1739 assert(I != E && "Ran out of registers to allocate!");
1740 Regs.push_back(*I);
1741 }
1742 }
1743 return RegsForValue(Regs, RegVT, ValueVT);
1744 }
1745
1746 // This is a reference to a register class. Allocate NumRegs consecutive,
1747 // available, registers from the class.
1748 std::vector<unsigned> RegClassRegs =
1749 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1750
1751 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1752 MachineFunction &MF = *CurMBB->getParent();
1753 unsigned NumAllocated = 0;
1754 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1755 unsigned Reg = RegClassRegs[i];
1756 // See if this register is available.
1757 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1758 (isInReg && InputRegs.count(Reg))) { // Already used.
1759 // Make sure we find consecutive registers.
1760 NumAllocated = 0;
1761 continue;
1762 }
1763
1764 // Check to see if this register is allocatable (i.e. don't give out the
1765 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001766 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001767 if (!RC) {
1768 // Make sure we find consecutive registers.
1769 NumAllocated = 0;
1770 continue;
1771 }
1772
1773 // Okay, this register is good, we can use it.
1774 ++NumAllocated;
1775
1776 // If we allocated enough consecutive
1777 if (NumAllocated == NumRegs) {
1778 unsigned RegStart = (i-NumAllocated)+1;
1779 unsigned RegEnd = i+1;
1780 // Mark all of the allocated registers used.
1781 for (unsigned i = RegStart; i != RegEnd; ++i) {
1782 unsigned Reg = RegClassRegs[i];
1783 Regs.push_back(Reg);
1784 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1785 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1786 }
1787
1788 return RegsForValue(Regs, *RC->vt_begin(), VT);
1789 }
1790 }
1791
1792 // Otherwise, we couldn't allocate enough registers for this.
1793 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001794}
1795
Chris Lattner864635a2006-02-22 22:37:12 +00001796
Chris Lattnerce7518c2006-01-26 22:24:51 +00001797/// visitInlineAsm - Handle a call to an InlineAsm object.
1798///
1799void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1800 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1801
1802 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1803 MVT::Other);
1804
1805 // Note, we treat inline asms both with and without side-effects as the same.
1806 // If an inline asm doesn't have side effects and doesn't access memory, we
1807 // could not choose to not chain it.
1808 bool hasSideEffects = IA->hasSideEffects();
1809
Chris Lattner2cc2f662006-02-01 01:28:23 +00001810 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001811 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001812
1813 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1814 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1815 /// if it is a def of that register.
1816 std::vector<SDOperand> AsmNodeOperands;
1817 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1818 AsmNodeOperands.push_back(AsmStr);
1819
1820 SDOperand Chain = getRoot();
1821 SDOperand Flag;
1822
Chris Lattner4e4b5762006-02-01 18:59:47 +00001823 // We fully assign registers here at isel time. This is not optimal, but
1824 // should work. For register classes that correspond to LLVM classes, we
1825 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1826 // over the constraints, collecting fixed registers that we know we can't use.
1827 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001828 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001829 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1830 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1831 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001832
Chris Lattner1efa40f2006-02-22 00:56:39 +00001833 MVT::ValueType OpVT;
1834
1835 // Compute the value type for each operand and add it to ConstraintVTs.
1836 switch (Constraints[i].Type) {
1837 case InlineAsm::isOutput:
1838 if (!Constraints[i].isIndirectOutput) {
1839 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1840 OpVT = TLI.getValueType(I.getType());
1841 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001842 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001843 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1844 OpNum++; // Consumes a call operand.
1845 }
1846 break;
1847 case InlineAsm::isInput:
1848 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1849 OpNum++; // Consumes a call operand.
1850 break;
1851 case InlineAsm::isClobber:
1852 OpVT = MVT::Other;
1853 break;
1854 }
1855
1856 ConstraintVTs.push_back(OpVT);
1857
Chris Lattner864635a2006-02-22 22:37:12 +00001858 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1859 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001860
Chris Lattner864635a2006-02-22 22:37:12 +00001861 // Build a list of regs that this operand uses. This always has a single
1862 // element for promoted/expanded operands.
1863 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1864 false, false,
1865 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001866
1867 switch (Constraints[i].Type) {
1868 case InlineAsm::isOutput:
1869 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001870 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001871 // If this is an early-clobber output, it cannot be assigned to the same
1872 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001873 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001874 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001875 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001876 case InlineAsm::isInput:
1877 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001878 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001879 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001880 case InlineAsm::isClobber:
1881 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001882 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1883 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001884 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001885 }
1886 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001887
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001888 // Loop over all of the inputs, copying the operand values into the
1889 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001890 RegsForValue RetValRegs;
1891 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001892 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001893
Chris Lattner6656dd12006-01-31 02:03:41 +00001894 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001895 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1896 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001897
Chris Lattner2cc2f662006-02-01 01:28:23 +00001898 switch (Constraints[i].Type) {
1899 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001900 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1901 if (ConstraintCode.size() == 1) // not a physreg name.
1902 CTy = TLI.getConstraintType(ConstraintCode[0]);
1903
1904 if (CTy == TargetLowering::C_Memory) {
1905 // Memory output.
1906 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1907
1908 // Check that the operand (the address to store to) isn't a float.
1909 if (!MVT::isInteger(InOperandVal.getValueType()))
1910 assert(0 && "MATCH FAIL!");
1911
1912 if (!Constraints[i].isIndirectOutput)
1913 assert(0 && "MATCH FAIL!");
1914
1915 OpNum++; // Consumes a call operand.
1916
1917 // Extend/truncate to the right pointer type if needed.
1918 MVT::ValueType PtrType = TLI.getPointerTy();
1919 if (InOperandVal.getValueType() < PtrType)
1920 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1921 else if (InOperandVal.getValueType() > PtrType)
1922 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1923
1924 // Add information to the INLINEASM node to know about this output.
1925 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1926 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1927 AsmNodeOperands.push_back(InOperandVal);
1928 break;
1929 }
1930
1931 // Otherwise, this is a register output.
1932 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1933
Chris Lattner864635a2006-02-22 22:37:12 +00001934 // If this is an early-clobber output, or if there is an input
1935 // constraint that matches this, we need to reserve the input register
1936 // so no other inputs allocate to it.
1937 bool UsesInputRegister = false;
1938 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1939 UsesInputRegister = true;
1940
1941 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001942 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001943 RegsForValue Regs =
1944 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1945 true, UsesInputRegister,
1946 OutputRegs, InputRegs);
1947 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001948
Chris Lattner2cc2f662006-02-01 01:28:23 +00001949 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001950 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001951 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001952 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001953 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001954 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001955 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1956 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001957 OpNum++; // Consumes a call operand.
1958 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001959
1960 // Add information to the INLINEASM node to know that this register is
1961 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001962 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001963 break;
1964 }
1965 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001966 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001967 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001968
Chris Lattner2223aea2006-02-02 00:25:23 +00001969 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1970 // If this is required to match an output register we have already set,
1971 // just use its register.
1972 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001973
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001974 // Scan until we find the definition we already emitted of this operand.
1975 // When we find it, create a RegsForValue operand.
1976 unsigned CurOp = 2; // The first operand.
1977 for (; OperandNo; --OperandNo) {
1978 // Advance to the next operand.
1979 unsigned NumOps =
1980 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1981 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1982 "Skipped past definitions?");
1983 CurOp += (NumOps>>3)+1;
1984 }
1985
1986 unsigned NumOps =
1987 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1988 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1989 "Skipped past definitions?");
1990
1991 // Add NumOps>>3 registers to MatchedRegs.
1992 RegsForValue MatchedRegs;
1993 MatchedRegs.ValueVT = InOperandVal.getValueType();
1994 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1995 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1996 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1997 MatchedRegs.Regs.push_back(Reg);
1998 }
1999
2000 // Use the produced MatchedRegs object to
2001 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2002 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002003 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002004 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002005
2006 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2007 if (ConstraintCode.size() == 1) // not a physreg name.
2008 CTy = TLI.getConstraintType(ConstraintCode[0]);
2009
2010 if (CTy == TargetLowering::C_Other) {
2011 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2012 assert(0 && "MATCH FAIL!");
2013
2014 // Add information to the INLINEASM node to know about this input.
2015 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2016 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2017 AsmNodeOperands.push_back(InOperandVal);
2018 break;
2019 } else if (CTy == TargetLowering::C_Memory) {
2020 // Memory input.
2021
2022 // Check that the operand isn't a float.
2023 if (!MVT::isInteger(InOperandVal.getValueType()))
2024 assert(0 && "MATCH FAIL!");
2025
2026 // Extend/truncate to the right pointer type if needed.
2027 MVT::ValueType PtrType = TLI.getPointerTy();
2028 if (InOperandVal.getValueType() < PtrType)
2029 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2030 else if (InOperandVal.getValueType() > PtrType)
2031 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2032
2033 // Add information to the INLINEASM node to know about this input.
2034 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2035 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2036 AsmNodeOperands.push_back(InOperandVal);
2037 break;
2038 }
2039
2040 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2041
2042 // Copy the input into the appropriate registers.
2043 RegsForValue InRegs =
2044 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2045 false, true, OutputRegs, InputRegs);
2046 // FIXME: should be match fail.
2047 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2048
2049 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2050
2051 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002052 break;
2053 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002054 case InlineAsm::isClobber: {
2055 RegsForValue ClobberedRegs =
2056 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2057 OutputRegs, InputRegs);
2058 // Add the clobbered value to the operand list, so that the register
2059 // allocator is aware that the physreg got clobbered.
2060 if (!ClobberedRegs.Regs.empty())
2061 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002062 break;
2063 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002064 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002065 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002066
2067 // Finish up input operands.
2068 AsmNodeOperands[0] = Chain;
2069 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2070
2071 std::vector<MVT::ValueType> VTs;
2072 VTs.push_back(MVT::Other);
2073 VTs.push_back(MVT::Flag);
2074 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2075 Flag = Chain.getValue(1);
2076
Chris Lattner6656dd12006-01-31 02:03:41 +00002077 // If this asm returns a register value, copy the result from that register
2078 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002079 if (!RetValRegs.Regs.empty())
2080 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002081
Chris Lattner6656dd12006-01-31 02:03:41 +00002082 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2083
2084 // Process indirect outputs, first output all of the flagged copies out of
2085 // physregs.
2086 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002087 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002088 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002089 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2090 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002091 }
2092
2093 // Emit the non-flagged stores from the physregs.
2094 std::vector<SDOperand> OutChains;
2095 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2096 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2097 StoresToEmit[i].first,
2098 getValue(StoresToEmit[i].second),
2099 DAG.getSrcValue(StoresToEmit[i].second)));
2100 if (!OutChains.empty())
2101 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00002102 DAG.setRoot(Chain);
2103}
2104
2105
Chris Lattner1c08c712005-01-07 07:47:53 +00002106void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2107 SDOperand Src = getValue(I.getOperand(0));
2108
2109 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002110
2111 if (IntPtr < Src.getValueType())
2112 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2113 else if (IntPtr > Src.getValueType())
2114 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002115
2116 // Scale the source by the type size.
2117 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2118 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2119 Src, getIntPtrConstant(ElementSize));
2120
2121 std::vector<std::pair<SDOperand, const Type*> > Args;
2122 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002123
2124 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002125 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002126 DAG.getExternalSymbol("malloc", IntPtr),
2127 Args, DAG);
2128 setValue(&I, Result.first); // Pointers always fit in registers
2129 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002130}
2131
2132void SelectionDAGLowering::visitFree(FreeInst &I) {
2133 std::vector<std::pair<SDOperand, const Type*> > Args;
2134 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2135 TLI.getTargetData().getIntPtrType()));
2136 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002137 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002138 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002139 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2140 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002141}
2142
Chris Lattner025c39b2005-08-26 20:54:47 +00002143// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2144// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2145// instructions are special in various ways, which require special support to
2146// insert. The specified MachineInstr is created but not inserted into any
2147// basic blocks, and the scheduler passes ownership of it to this method.
2148MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2149 MachineBasicBlock *MBB) {
2150 std::cerr << "If a target marks an instruction with "
2151 "'usesCustomDAGSchedInserter', it must implement "
2152 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2153 abort();
2154 return 0;
2155}
2156
Chris Lattner39ae3622005-01-09 00:00:49 +00002157void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002158 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2159 getValue(I.getOperand(1)),
2160 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002161}
2162
2163void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002164 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2165 getValue(I.getOperand(0)),
2166 DAG.getSrcValue(I.getOperand(0)));
2167 setValue(&I, V);
2168 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002169}
2170
2171void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002172 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2173 getValue(I.getOperand(1)),
2174 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002175}
2176
2177void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002178 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2179 getValue(I.getOperand(1)),
2180 getValue(I.getOperand(2)),
2181 DAG.getSrcValue(I.getOperand(1)),
2182 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002183}
2184
Chris Lattner39ae3622005-01-09 00:00:49 +00002185// It is always conservatively correct for llvm.returnaddress and
2186// llvm.frameaddress to return 0.
2187std::pair<SDOperand, SDOperand>
2188TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2189 unsigned Depth, SelectionDAG &DAG) {
2190 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00002191}
2192
Chris Lattner50381b62005-05-14 05:50:48 +00002193SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00002194 assert(0 && "LowerOperation not implemented for this target!");
2195 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00002196 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00002197}
2198
Nate Begeman0aed7842006-01-28 03:14:31 +00002199SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2200 SelectionDAG &DAG) {
2201 assert(0 && "CustomPromoteOperation not implemented for this target!");
2202 abort();
2203 return SDOperand();
2204}
2205
Chris Lattner39ae3622005-01-09 00:00:49 +00002206void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2207 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2208 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00002209 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00002210 setValue(&I, Result.first);
2211 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002212}
2213
Evan Cheng74d0aa92006-02-15 21:59:04 +00002214/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00002215/// operand.
2216static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00002217 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002218 MVT::ValueType CurVT = VT;
2219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2220 uint64_t Val = C->getValue() & 255;
2221 unsigned Shift = 8;
2222 while (CurVT != MVT::i8) {
2223 Val = (Val << Shift) | Val;
2224 Shift <<= 1;
2225 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002226 }
2227 return DAG.getConstant(Val, VT);
2228 } else {
2229 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2230 unsigned Shift = 8;
2231 while (CurVT != MVT::i8) {
2232 Value =
2233 DAG.getNode(ISD::OR, VT,
2234 DAG.getNode(ISD::SHL, VT, Value,
2235 DAG.getConstant(Shift, MVT::i8)), Value);
2236 Shift <<= 1;
2237 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002238 }
2239
2240 return Value;
2241 }
2242}
2243
Evan Cheng74d0aa92006-02-15 21:59:04 +00002244/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2245/// used when a memcpy is turned into a memset when the source is a constant
2246/// string ptr.
2247static SDOperand getMemsetStringVal(MVT::ValueType VT,
2248 SelectionDAG &DAG, TargetLowering &TLI,
2249 std::string &Str, unsigned Offset) {
2250 MVT::ValueType CurVT = VT;
2251 uint64_t Val = 0;
2252 unsigned MSB = getSizeInBits(VT) / 8;
2253 if (TLI.isLittleEndian())
2254 Offset = Offset + MSB - 1;
2255 for (unsigned i = 0; i != MSB; ++i) {
2256 Val = (Val << 8) | Str[Offset];
2257 Offset += TLI.isLittleEndian() ? -1 : 1;
2258 }
2259 return DAG.getConstant(Val, VT);
2260}
2261
Evan Cheng1db92f92006-02-14 08:22:34 +00002262/// getMemBasePlusOffset - Returns base and offset node for the
2263static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2264 SelectionDAG &DAG, TargetLowering &TLI) {
2265 MVT::ValueType VT = Base.getValueType();
2266 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2267}
2268
Evan Chengc4f8eee2006-02-14 20:12:38 +00002269/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00002270/// to replace the memset / memcpy is below the threshold. It also returns the
2271/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00002272static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2273 unsigned Limit, uint64_t Size,
2274 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002275 MVT::ValueType VT;
2276
2277 if (TLI.allowsUnalignedMemoryAccesses()) {
2278 VT = MVT::i64;
2279 } else {
2280 switch (Align & 7) {
2281 case 0:
2282 VT = MVT::i64;
2283 break;
2284 case 4:
2285 VT = MVT::i32;
2286 break;
2287 case 2:
2288 VT = MVT::i16;
2289 break;
2290 default:
2291 VT = MVT::i8;
2292 break;
2293 }
2294 }
2295
Evan Cheng80e89d72006-02-14 09:11:59 +00002296 MVT::ValueType LVT = MVT::i64;
2297 while (!TLI.isTypeLegal(LVT))
2298 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2299 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00002300
Evan Cheng80e89d72006-02-14 09:11:59 +00002301 if (VT > LVT)
2302 VT = LVT;
2303
Evan Chengdea72452006-02-14 23:05:54 +00002304 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00002305 while (Size != 0) {
2306 unsigned VTSize = getSizeInBits(VT) / 8;
2307 while (VTSize > Size) {
2308 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002309 VTSize >>= 1;
2310 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002311 assert(MVT::isInteger(VT));
2312
2313 if (++NumMemOps > Limit)
2314 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00002315 MemOps.push_back(VT);
2316 Size -= VTSize;
2317 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002318
2319 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00002320}
2321
Chris Lattner7041ee32005-01-11 05:56:49 +00002322void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002323 SDOperand Op1 = getValue(I.getOperand(1));
2324 SDOperand Op2 = getValue(I.getOperand(2));
2325 SDOperand Op3 = getValue(I.getOperand(3));
2326 SDOperand Op4 = getValue(I.getOperand(4));
2327 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2328 if (Align == 0) Align = 1;
2329
2330 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2331 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00002332
2333 // Expand memset / memcpy to a series of load / store ops
2334 // if the size operand falls below a certain threshold.
2335 std::vector<SDOperand> OutChains;
2336 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00002337 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00002338 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00002339 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2340 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00002341 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00002342 unsigned Offset = 0;
2343 for (unsigned i = 0; i < NumMemOps; i++) {
2344 MVT::ValueType VT = MemOps[i];
2345 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00002346 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00002347 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2348 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00002349 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2350 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00002351 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00002352 Offset += VTSize;
2353 }
Evan Cheng1db92f92006-02-14 08:22:34 +00002354 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002355 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00002356 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002357 case ISD::MEMCPY: {
2358 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2359 Size->getValue(), Align, TLI)) {
2360 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00002361 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002362 GlobalAddressSDNode *G = NULL;
2363 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00002364 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002365
2366 if (Op2.getOpcode() == ISD::GlobalAddress)
2367 G = cast<GlobalAddressSDNode>(Op2);
2368 else if (Op2.getOpcode() == ISD::ADD &&
2369 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2370 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2371 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00002372 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00002373 }
2374 if (G) {
2375 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00002376 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00002377 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00002378 if (!Str.empty()) {
2379 CopyFromStr = true;
2380 SrcOff += SrcDelta;
2381 }
2382 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00002383 }
2384
Evan Chengc080d6f2006-02-15 01:54:51 +00002385 for (unsigned i = 0; i < NumMemOps; i++) {
2386 MVT::ValueType VT = MemOps[i];
2387 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002388 SDOperand Value, Chain, Store;
2389
Evan Chengcffbb512006-02-16 23:11:42 +00002390 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00002391 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2392 Chain = getRoot();
2393 Store =
2394 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2395 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2396 DAG.getSrcValue(I.getOperand(1), DstOff));
2397 } else {
2398 Value = DAG.getLoad(VT, getRoot(),
2399 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2400 DAG.getSrcValue(I.getOperand(2), SrcOff));
2401 Chain = Value.getValue(1);
2402 Store =
2403 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2404 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2405 DAG.getSrcValue(I.getOperand(1), DstOff));
2406 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002407 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002408 SrcOff += VTSize;
2409 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00002410 }
2411 }
2412 break;
2413 }
2414 }
2415
2416 if (!OutChains.empty()) {
2417 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2418 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00002419 }
2420 }
2421
Chris Lattner7041ee32005-01-11 05:56:49 +00002422 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00002423 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00002424 Ops.push_back(Op1);
2425 Ops.push_back(Op2);
2426 Ops.push_back(Op3);
2427 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00002428 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00002429}
2430
Chris Lattner7041ee32005-01-11 05:56:49 +00002431//===----------------------------------------------------------------------===//
2432// SelectionDAGISel code
2433//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002434
2435unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2436 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2437}
2438
Chris Lattner495a0b52005-08-17 06:37:43 +00002439void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002440 // FIXME: we only modify the CFG to split critical edges. This
2441 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002442}
Chris Lattner1c08c712005-01-07 07:47:53 +00002443
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002444
2445/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2446/// casting to the type of GEPI.
2447static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2448 Value *Ptr, Value *PtrOffset) {
2449 if (V) return V; // Already computed.
2450
2451 BasicBlock::iterator InsertPt;
2452 if (BB == GEPI->getParent()) {
2453 // If insert into the GEP's block, insert right after the GEP.
2454 InsertPt = GEPI;
2455 ++InsertPt;
2456 } else {
2457 // Otherwise, insert at the top of BB, after any PHI nodes
2458 InsertPt = BB->begin();
2459 while (isa<PHINode>(InsertPt)) ++InsertPt;
2460 }
2461
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002462 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2463 // BB so that there is only one value live across basic blocks (the cast
2464 // operand).
2465 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2466 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2467 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2468
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002469 // Add the offset, cast it to the right type.
2470 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2471 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2472 return V = Ptr;
2473}
2474
2475
2476/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2477/// selection, we want to be a bit careful about some things. In particular, if
2478/// we have a GEP instruction that is used in a different block than it is
2479/// defined, the addressing expression of the GEP cannot be folded into loads or
2480/// stores that use it. In this case, decompose the GEP and move constant
2481/// indices into blocks that use it.
2482static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2483 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002484 // If this GEP is only used inside the block it is defined in, there is no
2485 // need to rewrite it.
2486 bool isUsedOutsideDefBB = false;
2487 BasicBlock *DefBB = GEPI->getParent();
2488 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2489 UI != E; ++UI) {
2490 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2491 isUsedOutsideDefBB = true;
2492 break;
2493 }
2494 }
2495 if (!isUsedOutsideDefBB) return;
2496
2497 // If this GEP has no non-zero constant indices, there is nothing we can do,
2498 // ignore it.
2499 bool hasConstantIndex = false;
2500 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2501 E = GEPI->op_end(); OI != E; ++OI) {
2502 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2503 if (CI->getRawValue()) {
2504 hasConstantIndex = true;
2505 break;
2506 }
2507 }
Chris Lattner3802c252005-12-11 09:05:13 +00002508 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2509 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002510
2511 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2512 // constant offset (which we now know is non-zero) and deal with it later.
2513 uint64_t ConstantOffset = 0;
2514 const Type *UIntPtrTy = TD.getIntPtrType();
2515 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2516 const Type *Ty = GEPI->getOperand(0)->getType();
2517
2518 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2519 E = GEPI->op_end(); OI != E; ++OI) {
2520 Value *Idx = *OI;
2521 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2522 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2523 if (Field)
2524 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2525 Ty = StTy->getElementType(Field);
2526 } else {
2527 Ty = cast<SequentialType>(Ty)->getElementType();
2528
2529 // Handle constant subscripts.
2530 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2531 if (CI->getRawValue() == 0) continue;
2532
2533 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2534 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2535 else
2536 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2537 continue;
2538 }
2539
2540 // Ptr = Ptr + Idx * ElementSize;
2541
2542 // Cast Idx to UIntPtrTy if needed.
2543 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2544
2545 uint64_t ElementSize = TD.getTypeSize(Ty);
2546 // Mask off bits that should not be set.
2547 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2548 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2549
2550 // Multiply by the element size and add to the base.
2551 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2552 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2553 }
2554 }
2555
2556 // Make sure that the offset fits in uintptr_t.
2557 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2558 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2559
2560 // Okay, we have now emitted all of the variable index parts to the BB that
2561 // the GEP is defined in. Loop over all of the using instructions, inserting
2562 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002563 // instruction to use the newly computed value, making GEPI dead. When the
2564 // user is a load or store instruction address, we emit the add into the user
2565 // block, otherwise we use a canonical version right next to the gep (these
2566 // won't be foldable as addresses, so we might as well share the computation).
2567
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002568 std::map<BasicBlock*,Value*> InsertedExprs;
2569 while (!GEPI->use_empty()) {
2570 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002571
2572 // If this use is not foldable into the addressing mode, use a version
2573 // emitted in the GEP block.
2574 Value *NewVal;
2575 if (!isa<LoadInst>(User) &&
2576 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2577 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2578 Ptr, PtrOffset);
2579 } else {
2580 // Otherwise, insert the code in the User's block so it can be folded into
2581 // any users in that block.
2582 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002583 User->getParent(), GEPI,
2584 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002585 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002586 User->replaceUsesOfWith(GEPI, NewVal);
2587 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002588
2589 // Finally, the GEP is dead, remove it.
2590 GEPI->eraseFromParent();
2591}
2592
Chris Lattner1c08c712005-01-07 07:47:53 +00002593bool SelectionDAGISel::runOnFunction(Function &Fn) {
2594 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2595 RegMap = MF.getSSARegMap();
2596 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2597
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002598 // First, split all critical edges for PHI nodes with incoming values that are
2599 // constants, this way the load of the constant into a vreg will not be placed
2600 // into MBBs that are used some other way.
2601 //
2602 // In this pass we also look for GEP instructions that are used across basic
2603 // blocks and rewrites them to improve basic-block-at-a-time selection.
2604 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002605 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2606 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002607 BasicBlock::iterator BBI;
2608 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2610 if (isa<Constant>(PN->getIncomingValue(i)))
2611 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002612
2613 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2614 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2615 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002616 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002617
Chris Lattner1c08c712005-01-07 07:47:53 +00002618 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2619
2620 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2621 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002622
Chris Lattner1c08c712005-01-07 07:47:53 +00002623 return true;
2624}
2625
2626
Chris Lattnerddb870b2005-01-13 17:59:43 +00002627SDOperand SelectionDAGISel::
2628CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002629 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002630 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002631 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002632 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002633
2634 // If this type is not legal, we must make sure to not create an invalid
2635 // register use.
2636 MVT::ValueType SrcVT = Op.getValueType();
2637 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2638 SelectionDAG &DAG = SDL.DAG;
2639 if (SrcVT == DestVT) {
2640 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00002641 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00002642 // Handle copies from generic vectors to registers.
2643 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2644 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2645 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00002646
Chris Lattner70c2a612006-03-31 02:06:56 +00002647 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2648 // MVT::Vector type.
2649 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2650 DAG.getConstant(NE, MVT::i32),
2651 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00002652
Chris Lattner70c2a612006-03-31 02:06:56 +00002653 // Loop over all of the elements of the resultant vector,
2654 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2655 // copying them into output registers.
2656 std::vector<SDOperand> OutChains;
2657 SDOperand Root = SDL.getRoot();
2658 for (unsigned i = 0; i != NE; ++i) {
2659 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2660 Op, DAG.getConstant(i, MVT::i32));
2661 if (PTyElementVT == PTyLegalElementVT) {
2662 // Elements are legal.
2663 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2664 } else if (PTyLegalElementVT > PTyElementVT) {
2665 // Elements are promoted.
2666 if (MVT::isFloatingPoint(PTyLegalElementVT))
2667 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2668 else
2669 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2670 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2671 } else {
2672 // Elements are expanded.
2673 // The src value is expanded into multiple registers.
2674 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2675 Elt, DAG.getConstant(0, MVT::i32));
2676 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2677 Elt, DAG.getConstant(1, MVT::i32));
2678 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2679 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2680 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00002681 }
Chris Lattner70c2a612006-03-31 02:06:56 +00002682 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002683 } else if (SrcVT < DestVT) {
2684 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002685 if (MVT::isFloatingPoint(SrcVT))
2686 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2687 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002688 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002689 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2690 } else {
2691 // The src value is expanded into multiple registers.
2692 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2693 Op, DAG.getConstant(0, MVT::i32));
2694 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2695 Op, DAG.getConstant(1, MVT::i32));
2696 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2697 return DAG.getCopyToReg(Op, Reg+1, Hi);
2698 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002699}
2700
Chris Lattner068a81e2005-01-17 17:15:02 +00002701void SelectionDAGISel::
2702LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2703 std::vector<SDOperand> &UnorderedChains) {
2704 // If this is the entry block, emit arguments.
2705 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002706 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002707 SDOperand OldRoot = SDL.DAG.getRoot();
2708 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002709
Chris Lattnerbf209482005-10-30 19:42:35 +00002710 unsigned a = 0;
2711 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2712 AI != E; ++AI, ++a)
2713 if (!AI->use_empty()) {
2714 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002715
Chris Lattnerbf209482005-10-30 19:42:35 +00002716 // If this argument is live outside of the entry block, insert a copy from
2717 // whereever we got it to the vreg that other BB's will reference it as.
2718 if (FuncInfo.ValueMap.count(AI)) {
2719 SDOperand Copy =
2720 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2721 UnorderedChains.push_back(Copy);
2722 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002723 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002724
2725 // Next, if the function has live ins that need to be copied into vregs,
2726 // emit the copies now, into the top of the block.
2727 MachineFunction &MF = SDL.DAG.getMachineFunction();
2728 if (MF.livein_begin() != MF.livein_end()) {
2729 SSARegMap *RegMap = MF.getSSARegMap();
2730 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2731 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2732 E = MF.livein_end(); LI != E; ++LI)
2733 if (LI->second)
2734 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2735 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002736 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002737
2738 // Finally, if the target has anything special to do, allow it to do so.
2739 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002740}
2741
2742
Chris Lattner1c08c712005-01-07 07:47:53 +00002743void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2744 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00002745 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002746 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002747
2748 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002749
Chris Lattnerbf209482005-10-30 19:42:35 +00002750 // Lower any arguments needed in this block if this is the entry block.
2751 if (LLVMBB == &LLVMBB->getParent()->front())
2752 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002753
2754 BB = FuncInfo.MBBMap[LLVMBB];
2755 SDL.setCurrentBasicBlock(BB);
2756
2757 // Lower all of the non-terminator instructions.
2758 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2759 I != E; ++I)
2760 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00002761
Chris Lattner1c08c712005-01-07 07:47:53 +00002762 // Ensure that all instructions which are used outside of their defining
2763 // blocks are available as virtual registers.
2764 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002765 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002766 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002767 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002768 UnorderedChains.push_back(
2769 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002770 }
2771
2772 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2773 // ensure constants are generated when needed. Remember the virtual registers
2774 // that need to be added to the Machine PHI nodes as input. We cannot just
2775 // directly add them, because expansion might result in multiple MBB's for one
2776 // BB. As such, the start of the BB might correspond to a different MBB than
2777 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002778 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002779
2780 // Emit constants only once even if used by multiple PHI nodes.
2781 std::map<Constant*, unsigned> ConstantsOut;
2782
2783 // Check successor nodes PHI nodes that expect a constant to be available from
2784 // this block.
2785 TerminatorInst *TI = LLVMBB->getTerminator();
2786 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2787 BasicBlock *SuccBB = TI->getSuccessor(succ);
2788 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2789 PHINode *PN;
2790
2791 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2792 // nodes and Machine PHI nodes, but the incoming operands have not been
2793 // emitted yet.
2794 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002795 (PN = dyn_cast<PHINode>(I)); ++I)
2796 if (!PN->use_empty()) {
2797 unsigned Reg;
2798 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2799 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2800 unsigned &RegOut = ConstantsOut[C];
2801 if (RegOut == 0) {
2802 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002803 UnorderedChains.push_back(
2804 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002805 }
2806 Reg = RegOut;
2807 } else {
2808 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002809 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002810 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002811 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2812 "Didn't codegen value into a register!??");
2813 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002814 UnorderedChains.push_back(
2815 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002816 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002817 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002818
Chris Lattnerf44fd882005-01-07 21:34:19 +00002819 // Remember that this register needs to added to the machine PHI node as
2820 // the input for this MBB.
Chris Lattner7e021512006-03-31 02:12:18 +00002821 MVT::ValueType VT = TLI.getValueType(PN->getType());
2822 unsigned NumElements;
2823 if (VT != MVT::Vector)
2824 NumElements = TLI.getNumElements(VT);
2825 else {
2826 MVT::ValueType VT1,VT2;
2827 NumElements =
2828 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
2829 VT1, VT2);
2830 }
Chris Lattnerf44fd882005-01-07 21:34:19 +00002831 for (unsigned i = 0, e = NumElements; i != e; ++i)
2832 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002833 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002834 }
2835 ConstantsOut.clear();
2836
Chris Lattnerddb870b2005-01-13 17:59:43 +00002837 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002838 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002839 SDOperand Root = SDL.getRoot();
2840 if (Root.getOpcode() != ISD::EntryToken) {
2841 unsigned i = 0, e = UnorderedChains.size();
2842 for (; i != e; ++i) {
2843 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2844 if (UnorderedChains[i].Val->getOperand(0) == Root)
2845 break; // Don't add the root if we already indirectly depend on it.
2846 }
2847
2848 if (i == e)
2849 UnorderedChains.push_back(Root);
2850 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002851 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2852 }
2853
Chris Lattner1c08c712005-01-07 07:47:53 +00002854 // Lower the terminator after the copies are emitted.
2855 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002856
Nate Begemanf15485a2006-03-27 01:32:24 +00002857 // Copy over any CaseBlock records that may now exist due to SwitchInst
2858 // lowering.
2859 SwitchCases.clear();
2860 SwitchCases = SDL.SwitchCases;
2861
Chris Lattnera651cf62005-01-17 19:43:36 +00002862 // Make sure the root of the DAG is up-to-date.
2863 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002864}
2865
Nate Begemanf15485a2006-03-27 01:32:24 +00002866void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattneraf21d552005-10-10 16:47:10 +00002867 // Run the DAG combiner in pre-legalize mode.
2868 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002869
Chris Lattner1c08c712005-01-07 07:47:53 +00002870 DEBUG(std::cerr << "Lowered selection DAG:\n");
2871 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002872
Chris Lattner1c08c712005-01-07 07:47:53 +00002873 // Second step, hack on the DAG until it only uses operations and types that
2874 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002875 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00002876
Chris Lattner1c08c712005-01-07 07:47:53 +00002877 DEBUG(std::cerr << "Legalized selection DAG:\n");
2878 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002879
Chris Lattneraf21d552005-10-10 16:47:10 +00002880 // Run the DAG combiner in post-legalize mode.
2881 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002882
Evan Chenga9c20912006-01-21 02:32:06 +00002883 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002884
Chris Lattnera33ef482005-03-30 01:10:47 +00002885 // Third, instruction select all of the operations to machine code, adding the
2886 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002887 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00002888
Chris Lattner1c08c712005-01-07 07:47:53 +00002889 DEBUG(std::cerr << "Selected machine code:\n");
2890 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00002891}
Chris Lattner1c08c712005-01-07 07:47:53 +00002892
Nate Begemanf15485a2006-03-27 01:32:24 +00002893void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2894 FunctionLoweringInfo &FuncInfo) {
2895 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2896 {
2897 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2898 CurDAG = &DAG;
2899
2900 // First step, lower LLVM code to some DAG. This DAG may use operations and
2901 // types that are not supported by the target.
2902 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2903
2904 // Second step, emit the lowered DAG as machine code.
2905 CodeGenAndEmitDAG(DAG);
2906 }
2907
Chris Lattnera33ef482005-03-30 01:10:47 +00002908 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002909 // PHI nodes in successors.
Nate Begemanf15485a2006-03-27 01:32:24 +00002910 if (SwitchCases.empty()) {
2911 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2912 MachineInstr *PHI = PHINodesToUpdate[i].first;
2913 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2914 "This is not a machine PHI node that we are updating!");
2915 PHI->addRegOperand(PHINodesToUpdate[i].second);
2916 PHI->addMachineBasicBlockOperand(BB);
2917 }
2918 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002919 }
Nate Begemanf15485a2006-03-27 01:32:24 +00002920
2921 // If we generated any switch lowering information, build and codegen any
2922 // additional DAGs necessary.
2923 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2924 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2925 CurDAG = &SDAG;
2926 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2927 // Set the current basic block to the mbb we wish to insert the code into
2928 BB = SwitchCases[i].ThisBB;
2929 SDL.setCurrentBasicBlock(BB);
2930 // Emit the code
2931 SDL.visitSwitchCase(SwitchCases[i]);
2932 SDAG.setRoot(SDL.getRoot());
2933 CodeGenAndEmitDAG(SDAG);
2934 // Iterate over the phi nodes, if there is a phi node in a successor of this
2935 // block (for instance, the default block), then add a pair of operands to
2936 // the phi node for this block, as if we were coming from the original
2937 // BB before switch expansion.
2938 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2939 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2940 MachineBasicBlock *PHIBB = PHI->getParent();
2941 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2942 "This is not a machine PHI node that we are updating!");
2943 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2944 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2945 PHI->addMachineBasicBlockOperand(BB);
2946 }
2947 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002948 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002949}
Evan Chenga9c20912006-01-21 02:32:06 +00002950
2951//===----------------------------------------------------------------------===//
2952/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2953/// target node in the graph.
2954void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2955 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002956 ScheduleDAG *SL = NULL;
2957
2958 switch (ISHeuristic) {
2959 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002960 case defaultScheduling:
2961 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2962 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2963 else /* TargetLowering::SchedulingForRegPressure */
2964 SL = createBURRListDAGScheduler(DAG, BB);
2965 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002966 case noScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002967 SL = createBFS_DAGScheduler(DAG, BB);
2968 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002969 case simpleScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002970 SL = createSimpleDAGScheduler(false, DAG, BB);
2971 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002972 case simpleNoItinScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002973 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002974 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002975 case listSchedulingBURR:
2976 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnera5de4842006-03-05 21:10:33 +00002977 break;
Chris Lattner03fc53c2006-03-06 00:22:00 +00002978 case listSchedulingTD:
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002979 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattnera5de4842006-03-05 21:10:33 +00002980 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002981 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002982 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002983 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002984}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002985
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002986HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2987 return new HazardRecognizer();
Chris Lattner03fc53c2006-03-06 00:22:00 +00002988}
2989
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002990/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2991/// by tblgen. Others should not call it.
2992void SelectionDAGISel::
2993SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2994 std::vector<SDOperand> InOps;
2995 std::swap(InOps, Ops);
2996
2997 Ops.push_back(InOps[0]); // input chain.
2998 Ops.push_back(InOps[1]); // input asm string.
2999
3000 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
3001 unsigned i = 2, e = InOps.size();
3002 if (InOps[e-1].getValueType() == MVT::Flag)
3003 --e; // Don't process a flag operand if it is here.
3004
3005 while (i != e) {
3006 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3007 if ((Flags & 7) != 4 /*MEM*/) {
3008 // Just skip over this operand, copying the operands verbatim.
3009 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3010 i += (Flags >> 3) + 1;
3011 } else {
3012 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3013 // Otherwise, this is a memory operand. Ask the target to select it.
3014 std::vector<SDOperand> SelOps;
3015 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3016 std::cerr << "Could not match memory address. Inline asm failure!\n";
3017 exit(1);
3018 }
3019
3020 // Add this to the output node.
3021 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3022 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3023 i += 2;
3024 }
3025 }
3026
3027 // Add the flag input back if present.
3028 if (e != InOps.size())
3029 Ops.push_back(InOps.back());
3030}