blob: b579ebf837aa32fc0717306fdba2f4c1010297ad [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/SelectionDAG.h"
32#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000033#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetFrameInfo.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000040#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
43#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000044#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000046#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000047using namespace llvm;
48
Chris Lattner975f5c92005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000050static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000051ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
53static cl::opt<bool>
54ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000056#else
Evan Cheng739a6a42006-01-21 02:32:06 +000057static const bool ViewISelDAGs = 0;
58static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Chris Lattner5255d042006-03-10 07:49:12 +000061// Scheduling heuristics
62enum SchedHeuristics {
63 defaultScheduling, // Let the target specify its preference.
64 noScheduling, // No scheduling, emit breadth first sequence.
65 simpleScheduling, // Two pass, min. critical path, max. utilization.
66 simpleNoItinScheduling, // Same as above exact using generic latency.
67 listSchedulingBURR, // Bottom up reg reduction list scheduling.
68 listSchedulingTD // Top-down list scheduler.
69};
70
Evan Chengc1e1d972006-01-23 07:01:07 +000071namespace {
72 cl::opt<SchedHeuristics>
73 ISHeuristic(
74 "sched",
75 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000076 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000077 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000078 clEnumValN(defaultScheduling, "default",
79 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000080 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000081 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000082 clEnumValN(simpleScheduling, "simple",
83 "Simple two pass scheduling: minimize critical path "
84 "and maximize processor utilization"),
85 clEnumValN(simpleNoItinScheduling, "simple-noitin",
86 "Simple two pass scheduling: Same as simple "
87 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000088 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000089 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000090 clEnumValN(listSchedulingTD, "list-td",
91 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000092 clEnumValEnd));
93} // namespace
94
Chris Lattner6f87d182006-02-22 22:37:12 +000095namespace {
96 /// RegsForValue - This struct represents the physical registers that a
97 /// particular value is assigned and the type information about the value.
98 /// This is needed because values can be promoted into larger registers and
99 /// expanded into multiple smaller registers than the value.
100 struct RegsForValue {
101 /// Regs - This list hold the register (for legal and promoted values)
102 /// or register set (for expanded values) that the value should be assigned
103 /// to.
104 std::vector<unsigned> Regs;
105
106 /// RegVT - The value type of each register.
107 ///
108 MVT::ValueType RegVT;
109
110 /// ValueVT - The value type of the LLVM value, which may be promoted from
111 /// RegVT or made from merging the two expanded parts.
112 MVT::ValueType ValueVT;
113
114 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
115
116 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117 : RegVT(regvt), ValueVT(valuevt) {
118 Regs.push_back(Reg);
119 }
120 RegsForValue(const std::vector<unsigned> &regs,
121 MVT::ValueType regvt, MVT::ValueType valuevt)
122 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
123 }
124
125 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126 /// this value and returns the result as a ValueVT value. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000129 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000130
131 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132 /// specified value into the registers specified by this object. This uses
133 /// Chain/Flag as the input and updates them for the output Chain/Flag.
134 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000135 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000136
137 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138 /// operand list. This adds the code marker and includes the number of
139 /// values added into it.
140 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000141 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000142 };
143}
Evan Chengc1e1d972006-01-23 07:01:07 +0000144
Chris Lattner7a60d912005-01-07 07:47:53 +0000145namespace llvm {
146 //===--------------------------------------------------------------------===//
147 /// FunctionLoweringInfo - This contains information that is global to a
148 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000149 class FunctionLoweringInfo {
150 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000151 TargetLowering &TLI;
152 Function &Fn;
153 MachineFunction &MF;
154 SSARegMap *RegMap;
155
156 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
157
158 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
160
161 /// ValueMap - Since we emit code for the function a basic block at a time,
162 /// we must remember which virtual registers hold the values for
163 /// cross-basic-block values.
164 std::map<const Value*, unsigned> ValueMap;
165
166 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167 /// the entry block. This allows the allocas to be efficiently referenced
168 /// anywhere in the function.
169 std::map<const AllocaInst*, int> StaticAllocaMap;
170
171 unsigned MakeReg(MVT::ValueType VT) {
172 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
173 }
Misha Brukman835702a2005-04-21 22:36:52 +0000174
Chris Lattner49409cb2006-03-16 19:51:18 +0000175 unsigned CreateRegForValue(const Value *V);
176
Chris Lattner7a60d912005-01-07 07:47:53 +0000177 unsigned InitializeRegForValue(const Value *V) {
178 unsigned &R = ValueMap[V];
179 assert(R == 0 && "Already initialized this value register!");
180 return R = CreateRegForValue(V);
181 }
182 };
183}
184
185/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
186/// PHI nodes or outside of the basic block that defines it.
187static 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)
191 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
192 return true;
193 return false;
194}
195
Chris Lattner6871b232005-10-30 19:42:35 +0000196/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
197/// entry block, return true.
198static bool isOnlyUsedInEntryBlock(Argument *A) {
199 BasicBlock *Entry = A->getParent()->begin();
200 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
201 if (cast<Instruction>(*UI)->getParent() != Entry)
202 return false; // Use not in entry block.
203 return true;
204}
205
Chris Lattner7a60d912005-01-07 07:47:53 +0000206FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000207 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000208 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
209
Chris Lattner6871b232005-10-30 19:42:35 +0000210 // Create a vreg for each argument register that is not dead and is used
211 // outside of the entry block for the function.
212 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
213 AI != E; ++AI)
214 if (!isOnlyUsedInEntryBlock(AI))
215 InitializeRegForValue(AI);
216
Chris Lattner7a60d912005-01-07 07:47:53 +0000217 // Initialize the mapping of values to registers. This is only set up for
218 // instruction values that are used outside of the block that defines
219 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000220 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000221 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
222 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
223 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
224 const Type *Ty = AI->getAllocatedType();
225 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000226 unsigned Align =
227 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
228 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000229
230 // If the alignment of the value is smaller than the size of the value,
231 // and if the size of the value is particularly small (<= 8 bytes),
232 // round up to the size of the value for potentially better performance.
233 //
234 // FIXME: This could be made better with a preferred alignment hook in
235 // TargetData. It serves primarily to 8-byte align doubles for X86.
236 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000237 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000238 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000239 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000240 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 }
242
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000243 for (; BB != EB; ++BB)
244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000245 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
246 if (!isa<AllocaInst>(I) ||
247 !StaticAllocaMap.count(cast<AllocaInst>(I)))
248 InitializeRegForValue(I);
249
250 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
251 // also creates the initial PHI MachineInstrs, though none of the input
252 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000253 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
255 MBBMap[BB] = MBB;
256 MF.getBasicBlockList().push_back(MBB);
257
258 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
259 // appropriate.
260 PHINode *PN;
261 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000262 (PN = dyn_cast<PHINode>(I)); ++I)
263 if (!PN->use_empty()) {
264 unsigned NumElements =
265 TLI.getNumElements(TLI.getValueType(PN->getType()));
266 unsigned PHIReg = ValueMap[PN];
267 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
268 for (unsigned i = 0; i != NumElements; ++i)
269 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
270 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000271 }
272}
273
Chris Lattner49409cb2006-03-16 19:51:18 +0000274/// CreateRegForValue - Allocate the appropriate number of virtual registers of
275/// the correctly promoted or expanded types. Assign these registers
276/// consecutive vreg numbers and return the first assigned number.
277unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
278 MVT::ValueType VT = TLI.getValueType(V->getType());
279
280 // The number of multiples of registers that we need, to, e.g., split up
281 // a <2 x int64> -> 4 x i32 registers.
282 unsigned NumVectorRegs = 1;
283
284 // If this is a packed type, figure out what type it will decompose into
285 // and how many of the elements it will use.
286 if (VT == MVT::Vector) {
287 const PackedType *PTy = cast<PackedType>(V->getType());
288 unsigned NumElts = PTy->getNumElements();
289 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
290
291 // Divide the input until we get to a supported size. This will always
292 // end with a scalar if the target doesn't support vectors.
293 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
294 NumElts >>= 1;
295 NumVectorRegs <<= 1;
296 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000297 if (NumElts == 1)
298 VT = EltTy;
299 else
300 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000301 }
302
303 // The common case is that we will only create one register for this
304 // value. If we have that case, create and return the virtual register.
305 unsigned NV = TLI.getNumElements(VT);
306 if (NV == 1) {
307 // If we are promoting this value, pick the next largest supported type.
308 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
309 unsigned Reg = MakeReg(PromotedType);
310 // If this is a vector of supported or promoted types (e.g. 4 x i16),
311 // create all of the registers.
312 for (unsigned i = 1; i != NumVectorRegs; ++i)
313 MakeReg(PromotedType);
314 return Reg;
315 }
316
317 // If this value is represented with multiple target registers, make sure
318 // to create enough consecutive registers of the right (smaller) type.
319 unsigned NT = VT-1; // Find the type to use.
320 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
321 --NT;
322
323 unsigned R = MakeReg((MVT::ValueType)NT);
324 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
325 MakeReg((MVT::ValueType)NT);
326 return R;
327}
Chris Lattner7a60d912005-01-07 07:47:53 +0000328
329//===----------------------------------------------------------------------===//
330/// SelectionDAGLowering - This is the common target-independent lowering
331/// implementation that is parameterized by a TargetLowering object.
332/// Also, targets can overload any lowering method.
333///
334namespace llvm {
335class SelectionDAGLowering {
336 MachineBasicBlock *CurMBB;
337
338 std::map<const Value*, SDOperand> NodeMap;
339
Chris Lattner4d9651c2005-01-17 22:19:26 +0000340 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
341 /// them up and then emit token factor nodes when possible. This allows us to
342 /// get simple disambiguation between loads without worrying about alias
343 /// analysis.
344 std::vector<SDOperand> PendingLoads;
345
Chris Lattner7a60d912005-01-07 07:47:53 +0000346public:
347 // TLI - This is information that describes the available target features we
348 // need for lowering. This indicates when operations are unavailable,
349 // implemented with a libcall, etc.
350 TargetLowering &TLI;
351 SelectionDAG &DAG;
352 const TargetData &TD;
353
354 /// FuncInfo - Information about the function as a whole.
355 ///
356 FunctionLoweringInfo &FuncInfo;
357
358 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000359 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000360 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
361 FuncInfo(funcinfo) {
362 }
363
Chris Lattner4108bb02005-01-17 19:43:36 +0000364 /// getRoot - Return the current virtual root of the Selection DAG.
365 ///
366 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000367 if (PendingLoads.empty())
368 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000369
Chris Lattner4d9651c2005-01-17 22:19:26 +0000370 if (PendingLoads.size() == 1) {
371 SDOperand Root = PendingLoads[0];
372 DAG.setRoot(Root);
373 PendingLoads.clear();
374 return Root;
375 }
376
377 // Otherwise, we have to make a token factor node.
378 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
379 PendingLoads.clear();
380 DAG.setRoot(Root);
381 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000382 }
383
Chris Lattner7a60d912005-01-07 07:47:53 +0000384 void visit(Instruction &I) { visit(I.getOpcode(), I); }
385
386 void visit(unsigned Opcode, User &I) {
387 switch (Opcode) {
388 default: assert(0 && "Unknown instruction type encountered!");
389 abort();
390 // Build the switch statement using the Instruction.def file.
391#define HANDLE_INST(NUM, OPCODE, CLASS) \
392 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
393#include "llvm/Instruction.def"
394 }
395 }
396
397 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
398
Chris Lattner4024c002006-03-15 22:19:46 +0000399 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
400 SDOperand SrcValue, SDOperand Root,
401 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000402
403 SDOperand getIntPtrConstant(uint64_t Val) {
404 return DAG.getConstant(Val, TLI.getPointerTy());
405 }
406
Chris Lattner8471b152006-03-16 19:57:50 +0000407 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000408
409 const SDOperand &setValue(const Value *V, SDOperand NewN) {
410 SDOperand &N = NodeMap[V];
411 assert(N.Val == 0 && "Already set a value for this node!");
412 return N = NewN;
413 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000414
Chris Lattner6f87d182006-02-22 22:37:12 +0000415 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
416 MVT::ValueType VT,
417 bool OutReg, bool InReg,
418 std::set<unsigned> &OutputRegs,
419 std::set<unsigned> &InputRegs);
420
Chris Lattner7a60d912005-01-07 07:47:53 +0000421 // Terminator instructions.
422 void visitRet(ReturnInst &I);
423 void visitBr(BranchInst &I);
424 void visitUnreachable(UnreachableInst &I) { /* noop */ }
425
426 // These all get lowered before this pass.
427 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
428 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
429 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
430
431 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000432 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000433 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000434 void visitAdd(User &I) {
435 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000436 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000437 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000438 void visitMul(User &I) {
439 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000440 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000441 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000442 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000443 visitBinary(I,
444 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
445 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000446 }
447 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000448 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000449 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000451 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
452 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
453 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000454 void visitShl(User &I) { visitShift(I, ISD::SHL); }
455 void visitShr(User &I) {
456 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000457 }
458
459 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
460 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
461 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
462 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
463 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
464 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
465 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
466
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000467 void visitExtractElement(ExtractElementInst &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000468 void visitInsertElement(InsertElementInst &I);
469
Chris Lattner7a60d912005-01-07 07:47:53 +0000470 void visitGetElementPtr(User &I);
471 void visitCast(User &I);
472 void visitSelect(User &I);
473 //
474
475 void visitMalloc(MallocInst &I);
476 void visitFree(FreeInst &I);
477 void visitAlloca(AllocaInst &I);
478 void visitLoad(LoadInst &I);
479 void visitStore(StoreInst &I);
480 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
481 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000482 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000483 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000484
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000486 void visitVAArg(VAArgInst &I);
487 void visitVAEnd(CallInst &I);
488 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000489 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000490
Chris Lattner875def92005-01-11 05:56:49 +0000491 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492
493 void visitUserOp1(Instruction &I) {
494 assert(0 && "UserOp1 should not exist at instruction selection time!");
495 abort();
496 }
497 void visitUserOp2(Instruction &I) {
498 assert(0 && "UserOp2 should not exist at instruction selection time!");
499 abort();
500 }
501};
502} // end namespace llvm
503
Chris Lattner8471b152006-03-16 19:57:50 +0000504SDOperand SelectionDAGLowering::getValue(const Value *V) {
505 SDOperand &N = NodeMap[V];
506 if (N.Val) return N;
507
508 const Type *VTy = V->getType();
509 MVT::ValueType VT = TLI.getValueType(VTy);
510 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
511 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
512 visit(CE->getOpcode(), *CE);
513 assert(N.Val && "visit didn't populate the ValueMap!");
514 return N;
515 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
516 return N = DAG.getGlobalAddress(GV, VT);
517 } else if (isa<ConstantPointerNull>(C)) {
518 return N = DAG.getConstant(0, TLI.getPointerTy());
519 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000520 if (!isa<PackedType>(VTy))
521 return N = DAG.getNode(ISD::UNDEF, VT);
522
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000523 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000524 const PackedType *PTy = cast<PackedType>(VTy);
525 unsigned NumElements = PTy->getNumElements();
526 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
527
528 std::vector<SDOperand> Ops;
529 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
530
531 // Create a VConstant node with generic Vector type.
532 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
533 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000534 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000535 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
536 return N = DAG.getConstantFP(CFP->getValue(), VT);
537 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
538 unsigned NumElements = PTy->getNumElements();
539 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000540
541 // Now that we know the number and type of the elements, push a
542 // Constant or ConstantFP node onto the ops list for each element of
543 // the packed constant.
544 std::vector<SDOperand> Ops;
545 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
546 if (MVT::isFloatingPoint(PVT)) {
547 for (unsigned i = 0; i != NumElements; ++i) {
548 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
549 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
550 }
551 } else {
552 for (unsigned i = 0; i != NumElements; ++i) {
553 const ConstantIntegral *El =
554 cast<ConstantIntegral>(CP->getOperand(i));
555 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
556 }
557 }
558 } else {
559 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
560 SDOperand Op;
561 if (MVT::isFloatingPoint(PVT))
562 Op = DAG.getConstantFP(0, PVT);
563 else
564 Op = DAG.getConstant(0, PVT);
565 Ops.assign(NumElements, Op);
566 }
567
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000568 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000569 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
570 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000571 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000572 } else {
573 // Canonicalize all constant ints to be unsigned.
574 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
575 }
576 }
577
578 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
579 std::map<const AllocaInst*, int>::iterator SI =
580 FuncInfo.StaticAllocaMap.find(AI);
581 if (SI != FuncInfo.StaticAllocaMap.end())
582 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
583 }
584
585 std::map<const Value*, unsigned>::const_iterator VMI =
586 FuncInfo.ValueMap.find(V);
587 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
588
589 unsigned InReg = VMI->second;
590
591 // If this type is not legal, make it so now.
592 if (VT == MVT::Vector) {
593 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
594 const PackedType *PTy = cast<PackedType>(VTy);
595 unsigned NumElements = PTy->getNumElements();
596 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
597 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
598 assert(TLI.isTypeLegal(TVT) &&
599 "FIXME: Cannot handle illegal vector types here yet!");
600 VT = TVT;
601 }
602
603 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
604
605 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
606 if (DestVT < VT) {
607 // Source must be expanded. This input value is actually coming from the
608 // register pair VMI->second and VMI->second+1.
609 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
610 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
611 } else {
612 if (DestVT > VT) { // Promotion case
613 if (MVT::isFloatingPoint(VT))
614 N = DAG.getNode(ISD::FP_ROUND, VT, N);
615 else
616 N = DAG.getNode(ISD::TRUNCATE, VT, N);
617 }
618 }
619
620 return N;
621}
622
623
Chris Lattner7a60d912005-01-07 07:47:53 +0000624void SelectionDAGLowering::visitRet(ReturnInst &I) {
625 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000626 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000627 return;
628 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000629 std::vector<SDOperand> NewValues;
630 NewValues.push_back(getRoot());
631 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
632 SDOperand RetOp = getValue(I.getOperand(i));
633
634 // If this is an integer return value, we need to promote it ourselves to
635 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
636 // than sign/zero.
637 if (MVT::isInteger(RetOp.getValueType()) &&
638 RetOp.getValueType() < MVT::i64) {
639 MVT::ValueType TmpVT;
640 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
641 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
642 else
643 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000644
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000645 if (I.getOperand(i)->getType()->isSigned())
646 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
647 else
648 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
649 }
650 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000651 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000652 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000653}
654
655void SelectionDAGLowering::visitBr(BranchInst &I) {
656 // Update machine-CFG edges.
657 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000658
659 // Figure out which block is immediately after the current one.
660 MachineBasicBlock *NextBlock = 0;
661 MachineFunction::iterator BBI = CurMBB;
662 if (++BBI != CurMBB->getParent()->end())
663 NextBlock = BBI;
664
665 if (I.isUnconditional()) {
666 // If this is not a fall-through branch, emit the branch.
667 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000668 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000669 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000670 } else {
671 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000672
673 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000674 if (Succ1MBB == NextBlock) {
675 // If the condition is false, fall through. This means we should branch
676 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000677 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000678 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000679 } else if (Succ0MBB == NextBlock) {
680 // If the condition is true, fall through. This means we should branch if
681 // the condition is false to Succ #1. Invert the condition first.
682 SDOperand True = DAG.getConstant(1, Cond.getValueType());
683 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000684 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000685 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000686 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000687 std::vector<SDOperand> Ops;
688 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000689 // If the false case is the current basic block, then this is a self
690 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
691 // adds an extra instruction in the loop. Instead, invert the
692 // condition and emit "Loop: ... br!cond Loop; br Out.
693 if (CurMBB == Succ1MBB) {
694 std::swap(Succ0MBB, Succ1MBB);
695 SDOperand True = DAG.getConstant(1, Cond.getValueType());
696 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
697 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000698 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
699 DAG.getBasicBlock(Succ0MBB));
700 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
701 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000702 }
703 }
704}
705
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000706void SelectionDAGLowering::visitSub(User &I) {
707 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000708 if (I.getType()->isFloatingPoint()) {
709 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
710 if (CFP->isExactlyValue(-0.0)) {
711 SDOperand Op2 = getValue(I.getOperand(1));
712 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
713 return;
714 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000715 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000716 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000717}
718
Nate Begemanb2e089c2005-11-19 00:36:38 +0000719void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
720 unsigned VecOp) {
721 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000722 SDOperand Op1 = getValue(I.getOperand(0));
723 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000724
Chris Lattner19baba62005-11-19 18:40:42 +0000725 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000726 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
727 } else if (Ty->isFloatingPoint()) {
728 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
729 } else {
730 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000731 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
732 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
733 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000734 }
Nate Begeman127321b2005-11-18 07:42:56 +0000735}
Chris Lattner96c26752005-01-19 22:31:21 +0000736
Nate Begeman127321b2005-11-18 07:42:56 +0000737void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
738 SDOperand Op1 = getValue(I.getOperand(0));
739 SDOperand Op2 = getValue(I.getOperand(1));
740
741 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
742
Chris Lattner7a60d912005-01-07 07:47:53 +0000743 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
744}
745
746void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
747 ISD::CondCode UnsignedOpcode) {
748 SDOperand Op1 = getValue(I.getOperand(0));
749 SDOperand Op2 = getValue(I.getOperand(1));
750 ISD::CondCode Opcode = SignedOpcode;
751 if (I.getOperand(0)->getType()->isUnsigned())
752 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000753 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000754}
755
756void SelectionDAGLowering::visitSelect(User &I) {
757 SDOperand Cond = getValue(I.getOperand(0));
758 SDOperand TrueVal = getValue(I.getOperand(1));
759 SDOperand FalseVal = getValue(I.getOperand(2));
760 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
761 TrueVal, FalseVal));
762}
763
764void SelectionDAGLowering::visitCast(User &I) {
765 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000766 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +0000767 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000768
Chris Lattner2f4119a2006-03-22 20:09:35 +0000769 if (DestVT == MVT::Vector) {
770 // This is a cast to a vector from something else. This is always a bit
771 // convert. Get information about the input vector.
772 const PackedType *DestTy = cast<PackedType>(I.getType());
773 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
774 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
775 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
776 DAG.getValueType(EltVT)));
777 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000778 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000779 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000780 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000781 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000782 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000783 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000784 } else if (isInteger(SrcVT)) {
785 if (isInteger(DestVT)) { // Int -> Int cast
786 if (DestVT < SrcVT) // Truncating cast?
787 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000788 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000789 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000790 else
Chris Lattner4024c002006-03-15 22:19:46 +0000791 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +0000792 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000793 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000794 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000795 else
Chris Lattner4024c002006-03-15 22:19:46 +0000796 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000797 } else {
798 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000799 }
Chris Lattner4024c002006-03-15 22:19:46 +0000800 } else if (isFloatingPoint(SrcVT)) {
801 if (isFloatingPoint(DestVT)) { // FP -> FP cast
802 if (DestVT < SrcVT) // Rounding cast?
803 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000804 else
Chris Lattner4024c002006-03-15 22:19:46 +0000805 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000806 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000807 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000808 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000809 else
Chris Lattner4024c002006-03-15 22:19:46 +0000810 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000811 } else {
812 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +0000813 }
814 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +0000815 assert(SrcVT == MVT::Vector && "Unknown cast!");
816 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
817 // This is a cast from a vector to something else. This is always a bit
818 // convert. Get information about the input vector.
819 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +0000820 }
821}
822
Chris Lattner32206f52006-03-18 01:44:44 +0000823void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
Chris Lattner32206f52006-03-18 01:44:44 +0000824 SDOperand InVec = getValue(I.getOperand(0));
825 SDOperand InVal = getValue(I.getOperand(1));
826 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
827 getValue(I.getOperand(2)));
828
Chris Lattner29b23012006-03-19 01:17:20 +0000829 SDOperand Num = *(InVec.Val->op_end()-2);
830 SDOperand Typ = *(InVec.Val->op_end()-1);
831 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
832 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +0000833}
834
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000835void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
836 SDOperand InVec = getValue(I.getOperand(0));
837 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
838 getValue(I.getOperand(1)));
839 SDOperand Typ = *(InVec.Val->op_end()-1);
840 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
841 TLI.getValueType(I.getType()), InVec, InIdx));
842}
Chris Lattner32206f52006-03-18 01:44:44 +0000843
Chris Lattner7a60d912005-01-07 07:47:53 +0000844void SelectionDAGLowering::visitGetElementPtr(User &I) {
845 SDOperand N = getValue(I.getOperand(0));
846 const Type *Ty = I.getOperand(0)->getType();
847 const Type *UIntPtrTy = TD.getIntPtrType();
848
849 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
850 OI != E; ++OI) {
851 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000852 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000853 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
854 if (Field) {
855 // N = N + Offset
856 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
857 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000858 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000859 }
860 Ty = StTy->getElementType(Field);
861 } else {
862 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000863
Chris Lattner43535a12005-11-09 04:45:33 +0000864 // If this is a constant subscript, handle it quickly.
865 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
866 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000867
Chris Lattner43535a12005-11-09 04:45:33 +0000868 uint64_t Offs;
869 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
870 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
871 else
872 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
873 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
874 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000875 }
Chris Lattner43535a12005-11-09 04:45:33 +0000876
877 // N = N + Idx * ElementSize;
878 uint64_t ElementSize = TD.getTypeSize(Ty);
879 SDOperand IdxN = getValue(Idx);
880
881 // If the index is smaller or larger than intptr_t, truncate or extend
882 // it.
883 if (IdxN.getValueType() < N.getValueType()) {
884 if (Idx->getType()->isSigned())
885 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
886 else
887 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
888 } else if (IdxN.getValueType() > N.getValueType())
889 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
890
891 // If this is a multiply by a power of two, turn it into a shl
892 // immediately. This is a very common case.
893 if (isPowerOf2_64(ElementSize)) {
894 unsigned Amt = Log2_64(ElementSize);
895 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000896 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000897 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
898 continue;
899 }
900
901 SDOperand Scale = getIntPtrConstant(ElementSize);
902 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
903 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000904 }
905 }
906 setValue(&I, N);
907}
908
909void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
910 // If this is a fixed sized alloca in the entry block of the function,
911 // allocate it statically on the stack.
912 if (FuncInfo.StaticAllocaMap.count(&I))
913 return; // getValue will auto-populate this.
914
915 const Type *Ty = I.getAllocatedType();
916 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000917 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
918 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000919
920 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000921 MVT::ValueType IntPtr = TLI.getPointerTy();
922 if (IntPtr < AllocSize.getValueType())
923 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
924 else if (IntPtr > AllocSize.getValueType())
925 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000926
Chris Lattnereccb73d2005-01-22 23:04:37 +0000927 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000928 getIntPtrConstant(TySize));
929
930 // Handle alignment. If the requested alignment is less than or equal to the
931 // stack alignment, ignore it and round the size of the allocation up to the
932 // stack alignment size. If the size is greater than the stack alignment, we
933 // note this in the DYNAMIC_STACKALLOC node.
934 unsigned StackAlign =
935 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
936 if (Align <= StackAlign) {
937 Align = 0;
938 // Add SA-1 to the size.
939 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
940 getIntPtrConstant(StackAlign-1));
941 // Mask out the low bits for alignment purposes.
942 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
943 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
944 }
945
Chris Lattner96c262e2005-05-14 07:29:57 +0000946 std::vector<MVT::ValueType> VTs;
947 VTs.push_back(AllocSize.getValueType());
948 VTs.push_back(MVT::Other);
949 std::vector<SDOperand> Ops;
950 Ops.push_back(getRoot());
951 Ops.push_back(AllocSize);
952 Ops.push_back(getIntPtrConstant(Align));
953 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000954 DAG.setRoot(setValue(&I, DSA).getValue(1));
955
956 // Inform the Frame Information that we have just allocated a variable-sized
957 // object.
958 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
959}
960
Chris Lattner7a60d912005-01-07 07:47:53 +0000961void SelectionDAGLowering::visitLoad(LoadInst &I) {
962 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000963
Chris Lattner4d9651c2005-01-17 22:19:26 +0000964 SDOperand Root;
965 if (I.isVolatile())
966 Root = getRoot();
967 else {
968 // Do not serialize non-volatile loads against each other.
969 Root = DAG.getRoot();
970 }
Chris Lattner4024c002006-03-15 22:19:46 +0000971
972 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
973 Root, I.isVolatile()));
974}
975
976SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
977 SDOperand SrcValue, SDOperand Root,
978 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000979 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000980 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000981 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +0000982 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000983 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000984 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000985 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000986
Chris Lattner4024c002006-03-15 22:19:46 +0000987 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +0000988 DAG.setRoot(L.getValue(1));
989 else
990 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +0000991
992 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +0000993}
994
995
996void SelectionDAGLowering::visitStore(StoreInst &I) {
997 Value *SrcV = I.getOperand(0);
998 SDOperand Src = getValue(SrcV);
999 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001000 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001001 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001002}
1003
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001004/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1005/// we want to emit this as a call to a named external function, return the name
1006/// otherwise lower it and return null.
1007const char *
1008SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1009 switch (Intrinsic) {
1010 case Intrinsic::vastart: visitVAStart(I); return 0;
1011 case Intrinsic::vaend: visitVAEnd(I); return 0;
1012 case Intrinsic::vacopy: visitVACopy(I); return 0;
1013 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1014 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1015 case Intrinsic::setjmp:
1016 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1017 break;
1018 case Intrinsic::longjmp:
1019 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1020 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001021 case Intrinsic::memcpy_i32:
1022 case Intrinsic::memcpy_i64:
1023 visitMemIntrinsic(I, ISD::MEMCPY);
1024 return 0;
1025 case Intrinsic::memset_i32:
1026 case Intrinsic::memset_i64:
1027 visitMemIntrinsic(I, ISD::MEMSET);
1028 return 0;
1029 case Intrinsic::memmove_i32:
1030 case Intrinsic::memmove_i64:
1031 visitMemIntrinsic(I, ISD::MEMMOVE);
1032 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001033
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001034 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001035 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001036 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1037 if (DebugInfo && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001038 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001039
Jim Laskey5995d012006-02-11 01:01:30 +00001040 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001041 Ops.push_back(getValue(SPI.getLineValue()));
1042 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001043
Jim Laskeya8bdac82006-03-23 18:06:46 +00001044 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001045 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001046 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1047
Jim Laskey5995d012006-02-11 01:01:30 +00001048 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1049 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1050
Jim Laskeya8bdac82006-03-23 18:06:46 +00001051 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001052 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001053
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001054 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001055 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001056 case Intrinsic::dbg_region_start: {
1057 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1058 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1059 if (DebugInfo && DebugInfo->Verify(RSI.getContext())) {
1060 std::vector<SDOperand> Ops;
1061
1062 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1063
1064 Ops.push_back(getRoot());
1065 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1066
1067 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1068 }
1069
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001070 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001071 }
1072 case Intrinsic::dbg_region_end: {
1073 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1074 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1075 if (DebugInfo && DebugInfo->Verify(REI.getContext())) {
1076 std::vector<SDOperand> Ops;
1077
1078 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1079
1080 Ops.push_back(getRoot());
1081 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1082
1083 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1084 }
1085
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001086 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001087 }
1088 case Intrinsic::dbg_func_start: {
1089 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1090 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1091 if (DebugInfo && DebugInfo->Verify(FSI.getSubprogram())) {
1092 std::vector<SDOperand> Ops;
1093
1094 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1095
1096 Ops.push_back(getRoot());
1097 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1098
1099 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1100 }
1101
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001102 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001103 }
1104 case Intrinsic::dbg_declare: {
1105 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1106 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1107 if (DebugInfo && DebugInfo->Verify(DI.getVariable())) {
1108 std::vector<SDOperand> Ops;
1109
1110 SDOperand AllocaOp = getValue(I.getOperand(1));
1111 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AllocaOp)) {
1112 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1113 }
1114 }
1115
1116 return 0;
1117 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001118
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001119 case Intrinsic::isunordered_f32:
1120 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001121 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1122 getValue(I.getOperand(2)), ISD::SETUO));
1123 return 0;
1124
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001125 case Intrinsic::sqrt_f32:
1126 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001127 setValue(&I, DAG.getNode(ISD::FSQRT,
1128 getValue(I.getOperand(1)).getValueType(),
1129 getValue(I.getOperand(1))));
1130 return 0;
1131 case Intrinsic::pcmarker: {
1132 SDOperand Tmp = getValue(I.getOperand(1));
1133 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1134 return 0;
1135 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001136 case Intrinsic::readcyclecounter: {
1137 std::vector<MVT::ValueType> VTs;
1138 VTs.push_back(MVT::i64);
1139 VTs.push_back(MVT::Other);
1140 std::vector<SDOperand> Ops;
1141 Ops.push_back(getRoot());
1142 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1143 setValue(&I, Tmp);
1144 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001145 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001146 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001147 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001148 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001149 case Intrinsic::bswap_i64:
1150 setValue(&I, DAG.getNode(ISD::BSWAP,
1151 getValue(I.getOperand(1)).getValueType(),
1152 getValue(I.getOperand(1))));
1153 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001154 case Intrinsic::cttz_i8:
1155 case Intrinsic::cttz_i16:
1156 case Intrinsic::cttz_i32:
1157 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001158 setValue(&I, DAG.getNode(ISD::CTTZ,
1159 getValue(I.getOperand(1)).getValueType(),
1160 getValue(I.getOperand(1))));
1161 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001162 case Intrinsic::ctlz_i8:
1163 case Intrinsic::ctlz_i16:
1164 case Intrinsic::ctlz_i32:
1165 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001166 setValue(&I, DAG.getNode(ISD::CTLZ,
1167 getValue(I.getOperand(1)).getValueType(),
1168 getValue(I.getOperand(1))));
1169 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001170 case Intrinsic::ctpop_i8:
1171 case Intrinsic::ctpop_i16:
1172 case Intrinsic::ctpop_i32:
1173 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001174 setValue(&I, DAG.getNode(ISD::CTPOP,
1175 getValue(I.getOperand(1)).getValueType(),
1176 getValue(I.getOperand(1))));
1177 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001178 case Intrinsic::stacksave: {
1179 std::vector<MVT::ValueType> VTs;
1180 VTs.push_back(TLI.getPointerTy());
1181 VTs.push_back(MVT::Other);
1182 std::vector<SDOperand> Ops;
1183 Ops.push_back(getRoot());
1184 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1185 setValue(&I, Tmp);
1186 DAG.setRoot(Tmp.getValue(1));
1187 return 0;
1188 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001189 case Intrinsic::stackrestore: {
1190 SDOperand Tmp = getValue(I.getOperand(1));
1191 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001192 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001193 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001194 case Intrinsic::prefetch:
1195 // FIXME: Currently discarding prefetches.
1196 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001197 default:
1198 std::cerr << I;
1199 assert(0 && "This intrinsic is not implemented yet!");
1200 return 0;
1201 }
1202}
1203
1204
Chris Lattner7a60d912005-01-07 07:47:53 +00001205void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001206 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001207 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001208 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001209 if (unsigned IID = F->getIntrinsicID()) {
1210 RenameFn = visitIntrinsicCall(I, IID);
1211 if (!RenameFn)
1212 return;
1213 } else { // Not an LLVM intrinsic.
1214 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001215 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1216 if (I.getNumOperands() == 3 && // Basic sanity checks.
1217 I.getOperand(1)->getType()->isFloatingPoint() &&
1218 I.getType() == I.getOperand(1)->getType() &&
1219 I.getType() == I.getOperand(2)->getType()) {
1220 SDOperand LHS = getValue(I.getOperand(1));
1221 SDOperand RHS = getValue(I.getOperand(2));
1222 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1223 LHS, RHS));
1224 return;
1225 }
1226 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001227 if (I.getNumOperands() == 2 && // Basic sanity checks.
1228 I.getOperand(1)->getType()->isFloatingPoint() &&
1229 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001230 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001231 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1232 return;
1233 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001234 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001235 if (I.getNumOperands() == 2 && // Basic sanity checks.
1236 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001237 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001238 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001239 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1240 return;
1241 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001242 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001243 if (I.getNumOperands() == 2 && // Basic sanity checks.
1244 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001245 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001246 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001247 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1248 return;
1249 }
1250 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001251 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001252 } else if (isa<InlineAsm>(I.getOperand(0))) {
1253 visitInlineAsm(I);
1254 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001255 }
Misha Brukman835702a2005-04-21 22:36:52 +00001256
Chris Lattner18d2b342005-01-08 22:48:57 +00001257 SDOperand Callee;
1258 if (!RenameFn)
1259 Callee = getValue(I.getOperand(0));
1260 else
1261 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001262 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001263 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001264 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1265 Value *Arg = I.getOperand(i);
1266 SDOperand ArgNode = getValue(Arg);
1267 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1268 }
Misha Brukman835702a2005-04-21 22:36:52 +00001269
Nate Begemanf6565252005-03-26 01:29:23 +00001270 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1271 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001272
Chris Lattner1f45cd72005-01-08 19:26:18 +00001273 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001274 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001275 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001276 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001277 setValue(&I, Result.first);
1278 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001279}
1280
Chris Lattner6f87d182006-02-22 22:37:12 +00001281SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001282 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001283 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1284 Chain = Val.getValue(1);
1285 Flag = Val.getValue(2);
1286
1287 // If the result was expanded, copy from the top part.
1288 if (Regs.size() > 1) {
1289 assert(Regs.size() == 2 &&
1290 "Cannot expand to more than 2 elts yet!");
1291 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1292 Chain = Val.getValue(1);
1293 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001294 if (DAG.getTargetLoweringInfo().isLittleEndian())
1295 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1296 else
1297 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001298 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001299
Chris Lattner6f87d182006-02-22 22:37:12 +00001300 // Otherwise, if the return value was promoted, truncate it to the
1301 // appropriate type.
1302 if (RegVT == ValueVT)
1303 return Val;
1304
1305 if (MVT::isInteger(RegVT))
1306 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1307 else
1308 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1309}
1310
Chris Lattner571d9642006-02-23 19:21:04 +00001311/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1312/// specified value into the registers specified by this object. This uses
1313/// Chain/Flag as the input and updates them for the output Chain/Flag.
1314void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001315 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001316 if (Regs.size() == 1) {
1317 // If there is a single register and the types differ, this must be
1318 // a promotion.
1319 if (RegVT != ValueVT) {
1320 if (MVT::isInteger(RegVT))
1321 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1322 else
1323 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1324 }
1325 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1326 Flag = Chain.getValue(1);
1327 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001328 std::vector<unsigned> R(Regs);
1329 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1330 std::reverse(R.begin(), R.end());
1331
1332 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001333 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1334 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001335 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001336 Flag = Chain.getValue(1);
1337 }
1338 }
1339}
Chris Lattner6f87d182006-02-22 22:37:12 +00001340
Chris Lattner571d9642006-02-23 19:21:04 +00001341/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1342/// operand list. This adds the code marker and includes the number of
1343/// values added into it.
1344void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001345 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001346 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1347 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1348 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1349}
Chris Lattner6f87d182006-02-22 22:37:12 +00001350
1351/// isAllocatableRegister - If the specified register is safe to allocate,
1352/// i.e. it isn't a stack pointer or some other special register, return the
1353/// register class for the register. Otherwise, return null.
1354static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001355isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1356 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1357 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1358 E = MRI->regclass_end(); RCI != E; ++RCI) {
1359 const TargetRegisterClass *RC = *RCI;
1360 // If none of the the value types for this register class are valid, we
1361 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1362 bool isLegal = false;
1363 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1364 I != E; ++I) {
1365 if (TLI.isTypeLegal(*I)) {
1366 isLegal = true;
1367 break;
1368 }
1369 }
1370
1371 if (!isLegal) continue;
1372
Chris Lattner6f87d182006-02-22 22:37:12 +00001373 // NOTE: This isn't ideal. In particular, this might allocate the
1374 // frame pointer in functions that need it (due to them not being taken
1375 // out of allocation, because a variable sized allocation hasn't been seen
1376 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001377 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1378 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001379 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001380 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001381 }
1382 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001383}
1384
1385RegsForValue SelectionDAGLowering::
1386GetRegistersForValue(const std::string &ConstrCode,
1387 MVT::ValueType VT, bool isOutReg, bool isInReg,
1388 std::set<unsigned> &OutputRegs,
1389 std::set<unsigned> &InputRegs) {
1390 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1391 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1392 std::vector<unsigned> Regs;
1393
1394 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1395 MVT::ValueType RegVT;
1396 MVT::ValueType ValueVT = VT;
1397
1398 if (PhysReg.first) {
1399 if (VT == MVT::Other)
1400 ValueVT = *PhysReg.second->vt_begin();
1401 RegVT = VT;
1402
1403 // This is a explicit reference to a physical register.
1404 Regs.push_back(PhysReg.first);
1405
1406 // If this is an expanded reference, add the rest of the regs to Regs.
1407 if (NumRegs != 1) {
1408 RegVT = *PhysReg.second->vt_begin();
1409 TargetRegisterClass::iterator I = PhysReg.second->begin();
1410 TargetRegisterClass::iterator E = PhysReg.second->end();
1411 for (; *I != PhysReg.first; ++I)
1412 assert(I != E && "Didn't find reg!");
1413
1414 // Already added the first reg.
1415 --NumRegs; ++I;
1416 for (; NumRegs; --NumRegs, ++I) {
1417 assert(I != E && "Ran out of registers to allocate!");
1418 Regs.push_back(*I);
1419 }
1420 }
1421 return RegsForValue(Regs, RegVT, ValueVT);
1422 }
1423
1424 // This is a reference to a register class. Allocate NumRegs consecutive,
1425 // available, registers from the class.
1426 std::vector<unsigned> RegClassRegs =
1427 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1428
1429 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1430 MachineFunction &MF = *CurMBB->getParent();
1431 unsigned NumAllocated = 0;
1432 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1433 unsigned Reg = RegClassRegs[i];
1434 // See if this register is available.
1435 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1436 (isInReg && InputRegs.count(Reg))) { // Already used.
1437 // Make sure we find consecutive registers.
1438 NumAllocated = 0;
1439 continue;
1440 }
1441
1442 // Check to see if this register is allocatable (i.e. don't give out the
1443 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001444 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001445 if (!RC) {
1446 // Make sure we find consecutive registers.
1447 NumAllocated = 0;
1448 continue;
1449 }
1450
1451 // Okay, this register is good, we can use it.
1452 ++NumAllocated;
1453
1454 // If we allocated enough consecutive
1455 if (NumAllocated == NumRegs) {
1456 unsigned RegStart = (i-NumAllocated)+1;
1457 unsigned RegEnd = i+1;
1458 // Mark all of the allocated registers used.
1459 for (unsigned i = RegStart; i != RegEnd; ++i) {
1460 unsigned Reg = RegClassRegs[i];
1461 Regs.push_back(Reg);
1462 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1463 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1464 }
1465
1466 return RegsForValue(Regs, *RC->vt_begin(), VT);
1467 }
1468 }
1469
1470 // Otherwise, we couldn't allocate enough registers for this.
1471 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001472}
1473
Chris Lattner6f87d182006-02-22 22:37:12 +00001474
Chris Lattner476e67b2006-01-26 22:24:51 +00001475/// visitInlineAsm - Handle a call to an InlineAsm object.
1476///
1477void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1478 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1479
1480 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1481 MVT::Other);
1482
1483 // Note, we treat inline asms both with and without side-effects as the same.
1484 // If an inline asm doesn't have side effects and doesn't access memory, we
1485 // could not choose to not chain it.
1486 bool hasSideEffects = IA->hasSideEffects();
1487
Chris Lattner3a5ed552006-02-01 01:28:23 +00001488 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001489 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001490
1491 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1492 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1493 /// if it is a def of that register.
1494 std::vector<SDOperand> AsmNodeOperands;
1495 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1496 AsmNodeOperands.push_back(AsmStr);
1497
1498 SDOperand Chain = getRoot();
1499 SDOperand Flag;
1500
Chris Lattner1558fc62006-02-01 18:59:47 +00001501 // We fully assign registers here at isel time. This is not optimal, but
1502 // should work. For register classes that correspond to LLVM classes, we
1503 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1504 // over the constraints, collecting fixed registers that we know we can't use.
1505 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001506 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001507 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1508 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1509 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001510
Chris Lattner7ad77df2006-02-22 00:56:39 +00001511 MVT::ValueType OpVT;
1512
1513 // Compute the value type for each operand and add it to ConstraintVTs.
1514 switch (Constraints[i].Type) {
1515 case InlineAsm::isOutput:
1516 if (!Constraints[i].isIndirectOutput) {
1517 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1518 OpVT = TLI.getValueType(I.getType());
1519 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001520 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001521 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1522 OpNum++; // Consumes a call operand.
1523 }
1524 break;
1525 case InlineAsm::isInput:
1526 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1527 OpNum++; // Consumes a call operand.
1528 break;
1529 case InlineAsm::isClobber:
1530 OpVT = MVT::Other;
1531 break;
1532 }
1533
1534 ConstraintVTs.push_back(OpVT);
1535
Chris Lattner6f87d182006-02-22 22:37:12 +00001536 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1537 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001538
Chris Lattner6f87d182006-02-22 22:37:12 +00001539 // Build a list of regs that this operand uses. This always has a single
1540 // element for promoted/expanded operands.
1541 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1542 false, false,
1543 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001544
1545 switch (Constraints[i].Type) {
1546 case InlineAsm::isOutput:
1547 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001548 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001549 // If this is an early-clobber output, it cannot be assigned to the same
1550 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001551 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001552 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001553 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001554 case InlineAsm::isInput:
1555 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001556 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001557 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001558 case InlineAsm::isClobber:
1559 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001560 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1561 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001562 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001563 }
1564 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001565
Chris Lattner5c79f982006-02-21 23:12:12 +00001566 // Loop over all of the inputs, copying the operand values into the
1567 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001568 RegsForValue RetValRegs;
1569 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001570 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001571
Chris Lattner2e56e892006-01-31 02:03:41 +00001572 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001573 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1574 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001575
Chris Lattner3a5ed552006-02-01 01:28:23 +00001576 switch (Constraints[i].Type) {
1577 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001578 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1579 if (ConstraintCode.size() == 1) // not a physreg name.
1580 CTy = TLI.getConstraintType(ConstraintCode[0]);
1581
1582 if (CTy == TargetLowering::C_Memory) {
1583 // Memory output.
1584 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1585
1586 // Check that the operand (the address to store to) isn't a float.
1587 if (!MVT::isInteger(InOperandVal.getValueType()))
1588 assert(0 && "MATCH FAIL!");
1589
1590 if (!Constraints[i].isIndirectOutput)
1591 assert(0 && "MATCH FAIL!");
1592
1593 OpNum++; // Consumes a call operand.
1594
1595 // Extend/truncate to the right pointer type if needed.
1596 MVT::ValueType PtrType = TLI.getPointerTy();
1597 if (InOperandVal.getValueType() < PtrType)
1598 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1599 else if (InOperandVal.getValueType() > PtrType)
1600 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1601
1602 // Add information to the INLINEASM node to know about this output.
1603 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1604 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1605 AsmNodeOperands.push_back(InOperandVal);
1606 break;
1607 }
1608
1609 // Otherwise, this is a register output.
1610 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1611
Chris Lattner6f87d182006-02-22 22:37:12 +00001612 // If this is an early-clobber output, or if there is an input
1613 // constraint that matches this, we need to reserve the input register
1614 // so no other inputs allocate to it.
1615 bool UsesInputRegister = false;
1616 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1617 UsesInputRegister = true;
1618
1619 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001620 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001621 RegsForValue Regs =
1622 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1623 true, UsesInputRegister,
1624 OutputRegs, InputRegs);
1625 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001626
Chris Lattner3a5ed552006-02-01 01:28:23 +00001627 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001628 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001629 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001630 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001631 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001632 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001633 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1634 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001635 OpNum++; // Consumes a call operand.
1636 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001637
1638 // Add information to the INLINEASM node to know that this register is
1639 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001640 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001641 break;
1642 }
1643 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001644 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001645 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001646
Chris Lattner7f5880b2006-02-02 00:25:23 +00001647 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1648 // If this is required to match an output register we have already set,
1649 // just use its register.
1650 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001651
Chris Lattner571d9642006-02-23 19:21:04 +00001652 // Scan until we find the definition we already emitted of this operand.
1653 // When we find it, create a RegsForValue operand.
1654 unsigned CurOp = 2; // The first operand.
1655 for (; OperandNo; --OperandNo) {
1656 // Advance to the next operand.
1657 unsigned NumOps =
1658 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1659 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1660 "Skipped past definitions?");
1661 CurOp += (NumOps>>3)+1;
1662 }
1663
1664 unsigned NumOps =
1665 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1666 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1667 "Skipped past definitions?");
1668
1669 // Add NumOps>>3 registers to MatchedRegs.
1670 RegsForValue MatchedRegs;
1671 MatchedRegs.ValueVT = InOperandVal.getValueType();
1672 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1673 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1674 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1675 MatchedRegs.Regs.push_back(Reg);
1676 }
1677
1678 // Use the produced MatchedRegs object to
1679 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1680 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001681 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001682 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001683
1684 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1685 if (ConstraintCode.size() == 1) // not a physreg name.
1686 CTy = TLI.getConstraintType(ConstraintCode[0]);
1687
1688 if (CTy == TargetLowering::C_Other) {
1689 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1690 assert(0 && "MATCH FAIL!");
1691
1692 // Add information to the INLINEASM node to know about this input.
1693 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1694 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1695 AsmNodeOperands.push_back(InOperandVal);
1696 break;
1697 } else if (CTy == TargetLowering::C_Memory) {
1698 // Memory input.
1699
1700 // Check that the operand isn't a float.
1701 if (!MVT::isInteger(InOperandVal.getValueType()))
1702 assert(0 && "MATCH FAIL!");
1703
1704 // Extend/truncate to the right pointer type if needed.
1705 MVT::ValueType PtrType = TLI.getPointerTy();
1706 if (InOperandVal.getValueType() < PtrType)
1707 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1708 else if (InOperandVal.getValueType() > PtrType)
1709 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1710
1711 // Add information to the INLINEASM node to know about this input.
1712 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1713 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1714 AsmNodeOperands.push_back(InOperandVal);
1715 break;
1716 }
1717
1718 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1719
1720 // Copy the input into the appropriate registers.
1721 RegsForValue InRegs =
1722 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1723 false, true, OutputRegs, InputRegs);
1724 // FIXME: should be match fail.
1725 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1726
1727 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1728
1729 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001730 break;
1731 }
Chris Lattner571d9642006-02-23 19:21:04 +00001732 case InlineAsm::isClobber: {
1733 RegsForValue ClobberedRegs =
1734 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1735 OutputRegs, InputRegs);
1736 // Add the clobbered value to the operand list, so that the register
1737 // allocator is aware that the physreg got clobbered.
1738 if (!ClobberedRegs.Regs.empty())
1739 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001740 break;
1741 }
Chris Lattner571d9642006-02-23 19:21:04 +00001742 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001743 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001744
1745 // Finish up input operands.
1746 AsmNodeOperands[0] = Chain;
1747 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1748
1749 std::vector<MVT::ValueType> VTs;
1750 VTs.push_back(MVT::Other);
1751 VTs.push_back(MVT::Flag);
1752 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1753 Flag = Chain.getValue(1);
1754
Chris Lattner2e56e892006-01-31 02:03:41 +00001755 // If this asm returns a register value, copy the result from that register
1756 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001757 if (!RetValRegs.Regs.empty())
1758 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001759
Chris Lattner2e56e892006-01-31 02:03:41 +00001760 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1761
1762 // Process indirect outputs, first output all of the flagged copies out of
1763 // physregs.
1764 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001765 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001766 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001767 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1768 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001769 }
1770
1771 // Emit the non-flagged stores from the physregs.
1772 std::vector<SDOperand> OutChains;
1773 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1774 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1775 StoresToEmit[i].first,
1776 getValue(StoresToEmit[i].second),
1777 DAG.getSrcValue(StoresToEmit[i].second)));
1778 if (!OutChains.empty())
1779 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001780 DAG.setRoot(Chain);
1781}
1782
1783
Chris Lattner7a60d912005-01-07 07:47:53 +00001784void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1785 SDOperand Src = getValue(I.getOperand(0));
1786
1787 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001788
1789 if (IntPtr < Src.getValueType())
1790 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1791 else if (IntPtr > Src.getValueType())
1792 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001793
1794 // Scale the source by the type size.
1795 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1796 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1797 Src, getIntPtrConstant(ElementSize));
1798
1799 std::vector<std::pair<SDOperand, const Type*> > Args;
1800 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001801
1802 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001803 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001804 DAG.getExternalSymbol("malloc", IntPtr),
1805 Args, DAG);
1806 setValue(&I, Result.first); // Pointers always fit in registers
1807 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001808}
1809
1810void SelectionDAGLowering::visitFree(FreeInst &I) {
1811 std::vector<std::pair<SDOperand, const Type*> > Args;
1812 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1813 TLI.getTargetData().getIntPtrType()));
1814 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001815 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001816 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001817 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1818 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001819}
1820
Chris Lattner13d7c252005-08-26 20:54:47 +00001821// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1822// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1823// instructions are special in various ways, which require special support to
1824// insert. The specified MachineInstr is created but not inserted into any
1825// basic blocks, and the scheduler passes ownership of it to this method.
1826MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1827 MachineBasicBlock *MBB) {
1828 std::cerr << "If a target marks an instruction with "
1829 "'usesCustomDAGSchedInserter', it must implement "
1830 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1831 abort();
1832 return 0;
1833}
1834
Chris Lattner58cfd792005-01-09 00:00:49 +00001835void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001836 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1837 getValue(I.getOperand(1)),
1838 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001839}
1840
1841void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001842 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1843 getValue(I.getOperand(0)),
1844 DAG.getSrcValue(I.getOperand(0)));
1845 setValue(&I, V);
1846 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001847}
1848
1849void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001850 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1851 getValue(I.getOperand(1)),
1852 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001853}
1854
1855void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001856 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1857 getValue(I.getOperand(1)),
1858 getValue(I.getOperand(2)),
1859 DAG.getSrcValue(I.getOperand(1)),
1860 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001861}
1862
Chris Lattner58cfd792005-01-09 00:00:49 +00001863// It is always conservatively correct for llvm.returnaddress and
1864// llvm.frameaddress to return 0.
1865std::pair<SDOperand, SDOperand>
1866TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1867 unsigned Depth, SelectionDAG &DAG) {
1868 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001869}
1870
Chris Lattner29dcc712005-05-14 05:50:48 +00001871SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001872 assert(0 && "LowerOperation not implemented for this target!");
1873 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001874 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001875}
1876
Nate Begeman595ec732006-01-28 03:14:31 +00001877SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1878 SelectionDAG &DAG) {
1879 assert(0 && "CustomPromoteOperation not implemented for this target!");
1880 abort();
1881 return SDOperand();
1882}
1883
Chris Lattner58cfd792005-01-09 00:00:49 +00001884void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1885 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1886 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001887 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001888 setValue(&I, Result.first);
1889 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001890}
1891
Evan Cheng6781b6e2006-02-15 21:59:04 +00001892/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001893/// operand.
1894static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001895 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001896 MVT::ValueType CurVT = VT;
1897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1898 uint64_t Val = C->getValue() & 255;
1899 unsigned Shift = 8;
1900 while (CurVT != MVT::i8) {
1901 Val = (Val << Shift) | Val;
1902 Shift <<= 1;
1903 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001904 }
1905 return DAG.getConstant(Val, VT);
1906 } else {
1907 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1908 unsigned Shift = 8;
1909 while (CurVT != MVT::i8) {
1910 Value =
1911 DAG.getNode(ISD::OR, VT,
1912 DAG.getNode(ISD::SHL, VT, Value,
1913 DAG.getConstant(Shift, MVT::i8)), Value);
1914 Shift <<= 1;
1915 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001916 }
1917
1918 return Value;
1919 }
1920}
1921
Evan Cheng6781b6e2006-02-15 21:59:04 +00001922/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1923/// used when a memcpy is turned into a memset when the source is a constant
1924/// string ptr.
1925static SDOperand getMemsetStringVal(MVT::ValueType VT,
1926 SelectionDAG &DAG, TargetLowering &TLI,
1927 std::string &Str, unsigned Offset) {
1928 MVT::ValueType CurVT = VT;
1929 uint64_t Val = 0;
1930 unsigned MSB = getSizeInBits(VT) / 8;
1931 if (TLI.isLittleEndian())
1932 Offset = Offset + MSB - 1;
1933 for (unsigned i = 0; i != MSB; ++i) {
1934 Val = (Val << 8) | Str[Offset];
1935 Offset += TLI.isLittleEndian() ? -1 : 1;
1936 }
1937 return DAG.getConstant(Val, VT);
1938}
1939
Evan Cheng81fcea82006-02-14 08:22:34 +00001940/// getMemBasePlusOffset - Returns base and offset node for the
1941static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1942 SelectionDAG &DAG, TargetLowering &TLI) {
1943 MVT::ValueType VT = Base.getValueType();
1944 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1945}
1946
Evan Chengdb2a7a72006-02-14 20:12:38 +00001947/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001948/// to replace the memset / memcpy is below the threshold. It also returns the
1949/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001950static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1951 unsigned Limit, uint64_t Size,
1952 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001953 MVT::ValueType VT;
1954
1955 if (TLI.allowsUnalignedMemoryAccesses()) {
1956 VT = MVT::i64;
1957 } else {
1958 switch (Align & 7) {
1959 case 0:
1960 VT = MVT::i64;
1961 break;
1962 case 4:
1963 VT = MVT::i32;
1964 break;
1965 case 2:
1966 VT = MVT::i16;
1967 break;
1968 default:
1969 VT = MVT::i8;
1970 break;
1971 }
1972 }
1973
Evan Chengd5026102006-02-14 09:11:59 +00001974 MVT::ValueType LVT = MVT::i64;
1975 while (!TLI.isTypeLegal(LVT))
1976 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1977 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001978
Evan Chengd5026102006-02-14 09:11:59 +00001979 if (VT > LVT)
1980 VT = LVT;
1981
Evan Cheng04514992006-02-14 23:05:54 +00001982 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001983 while (Size != 0) {
1984 unsigned VTSize = getSizeInBits(VT) / 8;
1985 while (VTSize > Size) {
1986 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001987 VTSize >>= 1;
1988 }
Evan Chengd5026102006-02-14 09:11:59 +00001989 assert(MVT::isInteger(VT));
1990
1991 if (++NumMemOps > Limit)
1992 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001993 MemOps.push_back(VT);
1994 Size -= VTSize;
1995 }
Evan Chengd5026102006-02-14 09:11:59 +00001996
1997 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001998}
1999
Chris Lattner875def92005-01-11 05:56:49 +00002000void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002001 SDOperand Op1 = getValue(I.getOperand(1));
2002 SDOperand Op2 = getValue(I.getOperand(2));
2003 SDOperand Op3 = getValue(I.getOperand(3));
2004 SDOperand Op4 = getValue(I.getOperand(4));
2005 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2006 if (Align == 0) Align = 1;
2007
2008 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2009 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002010
2011 // Expand memset / memcpy to a series of load / store ops
2012 // if the size operand falls below a certain threshold.
2013 std::vector<SDOperand> OutChains;
2014 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002015 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002016 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002017 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2018 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002019 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002020 unsigned Offset = 0;
2021 for (unsigned i = 0; i < NumMemOps; i++) {
2022 MVT::ValueType VT = MemOps[i];
2023 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002024 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002025 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2026 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002027 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2028 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002029 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002030 Offset += VTSize;
2031 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002032 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002033 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002034 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002035 case ISD::MEMCPY: {
2036 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2037 Size->getValue(), Align, TLI)) {
2038 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002039 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002040 GlobalAddressSDNode *G = NULL;
2041 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002042 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002043
2044 if (Op2.getOpcode() == ISD::GlobalAddress)
2045 G = cast<GlobalAddressSDNode>(Op2);
2046 else if (Op2.getOpcode() == ISD::ADD &&
2047 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2048 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2049 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002050 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002051 }
2052 if (G) {
2053 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002054 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002055 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002056 if (!Str.empty()) {
2057 CopyFromStr = true;
2058 SrcOff += SrcDelta;
2059 }
2060 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002061 }
2062
Evan Chenge2038bd2006-02-15 01:54:51 +00002063 for (unsigned i = 0; i < NumMemOps; i++) {
2064 MVT::ValueType VT = MemOps[i];
2065 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002066 SDOperand Value, Chain, Store;
2067
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002068 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002069 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2070 Chain = getRoot();
2071 Store =
2072 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2073 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2074 DAG.getSrcValue(I.getOperand(1), DstOff));
2075 } else {
2076 Value = DAG.getLoad(VT, getRoot(),
2077 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2078 DAG.getSrcValue(I.getOperand(2), SrcOff));
2079 Chain = Value.getValue(1);
2080 Store =
2081 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2082 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2083 DAG.getSrcValue(I.getOperand(1), DstOff));
2084 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002085 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002086 SrcOff += VTSize;
2087 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002088 }
2089 }
2090 break;
2091 }
2092 }
2093
2094 if (!OutChains.empty()) {
2095 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2096 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002097 }
2098 }
2099
Chris Lattner875def92005-01-11 05:56:49 +00002100 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002101 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002102 Ops.push_back(Op1);
2103 Ops.push_back(Op2);
2104 Ops.push_back(Op3);
2105 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002106 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002107}
2108
Chris Lattner875def92005-01-11 05:56:49 +00002109//===----------------------------------------------------------------------===//
2110// SelectionDAGISel code
2111//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002112
2113unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2114 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2115}
2116
Chris Lattnerc9950c12005-08-17 06:37:43 +00002117void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002118 // FIXME: we only modify the CFG to split critical edges. This
2119 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002120}
Chris Lattner7a60d912005-01-07 07:47:53 +00002121
Chris Lattner35397782005-12-05 07:10:48 +00002122
2123/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2124/// casting to the type of GEPI.
2125static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2126 Value *Ptr, Value *PtrOffset) {
2127 if (V) return V; // Already computed.
2128
2129 BasicBlock::iterator InsertPt;
2130 if (BB == GEPI->getParent()) {
2131 // If insert into the GEP's block, insert right after the GEP.
2132 InsertPt = GEPI;
2133 ++InsertPt;
2134 } else {
2135 // Otherwise, insert at the top of BB, after any PHI nodes
2136 InsertPt = BB->begin();
2137 while (isa<PHINode>(InsertPt)) ++InsertPt;
2138 }
2139
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002140 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2141 // BB so that there is only one value live across basic blocks (the cast
2142 // operand).
2143 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2144 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2145 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2146
Chris Lattner35397782005-12-05 07:10:48 +00002147 // Add the offset, cast it to the right type.
2148 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2149 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2150 return V = Ptr;
2151}
2152
2153
2154/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2155/// selection, we want to be a bit careful about some things. In particular, if
2156/// we have a GEP instruction that is used in a different block than it is
2157/// defined, the addressing expression of the GEP cannot be folded into loads or
2158/// stores that use it. In this case, decompose the GEP and move constant
2159/// indices into blocks that use it.
2160static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2161 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002162 // If this GEP is only used inside the block it is defined in, there is no
2163 // need to rewrite it.
2164 bool isUsedOutsideDefBB = false;
2165 BasicBlock *DefBB = GEPI->getParent();
2166 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2167 UI != E; ++UI) {
2168 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2169 isUsedOutsideDefBB = true;
2170 break;
2171 }
2172 }
2173 if (!isUsedOutsideDefBB) return;
2174
2175 // If this GEP has no non-zero constant indices, there is nothing we can do,
2176 // ignore it.
2177 bool hasConstantIndex = false;
2178 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2179 E = GEPI->op_end(); OI != E; ++OI) {
2180 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2181 if (CI->getRawValue()) {
2182 hasConstantIndex = true;
2183 break;
2184 }
2185 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002186 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2187 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002188
2189 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2190 // constant offset (which we now know is non-zero) and deal with it later.
2191 uint64_t ConstantOffset = 0;
2192 const Type *UIntPtrTy = TD.getIntPtrType();
2193 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2194 const Type *Ty = GEPI->getOperand(0)->getType();
2195
2196 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2197 E = GEPI->op_end(); OI != E; ++OI) {
2198 Value *Idx = *OI;
2199 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2200 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2201 if (Field)
2202 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2203 Ty = StTy->getElementType(Field);
2204 } else {
2205 Ty = cast<SequentialType>(Ty)->getElementType();
2206
2207 // Handle constant subscripts.
2208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2209 if (CI->getRawValue() == 0) continue;
2210
2211 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2212 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2213 else
2214 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2215 continue;
2216 }
2217
2218 // Ptr = Ptr + Idx * ElementSize;
2219
2220 // Cast Idx to UIntPtrTy if needed.
2221 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2222
2223 uint64_t ElementSize = TD.getTypeSize(Ty);
2224 // Mask off bits that should not be set.
2225 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2226 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2227
2228 // Multiply by the element size and add to the base.
2229 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2230 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2231 }
2232 }
2233
2234 // Make sure that the offset fits in uintptr_t.
2235 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2236 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2237
2238 // Okay, we have now emitted all of the variable index parts to the BB that
2239 // the GEP is defined in. Loop over all of the using instructions, inserting
2240 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002241 // instruction to use the newly computed value, making GEPI dead. When the
2242 // user is a load or store instruction address, we emit the add into the user
2243 // block, otherwise we use a canonical version right next to the gep (these
2244 // won't be foldable as addresses, so we might as well share the computation).
2245
Chris Lattner35397782005-12-05 07:10:48 +00002246 std::map<BasicBlock*,Value*> InsertedExprs;
2247 while (!GEPI->use_empty()) {
2248 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002249
2250 // If this use is not foldable into the addressing mode, use a version
2251 // emitted in the GEP block.
2252 Value *NewVal;
2253 if (!isa<LoadInst>(User) &&
2254 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2255 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2256 Ptr, PtrOffset);
2257 } else {
2258 // Otherwise, insert the code in the User's block so it can be folded into
2259 // any users in that block.
2260 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002261 User->getParent(), GEPI,
2262 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002263 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002264 User->replaceUsesOfWith(GEPI, NewVal);
2265 }
Chris Lattner35397782005-12-05 07:10:48 +00002266
2267 // Finally, the GEP is dead, remove it.
2268 GEPI->eraseFromParent();
2269}
2270
Chris Lattner7a60d912005-01-07 07:47:53 +00002271bool SelectionDAGISel::runOnFunction(Function &Fn) {
2272 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2273 RegMap = MF.getSSARegMap();
2274 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2275
Chris Lattner35397782005-12-05 07:10:48 +00002276 // First, split all critical edges for PHI nodes with incoming values that are
2277 // constants, this way the load of the constant into a vreg will not be placed
2278 // into MBBs that are used some other way.
2279 //
2280 // In this pass we also look for GEP instructions that are used across basic
2281 // blocks and rewrites them to improve basic-block-at-a-time selection.
2282 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002283 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2284 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002285 BasicBlock::iterator BBI;
2286 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2288 if (isa<Constant>(PN->getIncomingValue(i)))
2289 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002290
2291 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2292 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2293 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002294 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002295
Chris Lattner7a60d912005-01-07 07:47:53 +00002296 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2297
2298 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2299 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002300
Chris Lattner7a60d912005-01-07 07:47:53 +00002301 return true;
2302}
2303
2304
Chris Lattner718b5c22005-01-13 17:59:43 +00002305SDOperand SelectionDAGISel::
2306CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002307 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002308 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002309 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002310 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002311
2312 // If this type is not legal, we must make sure to not create an invalid
2313 // register use.
2314 MVT::ValueType SrcVT = Op.getValueType();
2315 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2316 SelectionDAG &DAG = SDL.DAG;
2317 if (SrcVT == DestVT) {
2318 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002319 } else if (SrcVT == MVT::Vector) {
2320 // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2321
2322 // Figure out the right, legal destination reg to copy into.
2323 const PackedType *PTy = cast<PackedType>(V->getType());
2324 unsigned NumElts = PTy->getNumElements();
2325 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2326
2327 unsigned NumVectorRegs = 1;
2328
2329 // Divide the input until we get to a supported size. This will always
2330 // end with a scalar if the target doesn't support vectors.
2331 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2332 NumElts >>= 1;
2333 NumVectorRegs <<= 1;
2334 }
2335
2336 MVT::ValueType VT;
2337 if (NumElts == 1)
2338 VT = EltTy;
2339 else
2340 VT = getVectorType(EltTy, NumElts);
2341
2342 // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2343 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2344 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002345 } else if (SrcVT < DestVT) {
2346 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002347 if (MVT::isFloatingPoint(SrcVT))
2348 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2349 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002350 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002351 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2352 } else {
2353 // The src value is expanded into multiple registers.
2354 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2355 Op, DAG.getConstant(0, MVT::i32));
2356 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2357 Op, DAG.getConstant(1, MVT::i32));
2358 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2359 return DAG.getCopyToReg(Op, Reg+1, Hi);
2360 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002361}
2362
Chris Lattner16f64df2005-01-17 17:15:02 +00002363void SelectionDAGISel::
2364LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2365 std::vector<SDOperand> &UnorderedChains) {
2366 // If this is the entry block, emit arguments.
2367 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002368 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002369 SDOperand OldRoot = SDL.DAG.getRoot();
2370 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002371
Chris Lattner6871b232005-10-30 19:42:35 +00002372 unsigned a = 0;
2373 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2374 AI != E; ++AI, ++a)
2375 if (!AI->use_empty()) {
2376 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002377
Chris Lattner6871b232005-10-30 19:42:35 +00002378 // If this argument is live outside of the entry block, insert a copy from
2379 // whereever we got it to the vreg that other BB's will reference it as.
2380 if (FuncInfo.ValueMap.count(AI)) {
2381 SDOperand Copy =
2382 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2383 UnorderedChains.push_back(Copy);
2384 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002385 }
Chris Lattner6871b232005-10-30 19:42:35 +00002386
2387 // Next, if the function has live ins that need to be copied into vregs,
2388 // emit the copies now, into the top of the block.
2389 MachineFunction &MF = SDL.DAG.getMachineFunction();
2390 if (MF.livein_begin() != MF.livein_end()) {
2391 SSARegMap *RegMap = MF.getSSARegMap();
2392 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2393 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2394 E = MF.livein_end(); LI != E; ++LI)
2395 if (LI->second)
2396 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2397 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002398 }
Chris Lattner6871b232005-10-30 19:42:35 +00002399
2400 // Finally, if the target has anything special to do, allow it to do so.
2401 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002402}
2403
2404
Chris Lattner7a60d912005-01-07 07:47:53 +00002405void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2406 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2407 FunctionLoweringInfo &FuncInfo) {
2408 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002409
2410 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002411
Chris Lattner6871b232005-10-30 19:42:35 +00002412 // Lower any arguments needed in this block if this is the entry block.
2413 if (LLVMBB == &LLVMBB->getParent()->front())
2414 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002415
2416 BB = FuncInfo.MBBMap[LLVMBB];
2417 SDL.setCurrentBasicBlock(BB);
2418
2419 // Lower all of the non-terminator instructions.
2420 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2421 I != E; ++I)
2422 SDL.visit(*I);
2423
2424 // Ensure that all instructions which are used outside of their defining
2425 // blocks are available as virtual registers.
2426 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002427 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002428 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002429 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002430 UnorderedChains.push_back(
2431 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002432 }
2433
2434 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2435 // ensure constants are generated when needed. Remember the virtual registers
2436 // that need to be added to the Machine PHI nodes as input. We cannot just
2437 // directly add them, because expansion might result in multiple MBB's for one
2438 // BB. As such, the start of the BB might correspond to a different MBB than
2439 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002440 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002441
2442 // Emit constants only once even if used by multiple PHI nodes.
2443 std::map<Constant*, unsigned> ConstantsOut;
2444
2445 // Check successor nodes PHI nodes that expect a constant to be available from
2446 // this block.
2447 TerminatorInst *TI = LLVMBB->getTerminator();
2448 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2449 BasicBlock *SuccBB = TI->getSuccessor(succ);
2450 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2451 PHINode *PN;
2452
2453 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2454 // nodes and Machine PHI nodes, but the incoming operands have not been
2455 // emitted yet.
2456 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002457 (PN = dyn_cast<PHINode>(I)); ++I)
2458 if (!PN->use_empty()) {
2459 unsigned Reg;
2460 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2461 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2462 unsigned &RegOut = ConstantsOut[C];
2463 if (RegOut == 0) {
2464 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002465 UnorderedChains.push_back(
2466 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002467 }
2468 Reg = RegOut;
2469 } else {
2470 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002471 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002472 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002473 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2474 "Didn't codegen value into a register!??");
2475 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002476 UnorderedChains.push_back(
2477 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002478 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002479 }
Misha Brukman835702a2005-04-21 22:36:52 +00002480
Chris Lattner8ea875f2005-01-07 21:34:19 +00002481 // Remember that this register needs to added to the machine PHI node as
2482 // the input for this MBB.
2483 unsigned NumElements =
2484 TLI.getNumElements(TLI.getValueType(PN->getType()));
2485 for (unsigned i = 0, e = NumElements; i != e; ++i)
2486 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002487 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002488 }
2489 ConstantsOut.clear();
2490
Chris Lattner718b5c22005-01-13 17:59:43 +00002491 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002492 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002493 SDOperand Root = SDL.getRoot();
2494 if (Root.getOpcode() != ISD::EntryToken) {
2495 unsigned i = 0, e = UnorderedChains.size();
2496 for (; i != e; ++i) {
2497 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2498 if (UnorderedChains[i].Val->getOperand(0) == Root)
2499 break; // Don't add the root if we already indirectly depend on it.
2500 }
2501
2502 if (i == e)
2503 UnorderedChains.push_back(Root);
2504 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002505 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2506 }
2507
Chris Lattner7a60d912005-01-07 07:47:53 +00002508 // Lower the terminator after the copies are emitted.
2509 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002510
2511 // Make sure the root of the DAG is up-to-date.
2512 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002513}
2514
2515void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2516 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002517 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002518 CurDAG = &DAG;
2519 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2520
2521 // First step, lower LLVM code to some DAG. This DAG may use operations and
2522 // types that are not supported by the target.
2523 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2524
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002525 // Run the DAG combiner in pre-legalize mode.
2526 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002527
Chris Lattner7a60d912005-01-07 07:47:53 +00002528 DEBUG(std::cerr << "Lowered selection DAG:\n");
2529 DEBUG(DAG.dump());
2530
2531 // Second step, hack on the DAG until it only uses operations and types that
2532 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002533 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002534
2535 DEBUG(std::cerr << "Legalized selection DAG:\n");
2536 DEBUG(DAG.dump());
2537
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002538 // Run the DAG combiner in post-legalize mode.
2539 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002540
Evan Cheng739a6a42006-01-21 02:32:06 +00002541 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002542
Chris Lattner5ca31d92005-03-30 01:10:47 +00002543 // Third, instruction select all of the operations to machine code, adding the
2544 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002545 InstructionSelectBasicBlock(DAG);
2546
Chris Lattner7a60d912005-01-07 07:47:53 +00002547 DEBUG(std::cerr << "Selected machine code:\n");
2548 DEBUG(BB->dump());
2549
Chris Lattner5ca31d92005-03-30 01:10:47 +00002550 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002551 // PHI nodes in successors.
2552 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2553 MachineInstr *PHI = PHINodesToUpdate[i].first;
2554 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2555 "This is not a machine PHI node that we are updating!");
2556 PHI->addRegOperand(PHINodesToUpdate[i].second);
2557 PHI->addMachineBasicBlockOperand(BB);
2558 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002559
2560 // Finally, add the CFG edges from the last selected MBB to the successor
2561 // MBBs.
2562 TerminatorInst *TI = LLVMBB->getTerminator();
2563 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2564 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2565 BB->addSuccessor(Succ0MBB);
2566 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002567}
Evan Cheng739a6a42006-01-21 02:32:06 +00002568
2569//===----------------------------------------------------------------------===//
2570/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2571/// target node in the graph.
2572void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2573 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002574 ScheduleDAG *SL = NULL;
2575
2576 switch (ISHeuristic) {
2577 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002578 case defaultScheduling:
2579 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2580 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2581 else /* TargetLowering::SchedulingForRegPressure */
2582 SL = createBURRListDAGScheduler(DAG, BB);
2583 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002584 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002585 SL = createBFS_DAGScheduler(DAG, BB);
2586 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002587 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002588 SL = createSimpleDAGScheduler(false, DAG, BB);
2589 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002590 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002591 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002592 break;
Evan Cheng31272342006-01-23 08:26:10 +00002593 case listSchedulingBURR:
2594 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002595 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002596 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002597 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002598 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002599 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002600 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002601 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002602}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002603
Chris Lattner543832d2006-03-08 04:25:59 +00002604HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2605 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002606}
2607
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002608/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2609/// by tblgen. Others should not call it.
2610void SelectionDAGISel::
2611SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2612 std::vector<SDOperand> InOps;
2613 std::swap(InOps, Ops);
2614
2615 Ops.push_back(InOps[0]); // input chain.
2616 Ops.push_back(InOps[1]); // input asm string.
2617
2618 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2619 unsigned i = 2, e = InOps.size();
2620 if (InOps[e-1].getValueType() == MVT::Flag)
2621 --e; // Don't process a flag operand if it is here.
2622
2623 while (i != e) {
2624 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2625 if ((Flags & 7) != 4 /*MEM*/) {
2626 // Just skip over this operand, copying the operands verbatim.
2627 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2628 i += (Flags >> 3) + 1;
2629 } else {
2630 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2631 // Otherwise, this is a memory operand. Ask the target to select it.
2632 std::vector<SDOperand> SelOps;
2633 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2634 std::cerr << "Could not match memory address. Inline asm failure!\n";
2635 exit(1);
2636 }
2637
2638 // Add this to the output node.
2639 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2640 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2641 i += 2;
2642 }
2643 }
2644
2645 // Add the flag input back if present.
2646 if (e != InOps.size())
2647 Ops.push_back(InOps.back());
2648}