blob: 50cb958a6d5119b5d2bd95a262fb1c63cd30f0aa [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"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner49409cb2006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
185/// PHI nodes or outside of the basic block that defines it.
186static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
187 if (isa<PHINode>(I)) return true;
188 BasicBlock *BB = I->getParent();
189 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
190 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
191 return true;
192 return false;
193}
194
Chris Lattner6871b232005-10-30 19:42:35 +0000195/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
196/// entry block, return true.
197static bool isOnlyUsedInEntryBlock(Argument *A) {
198 BasicBlock *Entry = A->getParent()->begin();
199 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != Entry)
201 return false; // Use not in entry block.
202 return true;
203}
204
Chris Lattner7a60d912005-01-07 07:47:53 +0000205FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000206 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
208
Chris Lattner6871b232005-10-30 19:42:35 +0000209 // Create a vreg for each argument register that is not dead and is used
210 // outside of the entry block for the function.
211 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
212 AI != E; ++AI)
213 if (!isOnlyUsedInEntryBlock(AI))
214 InitializeRegForValue(AI);
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216 // Initialize the mapping of values to registers. This is only set up for
217 // instruction values that are used outside of the block that defines
218 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000219 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
222 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
223 const Type *Ty = AI->getAllocatedType();
224 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000225 unsigned Align =
226 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
227 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000228
229 // If the alignment of the value is smaller than the size of the value,
230 // and if the size of the value is particularly small (<= 8 bytes),
231 // round up to the size of the value for potentially better performance.
232 //
233 // FIXME: This could be made better with a preferred alignment hook in
234 // TargetData. It serves primarily to 8-byte align doubles for X86.
235 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000236 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000237 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000239 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 }
241
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000242 for (; BB != EB; ++BB)
243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
245 if (!isa<AllocaInst>(I) ||
246 !StaticAllocaMap.count(cast<AllocaInst>(I)))
247 InitializeRegForValue(I);
248
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000252 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
254 MBBMap[BB] = MBB;
255 MF.getBasicBlockList().push_back(MBB);
256
257 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
258 // appropriate.
259 PHINode *PN;
260 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000261 (PN = dyn_cast<PHINode>(I)); ++I)
262 if (!PN->use_empty()) {
263 unsigned NumElements =
264 TLI.getNumElements(TLI.getValueType(PN->getType()));
265 unsigned PHIReg = ValueMap[PN];
266 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
267 for (unsigned i = 0; i != NumElements; ++i)
268 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
269 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000270 }
271}
272
Chris Lattner49409cb2006-03-16 19:51:18 +0000273/// CreateRegForValue - Allocate the appropriate number of virtual registers of
274/// the correctly promoted or expanded types. Assign these registers
275/// consecutive vreg numbers and return the first assigned number.
276unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278
279 // The number of multiples of registers that we need, to, e.g., split up
280 // a <2 x int64> -> 4 x i32 registers.
281 unsigned NumVectorRegs = 1;
282
283 // If this is a packed type, figure out what type it will decompose into
284 // and how many of the elements it will use.
285 if (VT == MVT::Vector) {
286 const PackedType *PTy = cast<PackedType>(V->getType());
287 unsigned NumElts = PTy->getNumElements();
288 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
289
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
293 NumElts >>= 1;
294 NumVectorRegs <<= 1;
295 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000296 if (NumElts == 1)
297 VT = EltTy;
298 else
299 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000300 }
301
302 // The common case is that we will only create one register for this
303 // value. If we have that case, create and return the virtual register.
304 unsigned NV = TLI.getNumElements(VT);
305 if (NV == 1) {
306 // If we are promoting this value, pick the next largest supported type.
307 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
308 unsigned Reg = MakeReg(PromotedType);
309 // If this is a vector of supported or promoted types (e.g. 4 x i16),
310 // create all of the registers.
311 for (unsigned i = 1; i != NumVectorRegs; ++i)
312 MakeReg(PromotedType);
313 return Reg;
314 }
315
316 // If this value is represented with multiple target registers, make sure
317 // to create enough consecutive registers of the right (smaller) type.
318 unsigned NT = VT-1; // Find the type to use.
319 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
320 --NT;
321
322 unsigned R = MakeReg((MVT::ValueType)NT);
323 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
324 MakeReg((MVT::ValueType)NT);
325 return R;
326}
Chris Lattner7a60d912005-01-07 07:47:53 +0000327
328//===----------------------------------------------------------------------===//
329/// SelectionDAGLowering - This is the common target-independent lowering
330/// implementation that is parameterized by a TargetLowering object.
331/// Also, targets can overload any lowering method.
332///
333namespace llvm {
334class SelectionDAGLowering {
335 MachineBasicBlock *CurMBB;
336
337 std::map<const Value*, SDOperand> NodeMap;
338
Chris Lattner4d9651c2005-01-17 22:19:26 +0000339 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
340 /// them up and then emit token factor nodes when possible. This allows us to
341 /// get simple disambiguation between loads without worrying about alias
342 /// analysis.
343 std::vector<SDOperand> PendingLoads;
344
Chris Lattner7a60d912005-01-07 07:47:53 +0000345public:
346 // TLI - This is information that describes the available target features we
347 // need for lowering. This indicates when operations are unavailable,
348 // implemented with a libcall, etc.
349 TargetLowering &TLI;
350 SelectionDAG &DAG;
351 const TargetData &TD;
352
353 /// FuncInfo - Information about the function as a whole.
354 ///
355 FunctionLoweringInfo &FuncInfo;
356
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000358 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000359 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
360 FuncInfo(funcinfo) {
361 }
362
Chris Lattner4108bb02005-01-17 19:43:36 +0000363 /// getRoot - Return the current virtual root of the Selection DAG.
364 ///
365 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000366 if (PendingLoads.empty())
367 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000368
Chris Lattner4d9651c2005-01-17 22:19:26 +0000369 if (PendingLoads.size() == 1) {
370 SDOperand Root = PendingLoads[0];
371 DAG.setRoot(Root);
372 PendingLoads.clear();
373 return Root;
374 }
375
376 // Otherwise, we have to make a token factor node.
377 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
378 PendingLoads.clear();
379 DAG.setRoot(Root);
380 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000381 }
382
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 void visit(Instruction &I) { visit(I.getOpcode(), I); }
384
385 void visit(unsigned Opcode, User &I) {
386 switch (Opcode) {
387 default: assert(0 && "Unknown instruction type encountered!");
388 abort();
389 // Build the switch statement using the Instruction.def file.
390#define HANDLE_INST(NUM, OPCODE, CLASS) \
391 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
392#include "llvm/Instruction.def"
393 }
394 }
395
396 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
397
Chris Lattner4024c002006-03-15 22:19:46 +0000398 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
399 SDOperand SrcValue, SDOperand Root,
400 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000401
402 SDOperand getIntPtrConstant(uint64_t Val) {
403 return DAG.getConstant(Val, TLI.getPointerTy());
404 }
405
Chris Lattner8471b152006-03-16 19:57:50 +0000406 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407
408 const SDOperand &setValue(const Value *V, SDOperand NewN) {
409 SDOperand &N = NodeMap[V];
410 assert(N.Val == 0 && "Already set a value for this node!");
411 return N = NewN;
412 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000413
Chris Lattner6f87d182006-02-22 22:37:12 +0000414 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
415 MVT::ValueType VT,
416 bool OutReg, bool InReg,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
419
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
424
425 // These all get lowered before this pass.
426 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
427 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
428 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
429
430 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000431 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000432 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000433 void visitAdd(User &I) {
434 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000435 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000436 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000437 void visitMul(User &I) {
438 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000439 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000441 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000442 visitBinary(I,
443 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
444 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 }
446 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000447 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000448 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000449 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000450 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
451 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
452 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000453 void visitShl(User &I) { visitShift(I, ISD::SHL); }
454 void visitShr(User &I) {
455 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 }
457
458 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
459 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
460 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
461 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
462 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
463 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
464 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
465
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000466 void visitExtractElement(ExtractElementInst &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000467 void visitInsertElement(InsertElementInst &I);
468
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 void visitGetElementPtr(User &I);
470 void visitCast(User &I);
471 void visitSelect(User &I);
472 //
473
474 void visitMalloc(MallocInst &I);
475 void visitFree(FreeInst &I);
476 void visitAlloca(AllocaInst &I);
477 void visitLoad(LoadInst &I);
478 void visitStore(StoreInst &I);
479 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
480 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000481 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000482 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000483
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 void visitVAArg(VAArgInst &I);
486 void visitVAEnd(CallInst &I);
487 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000488 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489
Chris Lattner875def92005-01-11 05:56:49 +0000490 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000491
492 void visitUserOp1(Instruction &I) {
493 assert(0 && "UserOp1 should not exist at instruction selection time!");
494 abort();
495 }
496 void visitUserOp2(Instruction &I) {
497 assert(0 && "UserOp2 should not exist at instruction selection time!");
498 abort();
499 }
500};
501} // end namespace llvm
502
Chris Lattner8471b152006-03-16 19:57:50 +0000503SDOperand SelectionDAGLowering::getValue(const Value *V) {
504 SDOperand &N = NodeMap[V];
505 if (N.Val) return N;
506
507 const Type *VTy = V->getType();
508 MVT::ValueType VT = TLI.getValueType(VTy);
509 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
511 visit(CE->getOpcode(), *CE);
512 assert(N.Val && "visit didn't populate the ValueMap!");
513 return N;
514 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
515 return N = DAG.getGlobalAddress(GV, VT);
516 } else if (isa<ConstantPointerNull>(C)) {
517 return N = DAG.getConstant(0, TLI.getPointerTy());
518 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000519 if (!isa<PackedType>(VTy))
520 return N = DAG.getNode(ISD::UNDEF, VT);
521
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000522 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000523 const PackedType *PTy = cast<PackedType>(VTy);
524 unsigned NumElements = PTy->getNumElements();
525 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
526
527 std::vector<SDOperand> Ops;
528 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
529
530 // Create a VConstant node with generic Vector type.
531 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
532 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000533 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000534 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
535 return N = DAG.getConstantFP(CFP->getValue(), VT);
536 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
537 unsigned NumElements = PTy->getNumElements();
538 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000539
540 // Now that we know the number and type of the elements, push a
541 // Constant or ConstantFP node onto the ops list for each element of
542 // the packed constant.
543 std::vector<SDOperand> Ops;
544 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
545 if (MVT::isFloatingPoint(PVT)) {
546 for (unsigned i = 0; i != NumElements; ++i) {
547 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
548 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
549 }
550 } else {
551 for (unsigned i = 0; i != NumElements; ++i) {
552 const ConstantIntegral *El =
553 cast<ConstantIntegral>(CP->getOperand(i));
554 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
555 }
556 }
557 } else {
558 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
559 SDOperand Op;
560 if (MVT::isFloatingPoint(PVT))
561 Op = DAG.getConstantFP(0, PVT);
562 else
563 Op = DAG.getConstant(0, PVT);
564 Ops.assign(NumElements, Op);
565 }
566
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000567 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000568 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
569 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000570 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000571 } else {
572 // Canonicalize all constant ints to be unsigned.
573 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
574 }
575 }
576
577 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
578 std::map<const AllocaInst*, int>::iterator SI =
579 FuncInfo.StaticAllocaMap.find(AI);
580 if (SI != FuncInfo.StaticAllocaMap.end())
581 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
582 }
583
584 std::map<const Value*, unsigned>::const_iterator VMI =
585 FuncInfo.ValueMap.find(V);
586 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
587
588 unsigned InReg = VMI->second;
589
590 // If this type is not legal, make it so now.
591 if (VT == MVT::Vector) {
592 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
593 const PackedType *PTy = cast<PackedType>(VTy);
594 unsigned NumElements = PTy->getNumElements();
595 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
596 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
597 assert(TLI.isTypeLegal(TVT) &&
598 "FIXME: Cannot handle illegal vector types here yet!");
599 VT = TVT;
600 }
601
602 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
603
604 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
605 if (DestVT < VT) {
606 // Source must be expanded. This input value is actually coming from the
607 // register pair VMI->second and VMI->second+1.
608 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
609 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
610 } else {
611 if (DestVT > VT) { // Promotion case
612 if (MVT::isFloatingPoint(VT))
613 N = DAG.getNode(ISD::FP_ROUND, VT, N);
614 else
615 N = DAG.getNode(ISD::TRUNCATE, VT, N);
616 }
617 }
618
619 return N;
620}
621
622
Chris Lattner7a60d912005-01-07 07:47:53 +0000623void SelectionDAGLowering::visitRet(ReturnInst &I) {
624 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000625 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000626 return;
627 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000628 std::vector<SDOperand> NewValues;
629 NewValues.push_back(getRoot());
630 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
631 SDOperand RetOp = getValue(I.getOperand(i));
632
633 // If this is an integer return value, we need to promote it ourselves to
634 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
635 // than sign/zero.
636 if (MVT::isInteger(RetOp.getValueType()) &&
637 RetOp.getValueType() < MVT::i64) {
638 MVT::ValueType TmpVT;
639 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
640 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
641 else
642 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000643
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000644 if (I.getOperand(i)->getType()->isSigned())
645 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
646 else
647 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
648 }
649 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000650 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000651 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000652}
653
654void SelectionDAGLowering::visitBr(BranchInst &I) {
655 // Update machine-CFG edges.
656 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000657
658 // Figure out which block is immediately after the current one.
659 MachineBasicBlock *NextBlock = 0;
660 MachineFunction::iterator BBI = CurMBB;
661 if (++BBI != CurMBB->getParent()->end())
662 NextBlock = BBI;
663
664 if (I.isUnconditional()) {
665 // If this is not a fall-through branch, emit the branch.
666 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000667 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000668 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000669 } else {
670 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000671
672 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000673 if (Succ1MBB == NextBlock) {
674 // If the condition is false, fall through. This means we should branch
675 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000676 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000677 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000678 } else if (Succ0MBB == NextBlock) {
679 // If the condition is true, fall through. This means we should branch if
680 // the condition is false to Succ #1. Invert the condition first.
681 SDOperand True = DAG.getConstant(1, Cond.getValueType());
682 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000683 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000684 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000685 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000686 std::vector<SDOperand> Ops;
687 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000688 // If the false case is the current basic block, then this is a self
689 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
690 // adds an extra instruction in the loop. Instead, invert the
691 // condition and emit "Loop: ... br!cond Loop; br Out.
692 if (CurMBB == Succ1MBB) {
693 std::swap(Succ0MBB, Succ1MBB);
694 SDOperand True = DAG.getConstant(1, Cond.getValueType());
695 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
696 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000697 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
698 DAG.getBasicBlock(Succ0MBB));
699 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
700 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000701 }
702 }
703}
704
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000705void SelectionDAGLowering::visitSub(User &I) {
706 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000707 if (I.getType()->isFloatingPoint()) {
708 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
709 if (CFP->isExactlyValue(-0.0)) {
710 SDOperand Op2 = getValue(I.getOperand(1));
711 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
712 return;
713 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000714 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000715 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000716}
717
Nate Begemanb2e089c2005-11-19 00:36:38 +0000718void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
719 unsigned VecOp) {
720 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000721 SDOperand Op1 = getValue(I.getOperand(0));
722 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000723
Chris Lattner19baba62005-11-19 18:40:42 +0000724 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000725 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
726 } else if (Ty->isFloatingPoint()) {
727 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
728 } else {
729 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000730 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
731 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
732 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000733 }
Nate Begeman127321b2005-11-18 07:42:56 +0000734}
Chris Lattner96c26752005-01-19 22:31:21 +0000735
Nate Begeman127321b2005-11-18 07:42:56 +0000736void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
737 SDOperand Op1 = getValue(I.getOperand(0));
738 SDOperand Op2 = getValue(I.getOperand(1));
739
740 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
741
Chris Lattner7a60d912005-01-07 07:47:53 +0000742 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
743}
744
745void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
746 ISD::CondCode UnsignedOpcode) {
747 SDOperand Op1 = getValue(I.getOperand(0));
748 SDOperand Op2 = getValue(I.getOperand(1));
749 ISD::CondCode Opcode = SignedOpcode;
750 if (I.getOperand(0)->getType()->isUnsigned())
751 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000752 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000753}
754
755void SelectionDAGLowering::visitSelect(User &I) {
756 SDOperand Cond = getValue(I.getOperand(0));
757 SDOperand TrueVal = getValue(I.getOperand(1));
758 SDOperand FalseVal = getValue(I.getOperand(2));
759 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
760 TrueVal, FalseVal));
761}
762
763void SelectionDAGLowering::visitCast(User &I) {
764 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000765 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
766 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000767
Chris Lattner4024c002006-03-15 22:19:46 +0000768 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000769 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000770 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000771 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000772 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000773 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000774 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000775 } else if (isInteger(SrcVT)) {
776 if (isInteger(DestVT)) { // Int -> Int cast
777 if (DestVT < SrcVT) // Truncating cast?
778 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000779 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000780 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000781 else
Chris Lattner4024c002006-03-15 22:19:46 +0000782 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000783 } else { // Int -> FP cast
784 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000785 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000786 else
Chris Lattner4024c002006-03-15 22:19:46 +0000787 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000788 }
Chris Lattner4024c002006-03-15 22:19:46 +0000789 } else if (isFloatingPoint(SrcVT)) {
790 if (isFloatingPoint(DestVT)) { // FP -> FP cast
791 if (DestVT < SrcVT) // Rounding cast?
792 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000793 else
Chris Lattner4024c002006-03-15 22:19:46 +0000794 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000795 } else { // FP -> Int cast.
796 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000797 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000798 else
Chris Lattner4024c002006-03-15 22:19:46 +0000799 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
800 }
801 } else {
Chris Lattner32206f52006-03-18 01:44:44 +0000802 assert(0 && "Cannot bitconvert vectors yet!");
803#if 0
Chris Lattner4024c002006-03-15 22:19:46 +0000804 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
805 const PackedType *DstTy = cast<PackedType>(I.getType());
806
807 unsigned SrcNumElements = SrcTy->getNumElements();
808 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
809 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
810
811 unsigned DstNumElements = DstTy->getNumElements();
812 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
813 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
814
815 // If the input and output type are legal, convert this to a bit convert of
816 // the SrcTVT/DstTVT types.
817 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
818 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
819 assert(N.getValueType() == SrcTVT);
820 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
821 } else {
822 // Otherwise, convert this directly into a store/load.
823 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
824 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
825 // Create the stack frame object.
826 uint64_t ByteSize = TD.getTypeSize(SrcTy);
827 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
828 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
829 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
830 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
831
832 // Emit a store to the stack slot.
833 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
834 N, FIPtr, DAG.getSrcValue(NULL));
835 // Result is a load from the stack slot.
836 SDOperand Val =
837 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
838 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000839 }
Chris Lattner32206f52006-03-18 01:44:44 +0000840#endif
Chris Lattner7a60d912005-01-07 07:47:53 +0000841 }
842}
843
Chris Lattner32206f52006-03-18 01:44:44 +0000844void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
Chris Lattner32206f52006-03-18 01:44:44 +0000845 SDOperand InVec = getValue(I.getOperand(0));
846 SDOperand InVal = getValue(I.getOperand(1));
847 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
848 getValue(I.getOperand(2)));
849
Chris Lattner29b23012006-03-19 01:17:20 +0000850 SDOperand Num = *(InVec.Val->op_end()-2);
851 SDOperand Typ = *(InVec.Val->op_end()-1);
852 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
853 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +0000854}
855
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000856void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
857 SDOperand InVec = getValue(I.getOperand(0));
858 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
859 getValue(I.getOperand(1)));
860 SDOperand Typ = *(InVec.Val->op_end()-1);
861 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
862 TLI.getValueType(I.getType()), InVec, InIdx));
863}
Chris Lattner32206f52006-03-18 01:44:44 +0000864
Chris Lattner7a60d912005-01-07 07:47:53 +0000865void SelectionDAGLowering::visitGetElementPtr(User &I) {
866 SDOperand N = getValue(I.getOperand(0));
867 const Type *Ty = I.getOperand(0)->getType();
868 const Type *UIntPtrTy = TD.getIntPtrType();
869
870 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
871 OI != E; ++OI) {
872 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000873 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000874 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
875 if (Field) {
876 // N = N + Offset
877 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
878 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000879 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000880 }
881 Ty = StTy->getElementType(Field);
882 } else {
883 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000884
Chris Lattner43535a12005-11-09 04:45:33 +0000885 // If this is a constant subscript, handle it quickly.
886 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
887 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000888
Chris Lattner43535a12005-11-09 04:45:33 +0000889 uint64_t Offs;
890 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
891 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
892 else
893 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
894 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
895 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000896 }
Chris Lattner43535a12005-11-09 04:45:33 +0000897
898 // N = N + Idx * ElementSize;
899 uint64_t ElementSize = TD.getTypeSize(Ty);
900 SDOperand IdxN = getValue(Idx);
901
902 // If the index is smaller or larger than intptr_t, truncate or extend
903 // it.
904 if (IdxN.getValueType() < N.getValueType()) {
905 if (Idx->getType()->isSigned())
906 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
907 else
908 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
909 } else if (IdxN.getValueType() > N.getValueType())
910 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
911
912 // If this is a multiply by a power of two, turn it into a shl
913 // immediately. This is a very common case.
914 if (isPowerOf2_64(ElementSize)) {
915 unsigned Amt = Log2_64(ElementSize);
916 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000917 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000918 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
919 continue;
920 }
921
922 SDOperand Scale = getIntPtrConstant(ElementSize);
923 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
924 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000925 }
926 }
927 setValue(&I, N);
928}
929
930void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
931 // If this is a fixed sized alloca in the entry block of the function,
932 // allocate it statically on the stack.
933 if (FuncInfo.StaticAllocaMap.count(&I))
934 return; // getValue will auto-populate this.
935
936 const Type *Ty = I.getAllocatedType();
937 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000938 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
939 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000940
941 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000942 MVT::ValueType IntPtr = TLI.getPointerTy();
943 if (IntPtr < AllocSize.getValueType())
944 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
945 else if (IntPtr > AllocSize.getValueType())
946 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000947
Chris Lattnereccb73d2005-01-22 23:04:37 +0000948 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000949 getIntPtrConstant(TySize));
950
951 // Handle alignment. If the requested alignment is less than or equal to the
952 // stack alignment, ignore it and round the size of the allocation up to the
953 // stack alignment size. If the size is greater than the stack alignment, we
954 // note this in the DYNAMIC_STACKALLOC node.
955 unsigned StackAlign =
956 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
957 if (Align <= StackAlign) {
958 Align = 0;
959 // Add SA-1 to the size.
960 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
961 getIntPtrConstant(StackAlign-1));
962 // Mask out the low bits for alignment purposes.
963 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
964 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
965 }
966
Chris Lattner96c262e2005-05-14 07:29:57 +0000967 std::vector<MVT::ValueType> VTs;
968 VTs.push_back(AllocSize.getValueType());
969 VTs.push_back(MVT::Other);
970 std::vector<SDOperand> Ops;
971 Ops.push_back(getRoot());
972 Ops.push_back(AllocSize);
973 Ops.push_back(getIntPtrConstant(Align));
974 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000975 DAG.setRoot(setValue(&I, DSA).getValue(1));
976
977 // Inform the Frame Information that we have just allocated a variable-sized
978 // object.
979 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
980}
981
Chris Lattner7a60d912005-01-07 07:47:53 +0000982void SelectionDAGLowering::visitLoad(LoadInst &I) {
983 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000984
Chris Lattner4d9651c2005-01-17 22:19:26 +0000985 SDOperand Root;
986 if (I.isVolatile())
987 Root = getRoot();
988 else {
989 // Do not serialize non-volatile loads against each other.
990 Root = DAG.getRoot();
991 }
Chris Lattner4024c002006-03-15 22:19:46 +0000992
993 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
994 Root, I.isVolatile()));
995}
996
997SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
998 SDOperand SrcValue, SDOperand Root,
999 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001000 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001001 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001002 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001003 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001004 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001005 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001006 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001007
Chris Lattner4024c002006-03-15 22:19:46 +00001008 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001009 DAG.setRoot(L.getValue(1));
1010 else
1011 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001012
1013 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001014}
1015
1016
1017void SelectionDAGLowering::visitStore(StoreInst &I) {
1018 Value *SrcV = I.getOperand(0);
1019 SDOperand Src = getValue(SrcV);
1020 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001021 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001022 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001023}
1024
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001025/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1026/// we want to emit this as a call to a named external function, return the name
1027/// otherwise lower it and return null.
1028const char *
1029SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1030 switch (Intrinsic) {
1031 case Intrinsic::vastart: visitVAStart(I); return 0;
1032 case Intrinsic::vaend: visitVAEnd(I); return 0;
1033 case Intrinsic::vacopy: visitVACopy(I); return 0;
1034 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1035 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1036 case Intrinsic::setjmp:
1037 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1038 break;
1039 case Intrinsic::longjmp:
1040 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1041 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001042 case Intrinsic::memcpy_i32:
1043 case Intrinsic::memcpy_i64:
1044 visitMemIntrinsic(I, ISD::MEMCPY);
1045 return 0;
1046 case Intrinsic::memset_i32:
1047 case Intrinsic::memset_i64:
1048 visitMemIntrinsic(I, ISD::MEMSET);
1049 return 0;
1050 case Intrinsic::memmove_i32:
1051 case Intrinsic::memmove_i64:
1052 visitMemIntrinsic(I, ISD::MEMMOVE);
1053 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001054
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001055 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001056 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001057 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001058 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001059
Jim Laskey5995d012006-02-11 01:01:30 +00001060 // Input Chain
1061 Ops.push_back(getRoot());
1062
1063 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001064 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001065
1066 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001067 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001068
Jim Laskeyacb6e342006-03-13 13:07:37 +00001069 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001070 assert(DD && "Not a debug information descriptor");
1071 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1072 assert(CompileUnit && "Not a compile unit");
1073 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1074 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1075
1076 if (Ops.size() == 5) // Found filename/workingdir.
1077 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001078 }
1079
Chris Lattner8782b782005-12-03 18:50:48 +00001080 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001081 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001082 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001083 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001084 if (I.getType() != Type::VoidTy)
1085 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1086 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001087 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001088 if (I.getType() != Type::VoidTy)
1089 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1090 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001091 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001092 if (I.getType() != Type::VoidTy)
1093 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1094 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001095
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001096 case Intrinsic::isunordered_f32:
1097 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001098 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1099 getValue(I.getOperand(2)), ISD::SETUO));
1100 return 0;
1101
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001102 case Intrinsic::sqrt_f32:
1103 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001104 setValue(&I, DAG.getNode(ISD::FSQRT,
1105 getValue(I.getOperand(1)).getValueType(),
1106 getValue(I.getOperand(1))));
1107 return 0;
1108 case Intrinsic::pcmarker: {
1109 SDOperand Tmp = getValue(I.getOperand(1));
1110 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1111 return 0;
1112 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001113 case Intrinsic::readcyclecounter: {
1114 std::vector<MVT::ValueType> VTs;
1115 VTs.push_back(MVT::i64);
1116 VTs.push_back(MVT::Other);
1117 std::vector<SDOperand> Ops;
1118 Ops.push_back(getRoot());
1119 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1120 setValue(&I, Tmp);
1121 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001122 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001123 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001124 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001125 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001126 case Intrinsic::bswap_i64:
1127 setValue(&I, DAG.getNode(ISD::BSWAP,
1128 getValue(I.getOperand(1)).getValueType(),
1129 getValue(I.getOperand(1))));
1130 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001131 case Intrinsic::cttz_i8:
1132 case Intrinsic::cttz_i16:
1133 case Intrinsic::cttz_i32:
1134 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001135 setValue(&I, DAG.getNode(ISD::CTTZ,
1136 getValue(I.getOperand(1)).getValueType(),
1137 getValue(I.getOperand(1))));
1138 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001139 case Intrinsic::ctlz_i8:
1140 case Intrinsic::ctlz_i16:
1141 case Intrinsic::ctlz_i32:
1142 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001143 setValue(&I, DAG.getNode(ISD::CTLZ,
1144 getValue(I.getOperand(1)).getValueType(),
1145 getValue(I.getOperand(1))));
1146 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001147 case Intrinsic::ctpop_i8:
1148 case Intrinsic::ctpop_i16:
1149 case Intrinsic::ctpop_i32:
1150 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001151 setValue(&I, DAG.getNode(ISD::CTPOP,
1152 getValue(I.getOperand(1)).getValueType(),
1153 getValue(I.getOperand(1))));
1154 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001155 case Intrinsic::stacksave: {
1156 std::vector<MVT::ValueType> VTs;
1157 VTs.push_back(TLI.getPointerTy());
1158 VTs.push_back(MVT::Other);
1159 std::vector<SDOperand> Ops;
1160 Ops.push_back(getRoot());
1161 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1162 setValue(&I, Tmp);
1163 DAG.setRoot(Tmp.getValue(1));
1164 return 0;
1165 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001166 case Intrinsic::stackrestore: {
1167 SDOperand Tmp = getValue(I.getOperand(1));
1168 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001169 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001170 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001171 case Intrinsic::prefetch:
1172 // FIXME: Currently discarding prefetches.
1173 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001174 default:
1175 std::cerr << I;
1176 assert(0 && "This intrinsic is not implemented yet!");
1177 return 0;
1178 }
1179}
1180
1181
Chris Lattner7a60d912005-01-07 07:47:53 +00001182void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001183 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001184 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001185 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001186 if (unsigned IID = F->getIntrinsicID()) {
1187 RenameFn = visitIntrinsicCall(I, IID);
1188 if (!RenameFn)
1189 return;
1190 } else { // Not an LLVM intrinsic.
1191 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001192 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1193 if (I.getNumOperands() == 3 && // Basic sanity checks.
1194 I.getOperand(1)->getType()->isFloatingPoint() &&
1195 I.getType() == I.getOperand(1)->getType() &&
1196 I.getType() == I.getOperand(2)->getType()) {
1197 SDOperand LHS = getValue(I.getOperand(1));
1198 SDOperand RHS = getValue(I.getOperand(2));
1199 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1200 LHS, RHS));
1201 return;
1202 }
1203 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001204 if (I.getNumOperands() == 2 && // Basic sanity checks.
1205 I.getOperand(1)->getType()->isFloatingPoint() &&
1206 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001207 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001208 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1209 return;
1210 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001211 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001212 if (I.getNumOperands() == 2 && // Basic sanity checks.
1213 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001214 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001215 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001216 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1217 return;
1218 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001219 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001220 if (I.getNumOperands() == 2 && // Basic sanity checks.
1221 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001222 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001223 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001224 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1225 return;
1226 }
1227 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001228 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001229 } else if (isa<InlineAsm>(I.getOperand(0))) {
1230 visitInlineAsm(I);
1231 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001232 }
Misha Brukman835702a2005-04-21 22:36:52 +00001233
Chris Lattner18d2b342005-01-08 22:48:57 +00001234 SDOperand Callee;
1235 if (!RenameFn)
1236 Callee = getValue(I.getOperand(0));
1237 else
1238 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001239 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001240 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001241 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1242 Value *Arg = I.getOperand(i);
1243 SDOperand ArgNode = getValue(Arg);
1244 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1245 }
Misha Brukman835702a2005-04-21 22:36:52 +00001246
Nate Begemanf6565252005-03-26 01:29:23 +00001247 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1248 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001249
Chris Lattner1f45cd72005-01-08 19:26:18 +00001250 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001251 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001252 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001253 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001254 setValue(&I, Result.first);
1255 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001256}
1257
Chris Lattner6f87d182006-02-22 22:37:12 +00001258SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001259 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001260 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1261 Chain = Val.getValue(1);
1262 Flag = Val.getValue(2);
1263
1264 // If the result was expanded, copy from the top part.
1265 if (Regs.size() > 1) {
1266 assert(Regs.size() == 2 &&
1267 "Cannot expand to more than 2 elts yet!");
1268 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1269 Chain = Val.getValue(1);
1270 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001271 if (DAG.getTargetLoweringInfo().isLittleEndian())
1272 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1273 else
1274 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001275 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001276
Chris Lattner6f87d182006-02-22 22:37:12 +00001277 // Otherwise, if the return value was promoted, truncate it to the
1278 // appropriate type.
1279 if (RegVT == ValueVT)
1280 return Val;
1281
1282 if (MVT::isInteger(RegVT))
1283 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1284 else
1285 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1286}
1287
Chris Lattner571d9642006-02-23 19:21:04 +00001288/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1289/// specified value into the registers specified by this object. This uses
1290/// Chain/Flag as the input and updates them for the output Chain/Flag.
1291void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001292 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001293 if (Regs.size() == 1) {
1294 // If there is a single register and the types differ, this must be
1295 // a promotion.
1296 if (RegVT != ValueVT) {
1297 if (MVT::isInteger(RegVT))
1298 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1299 else
1300 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1301 }
1302 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1303 Flag = Chain.getValue(1);
1304 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001305 std::vector<unsigned> R(Regs);
1306 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1307 std::reverse(R.begin(), R.end());
1308
1309 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001310 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1311 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001312 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001313 Flag = Chain.getValue(1);
1314 }
1315 }
1316}
Chris Lattner6f87d182006-02-22 22:37:12 +00001317
Chris Lattner571d9642006-02-23 19:21:04 +00001318/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1319/// operand list. This adds the code marker and includes the number of
1320/// values added into it.
1321void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001322 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001323 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1324 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1325 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1326}
Chris Lattner6f87d182006-02-22 22:37:12 +00001327
1328/// isAllocatableRegister - If the specified register is safe to allocate,
1329/// i.e. it isn't a stack pointer or some other special register, return the
1330/// register class for the register. Otherwise, return null.
1331static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001332isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1333 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1334 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1335 E = MRI->regclass_end(); RCI != E; ++RCI) {
1336 const TargetRegisterClass *RC = *RCI;
1337 // If none of the the value types for this register class are valid, we
1338 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1339 bool isLegal = false;
1340 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1341 I != E; ++I) {
1342 if (TLI.isTypeLegal(*I)) {
1343 isLegal = true;
1344 break;
1345 }
1346 }
1347
1348 if (!isLegal) continue;
1349
Chris Lattner6f87d182006-02-22 22:37:12 +00001350 // NOTE: This isn't ideal. In particular, this might allocate the
1351 // frame pointer in functions that need it (due to them not being taken
1352 // out of allocation, because a variable sized allocation hasn't been seen
1353 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001354 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1355 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001356 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001357 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001358 }
1359 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001360}
1361
1362RegsForValue SelectionDAGLowering::
1363GetRegistersForValue(const std::string &ConstrCode,
1364 MVT::ValueType VT, bool isOutReg, bool isInReg,
1365 std::set<unsigned> &OutputRegs,
1366 std::set<unsigned> &InputRegs) {
1367 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1368 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1369 std::vector<unsigned> Regs;
1370
1371 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1372 MVT::ValueType RegVT;
1373 MVT::ValueType ValueVT = VT;
1374
1375 if (PhysReg.first) {
1376 if (VT == MVT::Other)
1377 ValueVT = *PhysReg.second->vt_begin();
1378 RegVT = VT;
1379
1380 // This is a explicit reference to a physical register.
1381 Regs.push_back(PhysReg.first);
1382
1383 // If this is an expanded reference, add the rest of the regs to Regs.
1384 if (NumRegs != 1) {
1385 RegVT = *PhysReg.second->vt_begin();
1386 TargetRegisterClass::iterator I = PhysReg.second->begin();
1387 TargetRegisterClass::iterator E = PhysReg.second->end();
1388 for (; *I != PhysReg.first; ++I)
1389 assert(I != E && "Didn't find reg!");
1390
1391 // Already added the first reg.
1392 --NumRegs; ++I;
1393 for (; NumRegs; --NumRegs, ++I) {
1394 assert(I != E && "Ran out of registers to allocate!");
1395 Regs.push_back(*I);
1396 }
1397 }
1398 return RegsForValue(Regs, RegVT, ValueVT);
1399 }
1400
1401 // This is a reference to a register class. Allocate NumRegs consecutive,
1402 // available, registers from the class.
1403 std::vector<unsigned> RegClassRegs =
1404 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1405
1406 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1407 MachineFunction &MF = *CurMBB->getParent();
1408 unsigned NumAllocated = 0;
1409 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1410 unsigned Reg = RegClassRegs[i];
1411 // See if this register is available.
1412 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1413 (isInReg && InputRegs.count(Reg))) { // Already used.
1414 // Make sure we find consecutive registers.
1415 NumAllocated = 0;
1416 continue;
1417 }
1418
1419 // Check to see if this register is allocatable (i.e. don't give out the
1420 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001421 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001422 if (!RC) {
1423 // Make sure we find consecutive registers.
1424 NumAllocated = 0;
1425 continue;
1426 }
1427
1428 // Okay, this register is good, we can use it.
1429 ++NumAllocated;
1430
1431 // If we allocated enough consecutive
1432 if (NumAllocated == NumRegs) {
1433 unsigned RegStart = (i-NumAllocated)+1;
1434 unsigned RegEnd = i+1;
1435 // Mark all of the allocated registers used.
1436 for (unsigned i = RegStart; i != RegEnd; ++i) {
1437 unsigned Reg = RegClassRegs[i];
1438 Regs.push_back(Reg);
1439 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1440 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1441 }
1442
1443 return RegsForValue(Regs, *RC->vt_begin(), VT);
1444 }
1445 }
1446
1447 // Otherwise, we couldn't allocate enough registers for this.
1448 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001449}
1450
Chris Lattner6f87d182006-02-22 22:37:12 +00001451
Chris Lattner476e67b2006-01-26 22:24:51 +00001452/// visitInlineAsm - Handle a call to an InlineAsm object.
1453///
1454void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1455 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1456
1457 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1458 MVT::Other);
1459
1460 // Note, we treat inline asms both with and without side-effects as the same.
1461 // If an inline asm doesn't have side effects and doesn't access memory, we
1462 // could not choose to not chain it.
1463 bool hasSideEffects = IA->hasSideEffects();
1464
Chris Lattner3a5ed552006-02-01 01:28:23 +00001465 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001466 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001467
1468 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1469 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1470 /// if it is a def of that register.
1471 std::vector<SDOperand> AsmNodeOperands;
1472 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1473 AsmNodeOperands.push_back(AsmStr);
1474
1475 SDOperand Chain = getRoot();
1476 SDOperand Flag;
1477
Chris Lattner1558fc62006-02-01 18:59:47 +00001478 // We fully assign registers here at isel time. This is not optimal, but
1479 // should work. For register classes that correspond to LLVM classes, we
1480 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1481 // over the constraints, collecting fixed registers that we know we can't use.
1482 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001483 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001484 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1485 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1486 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001487
Chris Lattner7ad77df2006-02-22 00:56:39 +00001488 MVT::ValueType OpVT;
1489
1490 // Compute the value type for each operand and add it to ConstraintVTs.
1491 switch (Constraints[i].Type) {
1492 case InlineAsm::isOutput:
1493 if (!Constraints[i].isIndirectOutput) {
1494 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1495 OpVT = TLI.getValueType(I.getType());
1496 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001497 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001498 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1499 OpNum++; // Consumes a call operand.
1500 }
1501 break;
1502 case InlineAsm::isInput:
1503 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1504 OpNum++; // Consumes a call operand.
1505 break;
1506 case InlineAsm::isClobber:
1507 OpVT = MVT::Other;
1508 break;
1509 }
1510
1511 ConstraintVTs.push_back(OpVT);
1512
Chris Lattner6f87d182006-02-22 22:37:12 +00001513 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1514 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001515
Chris Lattner6f87d182006-02-22 22:37:12 +00001516 // Build a list of regs that this operand uses. This always has a single
1517 // element for promoted/expanded operands.
1518 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1519 false, false,
1520 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001521
1522 switch (Constraints[i].Type) {
1523 case InlineAsm::isOutput:
1524 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001525 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001526 // If this is an early-clobber output, it cannot be assigned to the same
1527 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001528 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001529 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001530 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001531 case InlineAsm::isInput:
1532 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001533 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001534 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001535 case InlineAsm::isClobber:
1536 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001537 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1538 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001539 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001540 }
1541 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001542
Chris Lattner5c79f982006-02-21 23:12:12 +00001543 // Loop over all of the inputs, copying the operand values into the
1544 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001545 RegsForValue RetValRegs;
1546 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001547 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001548
Chris Lattner2e56e892006-01-31 02:03:41 +00001549 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001550 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1551 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001552
Chris Lattner3a5ed552006-02-01 01:28:23 +00001553 switch (Constraints[i].Type) {
1554 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001555 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1556 if (ConstraintCode.size() == 1) // not a physreg name.
1557 CTy = TLI.getConstraintType(ConstraintCode[0]);
1558
1559 if (CTy == TargetLowering::C_Memory) {
1560 // Memory output.
1561 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1562
1563 // Check that the operand (the address to store to) isn't a float.
1564 if (!MVT::isInteger(InOperandVal.getValueType()))
1565 assert(0 && "MATCH FAIL!");
1566
1567 if (!Constraints[i].isIndirectOutput)
1568 assert(0 && "MATCH FAIL!");
1569
1570 OpNum++; // Consumes a call operand.
1571
1572 // Extend/truncate to the right pointer type if needed.
1573 MVT::ValueType PtrType = TLI.getPointerTy();
1574 if (InOperandVal.getValueType() < PtrType)
1575 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1576 else if (InOperandVal.getValueType() > PtrType)
1577 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1578
1579 // Add information to the INLINEASM node to know about this output.
1580 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1581 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1582 AsmNodeOperands.push_back(InOperandVal);
1583 break;
1584 }
1585
1586 // Otherwise, this is a register output.
1587 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1588
Chris Lattner6f87d182006-02-22 22:37:12 +00001589 // If this is an early-clobber output, or if there is an input
1590 // constraint that matches this, we need to reserve the input register
1591 // so no other inputs allocate to it.
1592 bool UsesInputRegister = false;
1593 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1594 UsesInputRegister = true;
1595
1596 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001597 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001598 RegsForValue Regs =
1599 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1600 true, UsesInputRegister,
1601 OutputRegs, InputRegs);
1602 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001603
Chris Lattner3a5ed552006-02-01 01:28:23 +00001604 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001605 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001606 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001607 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001608 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001609 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001610 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1611 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001612 OpNum++; // Consumes a call operand.
1613 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001614
1615 // Add information to the INLINEASM node to know that this register is
1616 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001617 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001618 break;
1619 }
1620 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001621 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001622 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001623
Chris Lattner7f5880b2006-02-02 00:25:23 +00001624 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1625 // If this is required to match an output register we have already set,
1626 // just use its register.
1627 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001628
Chris Lattner571d9642006-02-23 19:21:04 +00001629 // Scan until we find the definition we already emitted of this operand.
1630 // When we find it, create a RegsForValue operand.
1631 unsigned CurOp = 2; // The first operand.
1632 for (; OperandNo; --OperandNo) {
1633 // Advance to the next operand.
1634 unsigned NumOps =
1635 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1636 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1637 "Skipped past definitions?");
1638 CurOp += (NumOps>>3)+1;
1639 }
1640
1641 unsigned NumOps =
1642 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1643 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1644 "Skipped past definitions?");
1645
1646 // Add NumOps>>3 registers to MatchedRegs.
1647 RegsForValue MatchedRegs;
1648 MatchedRegs.ValueVT = InOperandVal.getValueType();
1649 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1650 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1651 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1652 MatchedRegs.Regs.push_back(Reg);
1653 }
1654
1655 // Use the produced MatchedRegs object to
1656 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1657 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001658 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001659 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001660
1661 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1662 if (ConstraintCode.size() == 1) // not a physreg name.
1663 CTy = TLI.getConstraintType(ConstraintCode[0]);
1664
1665 if (CTy == TargetLowering::C_Other) {
1666 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1667 assert(0 && "MATCH FAIL!");
1668
1669 // Add information to the INLINEASM node to know about this input.
1670 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1671 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1672 AsmNodeOperands.push_back(InOperandVal);
1673 break;
1674 } else if (CTy == TargetLowering::C_Memory) {
1675 // Memory input.
1676
1677 // Check that the operand isn't a float.
1678 if (!MVT::isInteger(InOperandVal.getValueType()))
1679 assert(0 && "MATCH FAIL!");
1680
1681 // Extend/truncate to the right pointer type if needed.
1682 MVT::ValueType PtrType = TLI.getPointerTy();
1683 if (InOperandVal.getValueType() < PtrType)
1684 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1685 else if (InOperandVal.getValueType() > PtrType)
1686 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1687
1688 // Add information to the INLINEASM node to know about this input.
1689 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1690 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1691 AsmNodeOperands.push_back(InOperandVal);
1692 break;
1693 }
1694
1695 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1696
1697 // Copy the input into the appropriate registers.
1698 RegsForValue InRegs =
1699 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1700 false, true, OutputRegs, InputRegs);
1701 // FIXME: should be match fail.
1702 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1703
1704 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1705
1706 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001707 break;
1708 }
Chris Lattner571d9642006-02-23 19:21:04 +00001709 case InlineAsm::isClobber: {
1710 RegsForValue ClobberedRegs =
1711 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1712 OutputRegs, InputRegs);
1713 // Add the clobbered value to the operand list, so that the register
1714 // allocator is aware that the physreg got clobbered.
1715 if (!ClobberedRegs.Regs.empty())
1716 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001717 break;
1718 }
Chris Lattner571d9642006-02-23 19:21:04 +00001719 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001720 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001721
1722 // Finish up input operands.
1723 AsmNodeOperands[0] = Chain;
1724 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1725
1726 std::vector<MVT::ValueType> VTs;
1727 VTs.push_back(MVT::Other);
1728 VTs.push_back(MVT::Flag);
1729 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1730 Flag = Chain.getValue(1);
1731
Chris Lattner2e56e892006-01-31 02:03:41 +00001732 // If this asm returns a register value, copy the result from that register
1733 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001734 if (!RetValRegs.Regs.empty())
1735 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001736
Chris Lattner2e56e892006-01-31 02:03:41 +00001737 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1738
1739 // Process indirect outputs, first output all of the flagged copies out of
1740 // physregs.
1741 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001742 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001743 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001744 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1745 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001746 }
1747
1748 // Emit the non-flagged stores from the physregs.
1749 std::vector<SDOperand> OutChains;
1750 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1751 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1752 StoresToEmit[i].first,
1753 getValue(StoresToEmit[i].second),
1754 DAG.getSrcValue(StoresToEmit[i].second)));
1755 if (!OutChains.empty())
1756 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001757 DAG.setRoot(Chain);
1758}
1759
1760
Chris Lattner7a60d912005-01-07 07:47:53 +00001761void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1762 SDOperand Src = getValue(I.getOperand(0));
1763
1764 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001765
1766 if (IntPtr < Src.getValueType())
1767 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1768 else if (IntPtr > Src.getValueType())
1769 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001770
1771 // Scale the source by the type size.
1772 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1773 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1774 Src, getIntPtrConstant(ElementSize));
1775
1776 std::vector<std::pair<SDOperand, const Type*> > Args;
1777 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001778
1779 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001780 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001781 DAG.getExternalSymbol("malloc", IntPtr),
1782 Args, DAG);
1783 setValue(&I, Result.first); // Pointers always fit in registers
1784 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001785}
1786
1787void SelectionDAGLowering::visitFree(FreeInst &I) {
1788 std::vector<std::pair<SDOperand, const Type*> > Args;
1789 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1790 TLI.getTargetData().getIntPtrType()));
1791 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001792 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001793 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001794 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1795 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001796}
1797
Chris Lattner13d7c252005-08-26 20:54:47 +00001798// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1799// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1800// instructions are special in various ways, which require special support to
1801// insert. The specified MachineInstr is created but not inserted into any
1802// basic blocks, and the scheduler passes ownership of it to this method.
1803MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1804 MachineBasicBlock *MBB) {
1805 std::cerr << "If a target marks an instruction with "
1806 "'usesCustomDAGSchedInserter', it must implement "
1807 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1808 abort();
1809 return 0;
1810}
1811
Chris Lattner58cfd792005-01-09 00:00:49 +00001812void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001813 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1814 getValue(I.getOperand(1)),
1815 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001816}
1817
1818void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001819 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1820 getValue(I.getOperand(0)),
1821 DAG.getSrcValue(I.getOperand(0)));
1822 setValue(&I, V);
1823 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001824}
1825
1826void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001827 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1828 getValue(I.getOperand(1)),
1829 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001830}
1831
1832void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001833 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1834 getValue(I.getOperand(1)),
1835 getValue(I.getOperand(2)),
1836 DAG.getSrcValue(I.getOperand(1)),
1837 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001838}
1839
Chris Lattner58cfd792005-01-09 00:00:49 +00001840// It is always conservatively correct for llvm.returnaddress and
1841// llvm.frameaddress to return 0.
1842std::pair<SDOperand, SDOperand>
1843TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1844 unsigned Depth, SelectionDAG &DAG) {
1845 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001846}
1847
Chris Lattner29dcc712005-05-14 05:50:48 +00001848SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001849 assert(0 && "LowerOperation not implemented for this target!");
1850 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001851 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001852}
1853
Nate Begeman595ec732006-01-28 03:14:31 +00001854SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1855 SelectionDAG &DAG) {
1856 assert(0 && "CustomPromoteOperation not implemented for this target!");
1857 abort();
1858 return SDOperand();
1859}
1860
Chris Lattner58cfd792005-01-09 00:00:49 +00001861void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1862 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1863 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001864 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001865 setValue(&I, Result.first);
1866 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001867}
1868
Evan Cheng6781b6e2006-02-15 21:59:04 +00001869/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001870/// operand.
1871static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001872 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001873 MVT::ValueType CurVT = VT;
1874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1875 uint64_t Val = C->getValue() & 255;
1876 unsigned Shift = 8;
1877 while (CurVT != MVT::i8) {
1878 Val = (Val << Shift) | Val;
1879 Shift <<= 1;
1880 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001881 }
1882 return DAG.getConstant(Val, VT);
1883 } else {
1884 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1885 unsigned Shift = 8;
1886 while (CurVT != MVT::i8) {
1887 Value =
1888 DAG.getNode(ISD::OR, VT,
1889 DAG.getNode(ISD::SHL, VT, Value,
1890 DAG.getConstant(Shift, MVT::i8)), Value);
1891 Shift <<= 1;
1892 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001893 }
1894
1895 return Value;
1896 }
1897}
1898
Evan Cheng6781b6e2006-02-15 21:59:04 +00001899/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1900/// used when a memcpy is turned into a memset when the source is a constant
1901/// string ptr.
1902static SDOperand getMemsetStringVal(MVT::ValueType VT,
1903 SelectionDAG &DAG, TargetLowering &TLI,
1904 std::string &Str, unsigned Offset) {
1905 MVT::ValueType CurVT = VT;
1906 uint64_t Val = 0;
1907 unsigned MSB = getSizeInBits(VT) / 8;
1908 if (TLI.isLittleEndian())
1909 Offset = Offset + MSB - 1;
1910 for (unsigned i = 0; i != MSB; ++i) {
1911 Val = (Val << 8) | Str[Offset];
1912 Offset += TLI.isLittleEndian() ? -1 : 1;
1913 }
1914 return DAG.getConstant(Val, VT);
1915}
1916
Evan Cheng81fcea82006-02-14 08:22:34 +00001917/// getMemBasePlusOffset - Returns base and offset node for the
1918static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1919 SelectionDAG &DAG, TargetLowering &TLI) {
1920 MVT::ValueType VT = Base.getValueType();
1921 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1922}
1923
Evan Chengdb2a7a72006-02-14 20:12:38 +00001924/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001925/// to replace the memset / memcpy is below the threshold. It also returns the
1926/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001927static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1928 unsigned Limit, uint64_t Size,
1929 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001930 MVT::ValueType VT;
1931
1932 if (TLI.allowsUnalignedMemoryAccesses()) {
1933 VT = MVT::i64;
1934 } else {
1935 switch (Align & 7) {
1936 case 0:
1937 VT = MVT::i64;
1938 break;
1939 case 4:
1940 VT = MVT::i32;
1941 break;
1942 case 2:
1943 VT = MVT::i16;
1944 break;
1945 default:
1946 VT = MVT::i8;
1947 break;
1948 }
1949 }
1950
Evan Chengd5026102006-02-14 09:11:59 +00001951 MVT::ValueType LVT = MVT::i64;
1952 while (!TLI.isTypeLegal(LVT))
1953 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1954 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001955
Evan Chengd5026102006-02-14 09:11:59 +00001956 if (VT > LVT)
1957 VT = LVT;
1958
Evan Cheng04514992006-02-14 23:05:54 +00001959 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001960 while (Size != 0) {
1961 unsigned VTSize = getSizeInBits(VT) / 8;
1962 while (VTSize > Size) {
1963 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001964 VTSize >>= 1;
1965 }
Evan Chengd5026102006-02-14 09:11:59 +00001966 assert(MVT::isInteger(VT));
1967
1968 if (++NumMemOps > Limit)
1969 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001970 MemOps.push_back(VT);
1971 Size -= VTSize;
1972 }
Evan Chengd5026102006-02-14 09:11:59 +00001973
1974 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001975}
1976
Chris Lattner875def92005-01-11 05:56:49 +00001977void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001978 SDOperand Op1 = getValue(I.getOperand(1));
1979 SDOperand Op2 = getValue(I.getOperand(2));
1980 SDOperand Op3 = getValue(I.getOperand(3));
1981 SDOperand Op4 = getValue(I.getOperand(4));
1982 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1983 if (Align == 0) Align = 1;
1984
1985 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1986 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001987
1988 // Expand memset / memcpy to a series of load / store ops
1989 // if the size operand falls below a certain threshold.
1990 std::vector<SDOperand> OutChains;
1991 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001992 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001993 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001994 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1995 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001996 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001997 unsigned Offset = 0;
1998 for (unsigned i = 0; i < NumMemOps; i++) {
1999 MVT::ValueType VT = MemOps[i];
2000 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002001 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002002 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2003 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002004 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2005 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002006 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002007 Offset += VTSize;
2008 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002009 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002010 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002011 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002012 case ISD::MEMCPY: {
2013 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2014 Size->getValue(), Align, TLI)) {
2015 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002016 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002017 GlobalAddressSDNode *G = NULL;
2018 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002019 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002020
2021 if (Op2.getOpcode() == ISD::GlobalAddress)
2022 G = cast<GlobalAddressSDNode>(Op2);
2023 else if (Op2.getOpcode() == ISD::ADD &&
2024 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2025 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2026 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002027 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002028 }
2029 if (G) {
2030 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002031 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002032 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002033 if (!Str.empty()) {
2034 CopyFromStr = true;
2035 SrcOff += SrcDelta;
2036 }
2037 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002038 }
2039
Evan Chenge2038bd2006-02-15 01:54:51 +00002040 for (unsigned i = 0; i < NumMemOps; i++) {
2041 MVT::ValueType VT = MemOps[i];
2042 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002043 SDOperand Value, Chain, Store;
2044
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002045 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002046 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2047 Chain = getRoot();
2048 Store =
2049 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2050 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2051 DAG.getSrcValue(I.getOperand(1), DstOff));
2052 } else {
2053 Value = DAG.getLoad(VT, getRoot(),
2054 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2055 DAG.getSrcValue(I.getOperand(2), SrcOff));
2056 Chain = Value.getValue(1);
2057 Store =
2058 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2059 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2060 DAG.getSrcValue(I.getOperand(1), DstOff));
2061 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002062 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002063 SrcOff += VTSize;
2064 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002065 }
2066 }
2067 break;
2068 }
2069 }
2070
2071 if (!OutChains.empty()) {
2072 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2073 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002074 }
2075 }
2076
Chris Lattner875def92005-01-11 05:56:49 +00002077 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002078 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002079 Ops.push_back(Op1);
2080 Ops.push_back(Op2);
2081 Ops.push_back(Op3);
2082 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002083 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002084}
2085
Chris Lattner875def92005-01-11 05:56:49 +00002086//===----------------------------------------------------------------------===//
2087// SelectionDAGISel code
2088//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002089
2090unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2091 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2092}
2093
Chris Lattnerc9950c12005-08-17 06:37:43 +00002094void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002095 // FIXME: we only modify the CFG to split critical edges. This
2096 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002097}
Chris Lattner7a60d912005-01-07 07:47:53 +00002098
Chris Lattner35397782005-12-05 07:10:48 +00002099
2100/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2101/// casting to the type of GEPI.
2102static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2103 Value *Ptr, Value *PtrOffset) {
2104 if (V) return V; // Already computed.
2105
2106 BasicBlock::iterator InsertPt;
2107 if (BB == GEPI->getParent()) {
2108 // If insert into the GEP's block, insert right after the GEP.
2109 InsertPt = GEPI;
2110 ++InsertPt;
2111 } else {
2112 // Otherwise, insert at the top of BB, after any PHI nodes
2113 InsertPt = BB->begin();
2114 while (isa<PHINode>(InsertPt)) ++InsertPt;
2115 }
2116
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002117 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2118 // BB so that there is only one value live across basic blocks (the cast
2119 // operand).
2120 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2121 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2122 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2123
Chris Lattner35397782005-12-05 07:10:48 +00002124 // Add the offset, cast it to the right type.
2125 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2126 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2127 return V = Ptr;
2128}
2129
2130
2131/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2132/// selection, we want to be a bit careful about some things. In particular, if
2133/// we have a GEP instruction that is used in a different block than it is
2134/// defined, the addressing expression of the GEP cannot be folded into loads or
2135/// stores that use it. In this case, decompose the GEP and move constant
2136/// indices into blocks that use it.
2137static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2138 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002139 // If this GEP is only used inside the block it is defined in, there is no
2140 // need to rewrite it.
2141 bool isUsedOutsideDefBB = false;
2142 BasicBlock *DefBB = GEPI->getParent();
2143 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2144 UI != E; ++UI) {
2145 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2146 isUsedOutsideDefBB = true;
2147 break;
2148 }
2149 }
2150 if (!isUsedOutsideDefBB) return;
2151
2152 // If this GEP has no non-zero constant indices, there is nothing we can do,
2153 // ignore it.
2154 bool hasConstantIndex = false;
2155 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2156 E = GEPI->op_end(); OI != E; ++OI) {
2157 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2158 if (CI->getRawValue()) {
2159 hasConstantIndex = true;
2160 break;
2161 }
2162 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002163 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2164 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002165
2166 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2167 // constant offset (which we now know is non-zero) and deal with it later.
2168 uint64_t ConstantOffset = 0;
2169 const Type *UIntPtrTy = TD.getIntPtrType();
2170 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2171 const Type *Ty = GEPI->getOperand(0)->getType();
2172
2173 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2174 E = GEPI->op_end(); OI != E; ++OI) {
2175 Value *Idx = *OI;
2176 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2177 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2178 if (Field)
2179 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2180 Ty = StTy->getElementType(Field);
2181 } else {
2182 Ty = cast<SequentialType>(Ty)->getElementType();
2183
2184 // Handle constant subscripts.
2185 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2186 if (CI->getRawValue() == 0) continue;
2187
2188 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2189 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2190 else
2191 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2192 continue;
2193 }
2194
2195 // Ptr = Ptr + Idx * ElementSize;
2196
2197 // Cast Idx to UIntPtrTy if needed.
2198 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2199
2200 uint64_t ElementSize = TD.getTypeSize(Ty);
2201 // Mask off bits that should not be set.
2202 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2203 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2204
2205 // Multiply by the element size and add to the base.
2206 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2207 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2208 }
2209 }
2210
2211 // Make sure that the offset fits in uintptr_t.
2212 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2213 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2214
2215 // Okay, we have now emitted all of the variable index parts to the BB that
2216 // the GEP is defined in. Loop over all of the using instructions, inserting
2217 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002218 // instruction to use the newly computed value, making GEPI dead. When the
2219 // user is a load or store instruction address, we emit the add into the user
2220 // block, otherwise we use a canonical version right next to the gep (these
2221 // won't be foldable as addresses, so we might as well share the computation).
2222
Chris Lattner35397782005-12-05 07:10:48 +00002223 std::map<BasicBlock*,Value*> InsertedExprs;
2224 while (!GEPI->use_empty()) {
2225 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002226
2227 // If this use is not foldable into the addressing mode, use a version
2228 // emitted in the GEP block.
2229 Value *NewVal;
2230 if (!isa<LoadInst>(User) &&
2231 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2232 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2233 Ptr, PtrOffset);
2234 } else {
2235 // Otherwise, insert the code in the User's block so it can be folded into
2236 // any users in that block.
2237 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002238 User->getParent(), GEPI,
2239 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002240 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002241 User->replaceUsesOfWith(GEPI, NewVal);
2242 }
Chris Lattner35397782005-12-05 07:10:48 +00002243
2244 // Finally, the GEP is dead, remove it.
2245 GEPI->eraseFromParent();
2246}
2247
Chris Lattner7a60d912005-01-07 07:47:53 +00002248bool SelectionDAGISel::runOnFunction(Function &Fn) {
2249 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2250 RegMap = MF.getSSARegMap();
2251 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2252
Chris Lattner35397782005-12-05 07:10:48 +00002253 // First, split all critical edges for PHI nodes with incoming values that are
2254 // constants, this way the load of the constant into a vreg will not be placed
2255 // into MBBs that are used some other way.
2256 //
2257 // In this pass we also look for GEP instructions that are used across basic
2258 // blocks and rewrites them to improve basic-block-at-a-time selection.
2259 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002260 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2261 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002262 BasicBlock::iterator BBI;
2263 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002264 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2265 if (isa<Constant>(PN->getIncomingValue(i)))
2266 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002267
2268 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2269 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2270 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002271 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002272
Chris Lattner7a60d912005-01-07 07:47:53 +00002273 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2274
2275 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2276 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002277
Chris Lattner7a60d912005-01-07 07:47:53 +00002278 return true;
2279}
2280
2281
Chris Lattner718b5c22005-01-13 17:59:43 +00002282SDOperand SelectionDAGISel::
2283CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002284 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002285 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002286 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002287 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002288
2289 // If this type is not legal, we must make sure to not create an invalid
2290 // register use.
2291 MVT::ValueType SrcVT = Op.getValueType();
2292 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2293 SelectionDAG &DAG = SDL.DAG;
2294 if (SrcVT == DestVT) {
2295 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002296 } else if (SrcVT == MVT::Vector) {
2297 // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2298
2299 // Figure out the right, legal destination reg to copy into.
2300 const PackedType *PTy = cast<PackedType>(V->getType());
2301 unsigned NumElts = PTy->getNumElements();
2302 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2303
2304 unsigned NumVectorRegs = 1;
2305
2306 // Divide the input until we get to a supported size. This will always
2307 // end with a scalar if the target doesn't support vectors.
2308 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2309 NumElts >>= 1;
2310 NumVectorRegs <<= 1;
2311 }
2312
2313 MVT::ValueType VT;
2314 if (NumElts == 1)
2315 VT = EltTy;
2316 else
2317 VT = getVectorType(EltTy, NumElts);
2318
2319 // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2320 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2321 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002322 } else if (SrcVT < DestVT) {
2323 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002324 if (MVT::isFloatingPoint(SrcVT))
2325 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2326 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002327 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002328 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2329 } else {
2330 // The src value is expanded into multiple registers.
2331 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2332 Op, DAG.getConstant(0, MVT::i32));
2333 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2334 Op, DAG.getConstant(1, MVT::i32));
2335 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2336 return DAG.getCopyToReg(Op, Reg+1, Hi);
2337 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002338}
2339
Chris Lattner16f64df2005-01-17 17:15:02 +00002340void SelectionDAGISel::
2341LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2342 std::vector<SDOperand> &UnorderedChains) {
2343 // If this is the entry block, emit arguments.
2344 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002345 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002346 SDOperand OldRoot = SDL.DAG.getRoot();
2347 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002348
Chris Lattner6871b232005-10-30 19:42:35 +00002349 unsigned a = 0;
2350 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2351 AI != E; ++AI, ++a)
2352 if (!AI->use_empty()) {
2353 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002354
Chris Lattner6871b232005-10-30 19:42:35 +00002355 // If this argument is live outside of the entry block, insert a copy from
2356 // whereever we got it to the vreg that other BB's will reference it as.
2357 if (FuncInfo.ValueMap.count(AI)) {
2358 SDOperand Copy =
2359 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2360 UnorderedChains.push_back(Copy);
2361 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002362 }
Chris Lattner6871b232005-10-30 19:42:35 +00002363
2364 // Next, if the function has live ins that need to be copied into vregs,
2365 // emit the copies now, into the top of the block.
2366 MachineFunction &MF = SDL.DAG.getMachineFunction();
2367 if (MF.livein_begin() != MF.livein_end()) {
2368 SSARegMap *RegMap = MF.getSSARegMap();
2369 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2370 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2371 E = MF.livein_end(); LI != E; ++LI)
2372 if (LI->second)
2373 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2374 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002375 }
Chris Lattner6871b232005-10-30 19:42:35 +00002376
2377 // Finally, if the target has anything special to do, allow it to do so.
2378 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002379}
2380
2381
Chris Lattner7a60d912005-01-07 07:47:53 +00002382void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2383 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2384 FunctionLoweringInfo &FuncInfo) {
2385 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002386
2387 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002388
Chris Lattner6871b232005-10-30 19:42:35 +00002389 // Lower any arguments needed in this block if this is the entry block.
2390 if (LLVMBB == &LLVMBB->getParent()->front())
2391 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002392
2393 BB = FuncInfo.MBBMap[LLVMBB];
2394 SDL.setCurrentBasicBlock(BB);
2395
2396 // Lower all of the non-terminator instructions.
2397 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2398 I != E; ++I)
2399 SDL.visit(*I);
2400
2401 // Ensure that all instructions which are used outside of their defining
2402 // blocks are available as virtual registers.
2403 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002404 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002405 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002406 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002407 UnorderedChains.push_back(
2408 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002409 }
2410
2411 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2412 // ensure constants are generated when needed. Remember the virtual registers
2413 // that need to be added to the Machine PHI nodes as input. We cannot just
2414 // directly add them, because expansion might result in multiple MBB's for one
2415 // BB. As such, the start of the BB might correspond to a different MBB than
2416 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002417 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002418
2419 // Emit constants only once even if used by multiple PHI nodes.
2420 std::map<Constant*, unsigned> ConstantsOut;
2421
2422 // Check successor nodes PHI nodes that expect a constant to be available from
2423 // this block.
2424 TerminatorInst *TI = LLVMBB->getTerminator();
2425 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2426 BasicBlock *SuccBB = TI->getSuccessor(succ);
2427 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2428 PHINode *PN;
2429
2430 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2431 // nodes and Machine PHI nodes, but the incoming operands have not been
2432 // emitted yet.
2433 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002434 (PN = dyn_cast<PHINode>(I)); ++I)
2435 if (!PN->use_empty()) {
2436 unsigned Reg;
2437 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2438 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2439 unsigned &RegOut = ConstantsOut[C];
2440 if (RegOut == 0) {
2441 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002442 UnorderedChains.push_back(
2443 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002444 }
2445 Reg = RegOut;
2446 } else {
2447 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002448 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002449 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002450 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2451 "Didn't codegen value into a register!??");
2452 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002453 UnorderedChains.push_back(
2454 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002455 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002456 }
Misha Brukman835702a2005-04-21 22:36:52 +00002457
Chris Lattner8ea875f2005-01-07 21:34:19 +00002458 // Remember that this register needs to added to the machine PHI node as
2459 // the input for this MBB.
2460 unsigned NumElements =
2461 TLI.getNumElements(TLI.getValueType(PN->getType()));
2462 for (unsigned i = 0, e = NumElements; i != e; ++i)
2463 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002464 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002465 }
2466 ConstantsOut.clear();
2467
Chris Lattner718b5c22005-01-13 17:59:43 +00002468 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002469 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002470 SDOperand Root = SDL.getRoot();
2471 if (Root.getOpcode() != ISD::EntryToken) {
2472 unsigned i = 0, e = UnorderedChains.size();
2473 for (; i != e; ++i) {
2474 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2475 if (UnorderedChains[i].Val->getOperand(0) == Root)
2476 break; // Don't add the root if we already indirectly depend on it.
2477 }
2478
2479 if (i == e)
2480 UnorderedChains.push_back(Root);
2481 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002482 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2483 }
2484
Chris Lattner7a60d912005-01-07 07:47:53 +00002485 // Lower the terminator after the copies are emitted.
2486 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002487
2488 // Make sure the root of the DAG is up-to-date.
2489 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002490}
2491
2492void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2493 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002494 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002495 CurDAG = &DAG;
2496 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2497
2498 // First step, lower LLVM code to some DAG. This DAG may use operations and
2499 // types that are not supported by the target.
2500 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2501
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002502 // Run the DAG combiner in pre-legalize mode.
2503 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002504
Chris Lattner7a60d912005-01-07 07:47:53 +00002505 DEBUG(std::cerr << "Lowered selection DAG:\n");
2506 DEBUG(DAG.dump());
2507
2508 // Second step, hack on the DAG until it only uses operations and types that
2509 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002510 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002511
2512 DEBUG(std::cerr << "Legalized selection DAG:\n");
2513 DEBUG(DAG.dump());
2514
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002515 // Run the DAG combiner in post-legalize mode.
2516 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002517
Evan Cheng739a6a42006-01-21 02:32:06 +00002518 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002519
Chris Lattner5ca31d92005-03-30 01:10:47 +00002520 // Third, instruction select all of the operations to machine code, adding the
2521 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002522 InstructionSelectBasicBlock(DAG);
2523
Chris Lattner7a60d912005-01-07 07:47:53 +00002524 DEBUG(std::cerr << "Selected machine code:\n");
2525 DEBUG(BB->dump());
2526
Chris Lattner5ca31d92005-03-30 01:10:47 +00002527 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002528 // PHI nodes in successors.
2529 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2530 MachineInstr *PHI = PHINodesToUpdate[i].first;
2531 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2532 "This is not a machine PHI node that we are updating!");
2533 PHI->addRegOperand(PHINodesToUpdate[i].second);
2534 PHI->addMachineBasicBlockOperand(BB);
2535 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002536
2537 // Finally, add the CFG edges from the last selected MBB to the successor
2538 // MBBs.
2539 TerminatorInst *TI = LLVMBB->getTerminator();
2540 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2541 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2542 BB->addSuccessor(Succ0MBB);
2543 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002544}
Evan Cheng739a6a42006-01-21 02:32:06 +00002545
2546//===----------------------------------------------------------------------===//
2547/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2548/// target node in the graph.
2549void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2550 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002551 ScheduleDAG *SL = NULL;
2552
2553 switch (ISHeuristic) {
2554 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002555 case defaultScheduling:
2556 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2557 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2558 else /* TargetLowering::SchedulingForRegPressure */
2559 SL = createBURRListDAGScheduler(DAG, BB);
2560 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002561 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002562 SL = createBFS_DAGScheduler(DAG, BB);
2563 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002564 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002565 SL = createSimpleDAGScheduler(false, DAG, BB);
2566 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002567 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002568 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002569 break;
Evan Cheng31272342006-01-23 08:26:10 +00002570 case listSchedulingBURR:
2571 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002572 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002573 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002574 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002575 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002576 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002577 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002578 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002579}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002580
Chris Lattner543832d2006-03-08 04:25:59 +00002581HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2582 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002583}
2584
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002585/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2586/// by tblgen. Others should not call it.
2587void SelectionDAGISel::
2588SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2589 std::vector<SDOperand> InOps;
2590 std::swap(InOps, Ops);
2591
2592 Ops.push_back(InOps[0]); // input chain.
2593 Ops.push_back(InOps[1]); // input asm string.
2594
2595 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2596 unsigned i = 2, e = InOps.size();
2597 if (InOps[e-1].getValueType() == MVT::Flag)
2598 --e; // Don't process a flag operand if it is here.
2599
2600 while (i != e) {
2601 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2602 if ((Flags & 7) != 4 /*MEM*/) {
2603 // Just skip over this operand, copying the operands verbatim.
2604 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2605 i += (Flags >> 3) + 1;
2606 } else {
2607 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2608 // Otherwise, this is a memory operand. Ask the target to select it.
2609 std::vector<SDOperand> SelOps;
2610 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2611 std::cerr << "Could not match memory address. Inline asm failure!\n";
2612 exit(1);
2613 }
2614
2615 // Add this to the output node.
2616 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2617 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2618 i += 2;
2619 }
2620 }
2621
2622 // Add the flag input back if present.
2623 if (e != InOps.size())
2624 Ops.push_back(InOps.back());
2625}