blob: 184e2156c7727dd6e4ee4b812103fd58f37d6387 [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 Lattner2f4119a2006-03-22 20:09:35 +0000765 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +0000766 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000767
Chris Lattner2f4119a2006-03-22 20:09:35 +0000768 if (DestVT == MVT::Vector) {
769 // This is a cast to a vector from something else. This is always a bit
770 // convert. Get information about the input vector.
771 const PackedType *DestTy = cast<PackedType>(I.getType());
772 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
773 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
774 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
775 DAG.getValueType(EltVT)));
776 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000777 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000778 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000779 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000780 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000781 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000782 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000783 } else if (isInteger(SrcVT)) {
784 if (isInteger(DestVT)) { // Int -> Int cast
785 if (DestVT < SrcVT) // Truncating cast?
786 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000787 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000788 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000789 else
Chris Lattner4024c002006-03-15 22:19:46 +0000790 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000791 } else if (isFloatingPoint(SrcVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000792 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000793 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000794 else
Chris Lattner4024c002006-03-15 22:19:46 +0000795 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000796 } else {
797 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000798 }
Chris Lattner4024c002006-03-15 22:19:46 +0000799 } else if (isFloatingPoint(SrcVT)) {
800 if (isFloatingPoint(DestVT)) { // FP -> FP cast
801 if (DestVT < SrcVT) // Rounding cast?
802 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000803 else
Chris Lattner4024c002006-03-15 22:19:46 +0000804 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000805 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000806 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000807 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000808 else
Chris Lattner4024c002006-03-15 22:19:46 +0000809 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +0000810 } else {
811 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +0000812 }
813 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +0000814 assert(SrcVT == MVT::Vector && "Unknown cast!");
815 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
816 // This is a cast from a vector to something else. This is always a bit
817 // convert. Get information about the input vector.
818 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +0000819 }
820}
821
Chris Lattner32206f52006-03-18 01:44:44 +0000822void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
Chris Lattner32206f52006-03-18 01:44:44 +0000823 SDOperand InVec = getValue(I.getOperand(0));
824 SDOperand InVal = getValue(I.getOperand(1));
825 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
826 getValue(I.getOperand(2)));
827
Chris Lattner29b23012006-03-19 01:17:20 +0000828 SDOperand Num = *(InVec.Val->op_end()-2);
829 SDOperand Typ = *(InVec.Val->op_end()-1);
830 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
831 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +0000832}
833
Chris Lattner7c0cd8c2006-03-21 20:44:12 +0000834void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
835 SDOperand InVec = getValue(I.getOperand(0));
836 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
837 getValue(I.getOperand(1)));
838 SDOperand Typ = *(InVec.Val->op_end()-1);
839 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
840 TLI.getValueType(I.getType()), InVec, InIdx));
841}
Chris Lattner32206f52006-03-18 01:44:44 +0000842
Chris Lattner7a60d912005-01-07 07:47:53 +0000843void SelectionDAGLowering::visitGetElementPtr(User &I) {
844 SDOperand N = getValue(I.getOperand(0));
845 const Type *Ty = I.getOperand(0)->getType();
846 const Type *UIntPtrTy = TD.getIntPtrType();
847
848 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
849 OI != E; ++OI) {
850 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000851 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000852 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
853 if (Field) {
854 // N = N + Offset
855 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
856 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000857 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000858 }
859 Ty = StTy->getElementType(Field);
860 } else {
861 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000862
Chris Lattner43535a12005-11-09 04:45:33 +0000863 // If this is a constant subscript, handle it quickly.
864 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
865 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000866
Chris Lattner43535a12005-11-09 04:45:33 +0000867 uint64_t Offs;
868 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
869 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
870 else
871 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
872 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
873 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000874 }
Chris Lattner43535a12005-11-09 04:45:33 +0000875
876 // N = N + Idx * ElementSize;
877 uint64_t ElementSize = TD.getTypeSize(Ty);
878 SDOperand IdxN = getValue(Idx);
879
880 // If the index is smaller or larger than intptr_t, truncate or extend
881 // it.
882 if (IdxN.getValueType() < N.getValueType()) {
883 if (Idx->getType()->isSigned())
884 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
885 else
886 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
887 } else if (IdxN.getValueType() > N.getValueType())
888 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
889
890 // If this is a multiply by a power of two, turn it into a shl
891 // immediately. This is a very common case.
892 if (isPowerOf2_64(ElementSize)) {
893 unsigned Amt = Log2_64(ElementSize);
894 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000895 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000896 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
897 continue;
898 }
899
900 SDOperand Scale = getIntPtrConstant(ElementSize);
901 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
902 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000903 }
904 }
905 setValue(&I, N);
906}
907
908void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
909 // If this is a fixed sized alloca in the entry block of the function,
910 // allocate it statically on the stack.
911 if (FuncInfo.StaticAllocaMap.count(&I))
912 return; // getValue will auto-populate this.
913
914 const Type *Ty = I.getAllocatedType();
915 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000916 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
917 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000918
919 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000920 MVT::ValueType IntPtr = TLI.getPointerTy();
921 if (IntPtr < AllocSize.getValueType())
922 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
923 else if (IntPtr > AllocSize.getValueType())
924 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000925
Chris Lattnereccb73d2005-01-22 23:04:37 +0000926 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000927 getIntPtrConstant(TySize));
928
929 // Handle alignment. If the requested alignment is less than or equal to the
930 // stack alignment, ignore it and round the size of the allocation up to the
931 // stack alignment size. If the size is greater than the stack alignment, we
932 // note this in the DYNAMIC_STACKALLOC node.
933 unsigned StackAlign =
934 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
935 if (Align <= StackAlign) {
936 Align = 0;
937 // Add SA-1 to the size.
938 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
939 getIntPtrConstant(StackAlign-1));
940 // Mask out the low bits for alignment purposes.
941 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
942 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
943 }
944
Chris Lattner96c262e2005-05-14 07:29:57 +0000945 std::vector<MVT::ValueType> VTs;
946 VTs.push_back(AllocSize.getValueType());
947 VTs.push_back(MVT::Other);
948 std::vector<SDOperand> Ops;
949 Ops.push_back(getRoot());
950 Ops.push_back(AllocSize);
951 Ops.push_back(getIntPtrConstant(Align));
952 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000953 DAG.setRoot(setValue(&I, DSA).getValue(1));
954
955 // Inform the Frame Information that we have just allocated a variable-sized
956 // object.
957 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
958}
959
Chris Lattner7a60d912005-01-07 07:47:53 +0000960void SelectionDAGLowering::visitLoad(LoadInst &I) {
961 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000962
Chris Lattner4d9651c2005-01-17 22:19:26 +0000963 SDOperand Root;
964 if (I.isVolatile())
965 Root = getRoot();
966 else {
967 // Do not serialize non-volatile loads against each other.
968 Root = DAG.getRoot();
969 }
Chris Lattner4024c002006-03-15 22:19:46 +0000970
971 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
972 Root, I.isVolatile()));
973}
974
975SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
976 SDOperand SrcValue, SDOperand Root,
977 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000978 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000979 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000980 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +0000981 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000982 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000983 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000984 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000985
Chris Lattner4024c002006-03-15 22:19:46 +0000986 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +0000987 DAG.setRoot(L.getValue(1));
988 else
989 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +0000990
991 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +0000992}
993
994
995void SelectionDAGLowering::visitStore(StoreInst &I) {
996 Value *SrcV = I.getOperand(0);
997 SDOperand Src = getValue(SrcV);
998 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000999 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001000 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001001}
1002
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001003/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1004/// we want to emit this as a call to a named external function, return the name
1005/// otherwise lower it and return null.
1006const char *
1007SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1008 switch (Intrinsic) {
1009 case Intrinsic::vastart: visitVAStart(I); return 0;
1010 case Intrinsic::vaend: visitVAEnd(I); return 0;
1011 case Intrinsic::vacopy: visitVACopy(I); return 0;
1012 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1013 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1014 case Intrinsic::setjmp:
1015 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1016 break;
1017 case Intrinsic::longjmp:
1018 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1019 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001020 case Intrinsic::memcpy_i32:
1021 case Intrinsic::memcpy_i64:
1022 visitMemIntrinsic(I, ISD::MEMCPY);
1023 return 0;
1024 case Intrinsic::memset_i32:
1025 case Intrinsic::memset_i64:
1026 visitMemIntrinsic(I, ISD::MEMSET);
1027 return 0;
1028 case Intrinsic::memmove_i32:
1029 case Intrinsic::memmove_i64:
1030 visitMemIntrinsic(I, ISD::MEMMOVE);
1031 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001032
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001033 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001034 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001035 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001036 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001037
Jim Laskey5995d012006-02-11 01:01:30 +00001038 // Input Chain
1039 Ops.push_back(getRoot());
1040
1041 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001042 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001043
1044 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001045 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001046
Jim Laskeyacb6e342006-03-13 13:07:37 +00001047 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001048 assert(DD && "Not a debug information descriptor");
1049 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1050 assert(CompileUnit && "Not a compile unit");
1051 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1052 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1053
1054 if (Ops.size() == 5) // Found filename/workingdir.
1055 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001056 }
1057
Chris Lattner8782b782005-12-03 18:50:48 +00001058 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001059 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001060 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001061 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001062 if (I.getType() != Type::VoidTy)
1063 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1064 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001065 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001066 if (I.getType() != Type::VoidTy)
1067 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1068 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001069 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001070 if (I.getType() != Type::VoidTy)
1071 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1072 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001073
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001074 case Intrinsic::isunordered_f32:
1075 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001076 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1077 getValue(I.getOperand(2)), ISD::SETUO));
1078 return 0;
1079
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001080 case Intrinsic::sqrt_f32:
1081 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001082 setValue(&I, DAG.getNode(ISD::FSQRT,
1083 getValue(I.getOperand(1)).getValueType(),
1084 getValue(I.getOperand(1))));
1085 return 0;
1086 case Intrinsic::pcmarker: {
1087 SDOperand Tmp = getValue(I.getOperand(1));
1088 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1089 return 0;
1090 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001091 case Intrinsic::readcyclecounter: {
1092 std::vector<MVT::ValueType> VTs;
1093 VTs.push_back(MVT::i64);
1094 VTs.push_back(MVT::Other);
1095 std::vector<SDOperand> Ops;
1096 Ops.push_back(getRoot());
1097 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1098 setValue(&I, Tmp);
1099 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001100 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001101 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001102 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001103 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001104 case Intrinsic::bswap_i64:
1105 setValue(&I, DAG.getNode(ISD::BSWAP,
1106 getValue(I.getOperand(1)).getValueType(),
1107 getValue(I.getOperand(1))));
1108 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001109 case Intrinsic::cttz_i8:
1110 case Intrinsic::cttz_i16:
1111 case Intrinsic::cttz_i32:
1112 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001113 setValue(&I, DAG.getNode(ISD::CTTZ,
1114 getValue(I.getOperand(1)).getValueType(),
1115 getValue(I.getOperand(1))));
1116 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001117 case Intrinsic::ctlz_i8:
1118 case Intrinsic::ctlz_i16:
1119 case Intrinsic::ctlz_i32:
1120 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001121 setValue(&I, DAG.getNode(ISD::CTLZ,
1122 getValue(I.getOperand(1)).getValueType(),
1123 getValue(I.getOperand(1))));
1124 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001125 case Intrinsic::ctpop_i8:
1126 case Intrinsic::ctpop_i16:
1127 case Intrinsic::ctpop_i32:
1128 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001129 setValue(&I, DAG.getNode(ISD::CTPOP,
1130 getValue(I.getOperand(1)).getValueType(),
1131 getValue(I.getOperand(1))));
1132 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001133 case Intrinsic::stacksave: {
1134 std::vector<MVT::ValueType> VTs;
1135 VTs.push_back(TLI.getPointerTy());
1136 VTs.push_back(MVT::Other);
1137 std::vector<SDOperand> Ops;
1138 Ops.push_back(getRoot());
1139 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1140 setValue(&I, Tmp);
1141 DAG.setRoot(Tmp.getValue(1));
1142 return 0;
1143 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001144 case Intrinsic::stackrestore: {
1145 SDOperand Tmp = getValue(I.getOperand(1));
1146 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001147 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001148 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001149 case Intrinsic::prefetch:
1150 // FIXME: Currently discarding prefetches.
1151 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001152 default:
1153 std::cerr << I;
1154 assert(0 && "This intrinsic is not implemented yet!");
1155 return 0;
1156 }
1157}
1158
1159
Chris Lattner7a60d912005-01-07 07:47:53 +00001160void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001161 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001162 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001163 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001164 if (unsigned IID = F->getIntrinsicID()) {
1165 RenameFn = visitIntrinsicCall(I, IID);
1166 if (!RenameFn)
1167 return;
1168 } else { // Not an LLVM intrinsic.
1169 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001170 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1171 if (I.getNumOperands() == 3 && // Basic sanity checks.
1172 I.getOperand(1)->getType()->isFloatingPoint() &&
1173 I.getType() == I.getOperand(1)->getType() &&
1174 I.getType() == I.getOperand(2)->getType()) {
1175 SDOperand LHS = getValue(I.getOperand(1));
1176 SDOperand RHS = getValue(I.getOperand(2));
1177 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1178 LHS, RHS));
1179 return;
1180 }
1181 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001182 if (I.getNumOperands() == 2 && // Basic sanity checks.
1183 I.getOperand(1)->getType()->isFloatingPoint() &&
1184 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001185 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001186 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1187 return;
1188 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001189 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001190 if (I.getNumOperands() == 2 && // Basic sanity checks.
1191 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001192 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001193 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001194 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1195 return;
1196 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001197 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001198 if (I.getNumOperands() == 2 && // Basic sanity checks.
1199 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001200 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001201 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001202 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1203 return;
1204 }
1205 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001206 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001207 } else if (isa<InlineAsm>(I.getOperand(0))) {
1208 visitInlineAsm(I);
1209 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001210 }
Misha Brukman835702a2005-04-21 22:36:52 +00001211
Chris Lattner18d2b342005-01-08 22:48:57 +00001212 SDOperand Callee;
1213 if (!RenameFn)
1214 Callee = getValue(I.getOperand(0));
1215 else
1216 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001217 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001218 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001219 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1220 Value *Arg = I.getOperand(i);
1221 SDOperand ArgNode = getValue(Arg);
1222 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1223 }
Misha Brukman835702a2005-04-21 22:36:52 +00001224
Nate Begemanf6565252005-03-26 01:29:23 +00001225 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1226 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001227
Chris Lattner1f45cd72005-01-08 19:26:18 +00001228 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001229 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001230 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001231 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001232 setValue(&I, Result.first);
1233 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001234}
1235
Chris Lattner6f87d182006-02-22 22:37:12 +00001236SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001237 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001238 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1239 Chain = Val.getValue(1);
1240 Flag = Val.getValue(2);
1241
1242 // If the result was expanded, copy from the top part.
1243 if (Regs.size() > 1) {
1244 assert(Regs.size() == 2 &&
1245 "Cannot expand to more than 2 elts yet!");
1246 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1247 Chain = Val.getValue(1);
1248 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001249 if (DAG.getTargetLoweringInfo().isLittleEndian())
1250 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1251 else
1252 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001253 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001254
Chris Lattner6f87d182006-02-22 22:37:12 +00001255 // Otherwise, if the return value was promoted, truncate it to the
1256 // appropriate type.
1257 if (RegVT == ValueVT)
1258 return Val;
1259
1260 if (MVT::isInteger(RegVT))
1261 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1262 else
1263 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1264}
1265
Chris Lattner571d9642006-02-23 19:21:04 +00001266/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1267/// specified value into the registers specified by this object. This uses
1268/// Chain/Flag as the input and updates them for the output Chain/Flag.
1269void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001270 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001271 if (Regs.size() == 1) {
1272 // If there is a single register and the types differ, this must be
1273 // a promotion.
1274 if (RegVT != ValueVT) {
1275 if (MVT::isInteger(RegVT))
1276 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1277 else
1278 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1279 }
1280 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1281 Flag = Chain.getValue(1);
1282 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001283 std::vector<unsigned> R(Regs);
1284 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1285 std::reverse(R.begin(), R.end());
1286
1287 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001288 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1289 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001290 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001291 Flag = Chain.getValue(1);
1292 }
1293 }
1294}
Chris Lattner6f87d182006-02-22 22:37:12 +00001295
Chris Lattner571d9642006-02-23 19:21:04 +00001296/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1297/// operand list. This adds the code marker and includes the number of
1298/// values added into it.
1299void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001300 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001301 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1302 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1303 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1304}
Chris Lattner6f87d182006-02-22 22:37:12 +00001305
1306/// isAllocatableRegister - If the specified register is safe to allocate,
1307/// i.e. it isn't a stack pointer or some other special register, return the
1308/// register class for the register. Otherwise, return null.
1309static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001310isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1311 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1312 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1313 E = MRI->regclass_end(); RCI != E; ++RCI) {
1314 const TargetRegisterClass *RC = *RCI;
1315 // If none of the the value types for this register class are valid, we
1316 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1317 bool isLegal = false;
1318 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1319 I != E; ++I) {
1320 if (TLI.isTypeLegal(*I)) {
1321 isLegal = true;
1322 break;
1323 }
1324 }
1325
1326 if (!isLegal) continue;
1327
Chris Lattner6f87d182006-02-22 22:37:12 +00001328 // NOTE: This isn't ideal. In particular, this might allocate the
1329 // frame pointer in functions that need it (due to them not being taken
1330 // out of allocation, because a variable sized allocation hasn't been seen
1331 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001332 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1333 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001334 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001335 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001336 }
1337 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001338}
1339
1340RegsForValue SelectionDAGLowering::
1341GetRegistersForValue(const std::string &ConstrCode,
1342 MVT::ValueType VT, bool isOutReg, bool isInReg,
1343 std::set<unsigned> &OutputRegs,
1344 std::set<unsigned> &InputRegs) {
1345 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1346 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1347 std::vector<unsigned> Regs;
1348
1349 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1350 MVT::ValueType RegVT;
1351 MVT::ValueType ValueVT = VT;
1352
1353 if (PhysReg.first) {
1354 if (VT == MVT::Other)
1355 ValueVT = *PhysReg.second->vt_begin();
1356 RegVT = VT;
1357
1358 // This is a explicit reference to a physical register.
1359 Regs.push_back(PhysReg.first);
1360
1361 // If this is an expanded reference, add the rest of the regs to Regs.
1362 if (NumRegs != 1) {
1363 RegVT = *PhysReg.second->vt_begin();
1364 TargetRegisterClass::iterator I = PhysReg.second->begin();
1365 TargetRegisterClass::iterator E = PhysReg.second->end();
1366 for (; *I != PhysReg.first; ++I)
1367 assert(I != E && "Didn't find reg!");
1368
1369 // Already added the first reg.
1370 --NumRegs; ++I;
1371 for (; NumRegs; --NumRegs, ++I) {
1372 assert(I != E && "Ran out of registers to allocate!");
1373 Regs.push_back(*I);
1374 }
1375 }
1376 return RegsForValue(Regs, RegVT, ValueVT);
1377 }
1378
1379 // This is a reference to a register class. Allocate NumRegs consecutive,
1380 // available, registers from the class.
1381 std::vector<unsigned> RegClassRegs =
1382 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1383
1384 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1385 MachineFunction &MF = *CurMBB->getParent();
1386 unsigned NumAllocated = 0;
1387 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1388 unsigned Reg = RegClassRegs[i];
1389 // See if this register is available.
1390 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1391 (isInReg && InputRegs.count(Reg))) { // Already used.
1392 // Make sure we find consecutive registers.
1393 NumAllocated = 0;
1394 continue;
1395 }
1396
1397 // Check to see if this register is allocatable (i.e. don't give out the
1398 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001399 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001400 if (!RC) {
1401 // Make sure we find consecutive registers.
1402 NumAllocated = 0;
1403 continue;
1404 }
1405
1406 // Okay, this register is good, we can use it.
1407 ++NumAllocated;
1408
1409 // If we allocated enough consecutive
1410 if (NumAllocated == NumRegs) {
1411 unsigned RegStart = (i-NumAllocated)+1;
1412 unsigned RegEnd = i+1;
1413 // Mark all of the allocated registers used.
1414 for (unsigned i = RegStart; i != RegEnd; ++i) {
1415 unsigned Reg = RegClassRegs[i];
1416 Regs.push_back(Reg);
1417 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1418 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1419 }
1420
1421 return RegsForValue(Regs, *RC->vt_begin(), VT);
1422 }
1423 }
1424
1425 // Otherwise, we couldn't allocate enough registers for this.
1426 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001427}
1428
Chris Lattner6f87d182006-02-22 22:37:12 +00001429
Chris Lattner476e67b2006-01-26 22:24:51 +00001430/// visitInlineAsm - Handle a call to an InlineAsm object.
1431///
1432void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1433 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1434
1435 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1436 MVT::Other);
1437
1438 // Note, we treat inline asms both with and without side-effects as the same.
1439 // If an inline asm doesn't have side effects and doesn't access memory, we
1440 // could not choose to not chain it.
1441 bool hasSideEffects = IA->hasSideEffects();
1442
Chris Lattner3a5ed552006-02-01 01:28:23 +00001443 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001444 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001445
1446 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1447 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1448 /// if it is a def of that register.
1449 std::vector<SDOperand> AsmNodeOperands;
1450 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1451 AsmNodeOperands.push_back(AsmStr);
1452
1453 SDOperand Chain = getRoot();
1454 SDOperand Flag;
1455
Chris Lattner1558fc62006-02-01 18:59:47 +00001456 // We fully assign registers here at isel time. This is not optimal, but
1457 // should work. For register classes that correspond to LLVM classes, we
1458 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1459 // over the constraints, collecting fixed registers that we know we can't use.
1460 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001461 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001462 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1463 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1464 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001465
Chris Lattner7ad77df2006-02-22 00:56:39 +00001466 MVT::ValueType OpVT;
1467
1468 // Compute the value type for each operand and add it to ConstraintVTs.
1469 switch (Constraints[i].Type) {
1470 case InlineAsm::isOutput:
1471 if (!Constraints[i].isIndirectOutput) {
1472 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1473 OpVT = TLI.getValueType(I.getType());
1474 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001475 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001476 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1477 OpNum++; // Consumes a call operand.
1478 }
1479 break;
1480 case InlineAsm::isInput:
1481 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1482 OpNum++; // Consumes a call operand.
1483 break;
1484 case InlineAsm::isClobber:
1485 OpVT = MVT::Other;
1486 break;
1487 }
1488
1489 ConstraintVTs.push_back(OpVT);
1490
Chris Lattner6f87d182006-02-22 22:37:12 +00001491 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1492 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001493
Chris Lattner6f87d182006-02-22 22:37:12 +00001494 // Build a list of regs that this operand uses. This always has a single
1495 // element for promoted/expanded operands.
1496 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1497 false, false,
1498 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001499
1500 switch (Constraints[i].Type) {
1501 case InlineAsm::isOutput:
1502 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001503 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001504 // If this is an early-clobber output, it cannot be assigned to the same
1505 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001506 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001507 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001508 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001509 case InlineAsm::isInput:
1510 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001511 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001512 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001513 case InlineAsm::isClobber:
1514 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001515 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1516 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001517 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001518 }
1519 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001520
Chris Lattner5c79f982006-02-21 23:12:12 +00001521 // Loop over all of the inputs, copying the operand values into the
1522 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001523 RegsForValue RetValRegs;
1524 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001525 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001526
Chris Lattner2e56e892006-01-31 02:03:41 +00001527 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001528 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1529 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001530
Chris Lattner3a5ed552006-02-01 01:28:23 +00001531 switch (Constraints[i].Type) {
1532 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001533 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1534 if (ConstraintCode.size() == 1) // not a physreg name.
1535 CTy = TLI.getConstraintType(ConstraintCode[0]);
1536
1537 if (CTy == TargetLowering::C_Memory) {
1538 // Memory output.
1539 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1540
1541 // Check that the operand (the address to store to) isn't a float.
1542 if (!MVT::isInteger(InOperandVal.getValueType()))
1543 assert(0 && "MATCH FAIL!");
1544
1545 if (!Constraints[i].isIndirectOutput)
1546 assert(0 && "MATCH FAIL!");
1547
1548 OpNum++; // Consumes a call operand.
1549
1550 // Extend/truncate to the right pointer type if needed.
1551 MVT::ValueType PtrType = TLI.getPointerTy();
1552 if (InOperandVal.getValueType() < PtrType)
1553 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1554 else if (InOperandVal.getValueType() > PtrType)
1555 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1556
1557 // Add information to the INLINEASM node to know about this output.
1558 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1559 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1560 AsmNodeOperands.push_back(InOperandVal);
1561 break;
1562 }
1563
1564 // Otherwise, this is a register output.
1565 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1566
Chris Lattner6f87d182006-02-22 22:37:12 +00001567 // If this is an early-clobber output, or if there is an input
1568 // constraint that matches this, we need to reserve the input register
1569 // so no other inputs allocate to it.
1570 bool UsesInputRegister = false;
1571 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1572 UsesInputRegister = true;
1573
1574 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001575 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001576 RegsForValue Regs =
1577 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1578 true, UsesInputRegister,
1579 OutputRegs, InputRegs);
1580 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001581
Chris Lattner3a5ed552006-02-01 01:28:23 +00001582 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001583 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001584 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001585 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001586 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001587 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001588 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1589 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001590 OpNum++; // Consumes a call operand.
1591 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001592
1593 // Add information to the INLINEASM node to know that this register is
1594 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001595 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001596 break;
1597 }
1598 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001599 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001600 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001601
Chris Lattner7f5880b2006-02-02 00:25:23 +00001602 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1603 // If this is required to match an output register we have already set,
1604 // just use its register.
1605 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001606
Chris Lattner571d9642006-02-23 19:21:04 +00001607 // Scan until we find the definition we already emitted of this operand.
1608 // When we find it, create a RegsForValue operand.
1609 unsigned CurOp = 2; // The first operand.
1610 for (; OperandNo; --OperandNo) {
1611 // Advance to the next operand.
1612 unsigned NumOps =
1613 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1614 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1615 "Skipped past definitions?");
1616 CurOp += (NumOps>>3)+1;
1617 }
1618
1619 unsigned NumOps =
1620 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1621 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1622 "Skipped past definitions?");
1623
1624 // Add NumOps>>3 registers to MatchedRegs.
1625 RegsForValue MatchedRegs;
1626 MatchedRegs.ValueVT = InOperandVal.getValueType();
1627 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1628 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1629 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1630 MatchedRegs.Regs.push_back(Reg);
1631 }
1632
1633 // Use the produced MatchedRegs object to
1634 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1635 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001636 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001637 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001638
1639 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1640 if (ConstraintCode.size() == 1) // not a physreg name.
1641 CTy = TLI.getConstraintType(ConstraintCode[0]);
1642
1643 if (CTy == TargetLowering::C_Other) {
1644 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1645 assert(0 && "MATCH FAIL!");
1646
1647 // Add information to the INLINEASM node to know about this input.
1648 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1649 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1650 AsmNodeOperands.push_back(InOperandVal);
1651 break;
1652 } else if (CTy == TargetLowering::C_Memory) {
1653 // Memory input.
1654
1655 // Check that the operand isn't a float.
1656 if (!MVT::isInteger(InOperandVal.getValueType()))
1657 assert(0 && "MATCH FAIL!");
1658
1659 // Extend/truncate to the right pointer type if needed.
1660 MVT::ValueType PtrType = TLI.getPointerTy();
1661 if (InOperandVal.getValueType() < PtrType)
1662 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1663 else if (InOperandVal.getValueType() > PtrType)
1664 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1665
1666 // Add information to the INLINEASM node to know about this input.
1667 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1668 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1669 AsmNodeOperands.push_back(InOperandVal);
1670 break;
1671 }
1672
1673 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1674
1675 // Copy the input into the appropriate registers.
1676 RegsForValue InRegs =
1677 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1678 false, true, OutputRegs, InputRegs);
1679 // FIXME: should be match fail.
1680 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1681
1682 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1683
1684 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001685 break;
1686 }
Chris Lattner571d9642006-02-23 19:21:04 +00001687 case InlineAsm::isClobber: {
1688 RegsForValue ClobberedRegs =
1689 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1690 OutputRegs, InputRegs);
1691 // Add the clobbered value to the operand list, so that the register
1692 // allocator is aware that the physreg got clobbered.
1693 if (!ClobberedRegs.Regs.empty())
1694 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001695 break;
1696 }
Chris Lattner571d9642006-02-23 19:21:04 +00001697 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001698 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001699
1700 // Finish up input operands.
1701 AsmNodeOperands[0] = Chain;
1702 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1703
1704 std::vector<MVT::ValueType> VTs;
1705 VTs.push_back(MVT::Other);
1706 VTs.push_back(MVT::Flag);
1707 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1708 Flag = Chain.getValue(1);
1709
Chris Lattner2e56e892006-01-31 02:03:41 +00001710 // If this asm returns a register value, copy the result from that register
1711 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001712 if (!RetValRegs.Regs.empty())
1713 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001714
Chris Lattner2e56e892006-01-31 02:03:41 +00001715 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1716
1717 // Process indirect outputs, first output all of the flagged copies out of
1718 // physregs.
1719 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001720 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001721 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001722 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1723 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001724 }
1725
1726 // Emit the non-flagged stores from the physregs.
1727 std::vector<SDOperand> OutChains;
1728 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1729 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1730 StoresToEmit[i].first,
1731 getValue(StoresToEmit[i].second),
1732 DAG.getSrcValue(StoresToEmit[i].second)));
1733 if (!OutChains.empty())
1734 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001735 DAG.setRoot(Chain);
1736}
1737
1738
Chris Lattner7a60d912005-01-07 07:47:53 +00001739void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1740 SDOperand Src = getValue(I.getOperand(0));
1741
1742 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001743
1744 if (IntPtr < Src.getValueType())
1745 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1746 else if (IntPtr > Src.getValueType())
1747 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001748
1749 // Scale the source by the type size.
1750 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1751 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1752 Src, getIntPtrConstant(ElementSize));
1753
1754 std::vector<std::pair<SDOperand, const Type*> > Args;
1755 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001756
1757 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001758 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001759 DAG.getExternalSymbol("malloc", IntPtr),
1760 Args, DAG);
1761 setValue(&I, Result.first); // Pointers always fit in registers
1762 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001763}
1764
1765void SelectionDAGLowering::visitFree(FreeInst &I) {
1766 std::vector<std::pair<SDOperand, const Type*> > Args;
1767 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1768 TLI.getTargetData().getIntPtrType()));
1769 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001770 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001771 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001772 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1773 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001774}
1775
Chris Lattner13d7c252005-08-26 20:54:47 +00001776// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1777// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1778// instructions are special in various ways, which require special support to
1779// insert. The specified MachineInstr is created but not inserted into any
1780// basic blocks, and the scheduler passes ownership of it to this method.
1781MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1782 MachineBasicBlock *MBB) {
1783 std::cerr << "If a target marks an instruction with "
1784 "'usesCustomDAGSchedInserter', it must implement "
1785 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1786 abort();
1787 return 0;
1788}
1789
Chris Lattner58cfd792005-01-09 00:00:49 +00001790void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001791 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1792 getValue(I.getOperand(1)),
1793 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001794}
1795
1796void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001797 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1798 getValue(I.getOperand(0)),
1799 DAG.getSrcValue(I.getOperand(0)));
1800 setValue(&I, V);
1801 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001802}
1803
1804void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001805 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1806 getValue(I.getOperand(1)),
1807 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001808}
1809
1810void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001811 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1812 getValue(I.getOperand(1)),
1813 getValue(I.getOperand(2)),
1814 DAG.getSrcValue(I.getOperand(1)),
1815 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001816}
1817
Chris Lattner58cfd792005-01-09 00:00:49 +00001818// It is always conservatively correct for llvm.returnaddress and
1819// llvm.frameaddress to return 0.
1820std::pair<SDOperand, SDOperand>
1821TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1822 unsigned Depth, SelectionDAG &DAG) {
1823 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001824}
1825
Chris Lattner29dcc712005-05-14 05:50:48 +00001826SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001827 assert(0 && "LowerOperation not implemented for this target!");
1828 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001829 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001830}
1831
Nate Begeman595ec732006-01-28 03:14:31 +00001832SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1833 SelectionDAG &DAG) {
1834 assert(0 && "CustomPromoteOperation not implemented for this target!");
1835 abort();
1836 return SDOperand();
1837}
1838
Chris Lattner58cfd792005-01-09 00:00:49 +00001839void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1840 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1841 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001842 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001843 setValue(&I, Result.first);
1844 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001845}
1846
Evan Cheng6781b6e2006-02-15 21:59:04 +00001847/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001848/// operand.
1849static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001850 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001851 MVT::ValueType CurVT = VT;
1852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1853 uint64_t Val = C->getValue() & 255;
1854 unsigned Shift = 8;
1855 while (CurVT != MVT::i8) {
1856 Val = (Val << Shift) | Val;
1857 Shift <<= 1;
1858 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001859 }
1860 return DAG.getConstant(Val, VT);
1861 } else {
1862 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1863 unsigned Shift = 8;
1864 while (CurVT != MVT::i8) {
1865 Value =
1866 DAG.getNode(ISD::OR, VT,
1867 DAG.getNode(ISD::SHL, VT, Value,
1868 DAG.getConstant(Shift, MVT::i8)), Value);
1869 Shift <<= 1;
1870 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001871 }
1872
1873 return Value;
1874 }
1875}
1876
Evan Cheng6781b6e2006-02-15 21:59:04 +00001877/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1878/// used when a memcpy is turned into a memset when the source is a constant
1879/// string ptr.
1880static SDOperand getMemsetStringVal(MVT::ValueType VT,
1881 SelectionDAG &DAG, TargetLowering &TLI,
1882 std::string &Str, unsigned Offset) {
1883 MVT::ValueType CurVT = VT;
1884 uint64_t Val = 0;
1885 unsigned MSB = getSizeInBits(VT) / 8;
1886 if (TLI.isLittleEndian())
1887 Offset = Offset + MSB - 1;
1888 for (unsigned i = 0; i != MSB; ++i) {
1889 Val = (Val << 8) | Str[Offset];
1890 Offset += TLI.isLittleEndian() ? -1 : 1;
1891 }
1892 return DAG.getConstant(Val, VT);
1893}
1894
Evan Cheng81fcea82006-02-14 08:22:34 +00001895/// getMemBasePlusOffset - Returns base and offset node for the
1896static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1897 SelectionDAG &DAG, TargetLowering &TLI) {
1898 MVT::ValueType VT = Base.getValueType();
1899 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1900}
1901
Evan Chengdb2a7a72006-02-14 20:12:38 +00001902/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001903/// to replace the memset / memcpy is below the threshold. It also returns the
1904/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001905static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1906 unsigned Limit, uint64_t Size,
1907 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001908 MVT::ValueType VT;
1909
1910 if (TLI.allowsUnalignedMemoryAccesses()) {
1911 VT = MVT::i64;
1912 } else {
1913 switch (Align & 7) {
1914 case 0:
1915 VT = MVT::i64;
1916 break;
1917 case 4:
1918 VT = MVT::i32;
1919 break;
1920 case 2:
1921 VT = MVT::i16;
1922 break;
1923 default:
1924 VT = MVT::i8;
1925 break;
1926 }
1927 }
1928
Evan Chengd5026102006-02-14 09:11:59 +00001929 MVT::ValueType LVT = MVT::i64;
1930 while (!TLI.isTypeLegal(LVT))
1931 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1932 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001933
Evan Chengd5026102006-02-14 09:11:59 +00001934 if (VT > LVT)
1935 VT = LVT;
1936
Evan Cheng04514992006-02-14 23:05:54 +00001937 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001938 while (Size != 0) {
1939 unsigned VTSize = getSizeInBits(VT) / 8;
1940 while (VTSize > Size) {
1941 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001942 VTSize >>= 1;
1943 }
Evan Chengd5026102006-02-14 09:11:59 +00001944 assert(MVT::isInteger(VT));
1945
1946 if (++NumMemOps > Limit)
1947 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001948 MemOps.push_back(VT);
1949 Size -= VTSize;
1950 }
Evan Chengd5026102006-02-14 09:11:59 +00001951
1952 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001953}
1954
Chris Lattner875def92005-01-11 05:56:49 +00001955void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001956 SDOperand Op1 = getValue(I.getOperand(1));
1957 SDOperand Op2 = getValue(I.getOperand(2));
1958 SDOperand Op3 = getValue(I.getOperand(3));
1959 SDOperand Op4 = getValue(I.getOperand(4));
1960 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1961 if (Align == 0) Align = 1;
1962
1963 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1964 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001965
1966 // Expand memset / memcpy to a series of load / store ops
1967 // if the size operand falls below a certain threshold.
1968 std::vector<SDOperand> OutChains;
1969 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001970 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001971 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001972 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1973 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001974 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001975 unsigned Offset = 0;
1976 for (unsigned i = 0; i < NumMemOps; i++) {
1977 MVT::ValueType VT = MemOps[i];
1978 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001979 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001980 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1981 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001982 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1983 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001984 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001985 Offset += VTSize;
1986 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001987 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001988 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001989 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001990 case ISD::MEMCPY: {
1991 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1992 Size->getValue(), Align, TLI)) {
1993 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001994 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001995 GlobalAddressSDNode *G = NULL;
1996 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001997 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001998
1999 if (Op2.getOpcode() == ISD::GlobalAddress)
2000 G = cast<GlobalAddressSDNode>(Op2);
2001 else if (Op2.getOpcode() == ISD::ADD &&
2002 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2003 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2004 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002005 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002006 }
2007 if (G) {
2008 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002009 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002010 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002011 if (!Str.empty()) {
2012 CopyFromStr = true;
2013 SrcOff += SrcDelta;
2014 }
2015 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002016 }
2017
Evan Chenge2038bd2006-02-15 01:54:51 +00002018 for (unsigned i = 0; i < NumMemOps; i++) {
2019 MVT::ValueType VT = MemOps[i];
2020 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002021 SDOperand Value, Chain, Store;
2022
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002023 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002024 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2025 Chain = getRoot();
2026 Store =
2027 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2028 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2029 DAG.getSrcValue(I.getOperand(1), DstOff));
2030 } else {
2031 Value = DAG.getLoad(VT, getRoot(),
2032 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2033 DAG.getSrcValue(I.getOperand(2), SrcOff));
2034 Chain = Value.getValue(1);
2035 Store =
2036 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2037 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2038 DAG.getSrcValue(I.getOperand(1), DstOff));
2039 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002040 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002041 SrcOff += VTSize;
2042 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002043 }
2044 }
2045 break;
2046 }
2047 }
2048
2049 if (!OutChains.empty()) {
2050 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2051 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002052 }
2053 }
2054
Chris Lattner875def92005-01-11 05:56:49 +00002055 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002056 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002057 Ops.push_back(Op1);
2058 Ops.push_back(Op2);
2059 Ops.push_back(Op3);
2060 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002061 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002062}
2063
Chris Lattner875def92005-01-11 05:56:49 +00002064//===----------------------------------------------------------------------===//
2065// SelectionDAGISel code
2066//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002067
2068unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2069 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2070}
2071
Chris Lattnerc9950c12005-08-17 06:37:43 +00002072void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002073 // FIXME: we only modify the CFG to split critical edges. This
2074 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002075}
Chris Lattner7a60d912005-01-07 07:47:53 +00002076
Chris Lattner35397782005-12-05 07:10:48 +00002077
2078/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2079/// casting to the type of GEPI.
2080static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2081 Value *Ptr, Value *PtrOffset) {
2082 if (V) return V; // Already computed.
2083
2084 BasicBlock::iterator InsertPt;
2085 if (BB == GEPI->getParent()) {
2086 // If insert into the GEP's block, insert right after the GEP.
2087 InsertPt = GEPI;
2088 ++InsertPt;
2089 } else {
2090 // Otherwise, insert at the top of BB, after any PHI nodes
2091 InsertPt = BB->begin();
2092 while (isa<PHINode>(InsertPt)) ++InsertPt;
2093 }
2094
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002095 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2096 // BB so that there is only one value live across basic blocks (the cast
2097 // operand).
2098 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2099 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2100 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2101
Chris Lattner35397782005-12-05 07:10:48 +00002102 // Add the offset, cast it to the right type.
2103 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2104 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2105 return V = Ptr;
2106}
2107
2108
2109/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2110/// selection, we want to be a bit careful about some things. In particular, if
2111/// we have a GEP instruction that is used in a different block than it is
2112/// defined, the addressing expression of the GEP cannot be folded into loads or
2113/// stores that use it. In this case, decompose the GEP and move constant
2114/// indices into blocks that use it.
2115static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2116 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002117 // If this GEP is only used inside the block it is defined in, there is no
2118 // need to rewrite it.
2119 bool isUsedOutsideDefBB = false;
2120 BasicBlock *DefBB = GEPI->getParent();
2121 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2122 UI != E; ++UI) {
2123 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2124 isUsedOutsideDefBB = true;
2125 break;
2126 }
2127 }
2128 if (!isUsedOutsideDefBB) return;
2129
2130 // If this GEP has no non-zero constant indices, there is nothing we can do,
2131 // ignore it.
2132 bool hasConstantIndex = false;
2133 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2134 E = GEPI->op_end(); OI != E; ++OI) {
2135 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2136 if (CI->getRawValue()) {
2137 hasConstantIndex = true;
2138 break;
2139 }
2140 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002141 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2142 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002143
2144 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2145 // constant offset (which we now know is non-zero) and deal with it later.
2146 uint64_t ConstantOffset = 0;
2147 const Type *UIntPtrTy = TD.getIntPtrType();
2148 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2149 const Type *Ty = GEPI->getOperand(0)->getType();
2150
2151 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2152 E = GEPI->op_end(); OI != E; ++OI) {
2153 Value *Idx = *OI;
2154 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2155 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2156 if (Field)
2157 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2158 Ty = StTy->getElementType(Field);
2159 } else {
2160 Ty = cast<SequentialType>(Ty)->getElementType();
2161
2162 // Handle constant subscripts.
2163 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2164 if (CI->getRawValue() == 0) continue;
2165
2166 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2167 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2168 else
2169 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2170 continue;
2171 }
2172
2173 // Ptr = Ptr + Idx * ElementSize;
2174
2175 // Cast Idx to UIntPtrTy if needed.
2176 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2177
2178 uint64_t ElementSize = TD.getTypeSize(Ty);
2179 // Mask off bits that should not be set.
2180 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2181 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2182
2183 // Multiply by the element size and add to the base.
2184 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2185 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2186 }
2187 }
2188
2189 // Make sure that the offset fits in uintptr_t.
2190 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2191 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2192
2193 // Okay, we have now emitted all of the variable index parts to the BB that
2194 // the GEP is defined in. Loop over all of the using instructions, inserting
2195 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002196 // instruction to use the newly computed value, making GEPI dead. When the
2197 // user is a load or store instruction address, we emit the add into the user
2198 // block, otherwise we use a canonical version right next to the gep (these
2199 // won't be foldable as addresses, so we might as well share the computation).
2200
Chris Lattner35397782005-12-05 07:10:48 +00002201 std::map<BasicBlock*,Value*> InsertedExprs;
2202 while (!GEPI->use_empty()) {
2203 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002204
2205 // If this use is not foldable into the addressing mode, use a version
2206 // emitted in the GEP block.
2207 Value *NewVal;
2208 if (!isa<LoadInst>(User) &&
2209 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2210 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2211 Ptr, PtrOffset);
2212 } else {
2213 // Otherwise, insert the code in the User's block so it can be folded into
2214 // any users in that block.
2215 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002216 User->getParent(), GEPI,
2217 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002218 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002219 User->replaceUsesOfWith(GEPI, NewVal);
2220 }
Chris Lattner35397782005-12-05 07:10:48 +00002221
2222 // Finally, the GEP is dead, remove it.
2223 GEPI->eraseFromParent();
2224}
2225
Chris Lattner7a60d912005-01-07 07:47:53 +00002226bool SelectionDAGISel::runOnFunction(Function &Fn) {
2227 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2228 RegMap = MF.getSSARegMap();
2229 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2230
Chris Lattner35397782005-12-05 07:10:48 +00002231 // First, split all critical edges for PHI nodes with incoming values that are
2232 // constants, this way the load of the constant into a vreg will not be placed
2233 // into MBBs that are used some other way.
2234 //
2235 // In this pass we also look for GEP instructions that are used across basic
2236 // blocks and rewrites them to improve basic-block-at-a-time selection.
2237 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002238 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2239 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002240 BasicBlock::iterator BBI;
2241 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002242 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2243 if (isa<Constant>(PN->getIncomingValue(i)))
2244 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002245
2246 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2247 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2248 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002249 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002250
Chris Lattner7a60d912005-01-07 07:47:53 +00002251 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2252
2253 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2254 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002255
Chris Lattner7a60d912005-01-07 07:47:53 +00002256 return true;
2257}
2258
2259
Chris Lattner718b5c22005-01-13 17:59:43 +00002260SDOperand SelectionDAGISel::
2261CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002262 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002263 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002264 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002265 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002266
2267 // If this type is not legal, we must make sure to not create an invalid
2268 // register use.
2269 MVT::ValueType SrcVT = Op.getValueType();
2270 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2271 SelectionDAG &DAG = SDL.DAG;
2272 if (SrcVT == DestVT) {
2273 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00002274 } else if (SrcVT == MVT::Vector) {
2275 // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2276
2277 // Figure out the right, legal destination reg to copy into.
2278 const PackedType *PTy = cast<PackedType>(V->getType());
2279 unsigned NumElts = PTy->getNumElements();
2280 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2281
2282 unsigned NumVectorRegs = 1;
2283
2284 // Divide the input until we get to a supported size. This will always
2285 // end with a scalar if the target doesn't support vectors.
2286 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2287 NumElts >>= 1;
2288 NumVectorRegs <<= 1;
2289 }
2290
2291 MVT::ValueType VT;
2292 if (NumElts == 1)
2293 VT = EltTy;
2294 else
2295 VT = getVectorType(EltTy, NumElts);
2296
2297 // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2298 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2299 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002300 } else if (SrcVT < DestVT) {
2301 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002302 if (MVT::isFloatingPoint(SrcVT))
2303 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2304 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002305 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002306 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2307 } else {
2308 // The src value is expanded into multiple registers.
2309 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2310 Op, DAG.getConstant(0, MVT::i32));
2311 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2312 Op, DAG.getConstant(1, MVT::i32));
2313 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2314 return DAG.getCopyToReg(Op, Reg+1, Hi);
2315 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002316}
2317
Chris Lattner16f64df2005-01-17 17:15:02 +00002318void SelectionDAGISel::
2319LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2320 std::vector<SDOperand> &UnorderedChains) {
2321 // If this is the entry block, emit arguments.
2322 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002323 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002324 SDOperand OldRoot = SDL.DAG.getRoot();
2325 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002326
Chris Lattner6871b232005-10-30 19:42:35 +00002327 unsigned a = 0;
2328 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2329 AI != E; ++AI, ++a)
2330 if (!AI->use_empty()) {
2331 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002332
Chris Lattner6871b232005-10-30 19:42:35 +00002333 // If this argument is live outside of the entry block, insert a copy from
2334 // whereever we got it to the vreg that other BB's will reference it as.
2335 if (FuncInfo.ValueMap.count(AI)) {
2336 SDOperand Copy =
2337 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2338 UnorderedChains.push_back(Copy);
2339 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002340 }
Chris Lattner6871b232005-10-30 19:42:35 +00002341
2342 // Next, if the function has live ins that need to be copied into vregs,
2343 // emit the copies now, into the top of the block.
2344 MachineFunction &MF = SDL.DAG.getMachineFunction();
2345 if (MF.livein_begin() != MF.livein_end()) {
2346 SSARegMap *RegMap = MF.getSSARegMap();
2347 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2348 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2349 E = MF.livein_end(); LI != E; ++LI)
2350 if (LI->second)
2351 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2352 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002353 }
Chris Lattner6871b232005-10-30 19:42:35 +00002354
2355 // Finally, if the target has anything special to do, allow it to do so.
2356 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002357}
2358
2359
Chris Lattner7a60d912005-01-07 07:47:53 +00002360void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2361 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2362 FunctionLoweringInfo &FuncInfo) {
2363 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002364
2365 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002366
Chris Lattner6871b232005-10-30 19:42:35 +00002367 // Lower any arguments needed in this block if this is the entry block.
2368 if (LLVMBB == &LLVMBB->getParent()->front())
2369 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002370
2371 BB = FuncInfo.MBBMap[LLVMBB];
2372 SDL.setCurrentBasicBlock(BB);
2373
2374 // Lower all of the non-terminator instructions.
2375 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2376 I != E; ++I)
2377 SDL.visit(*I);
2378
2379 // Ensure that all instructions which are used outside of their defining
2380 // blocks are available as virtual registers.
2381 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002382 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002383 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002384 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002385 UnorderedChains.push_back(
2386 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002387 }
2388
2389 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2390 // ensure constants are generated when needed. Remember the virtual registers
2391 // that need to be added to the Machine PHI nodes as input. We cannot just
2392 // directly add them, because expansion might result in multiple MBB's for one
2393 // BB. As such, the start of the BB might correspond to a different MBB than
2394 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002395 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002396
2397 // Emit constants only once even if used by multiple PHI nodes.
2398 std::map<Constant*, unsigned> ConstantsOut;
2399
2400 // Check successor nodes PHI nodes that expect a constant to be available from
2401 // this block.
2402 TerminatorInst *TI = LLVMBB->getTerminator();
2403 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2404 BasicBlock *SuccBB = TI->getSuccessor(succ);
2405 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2406 PHINode *PN;
2407
2408 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2409 // nodes and Machine PHI nodes, but the incoming operands have not been
2410 // emitted yet.
2411 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002412 (PN = dyn_cast<PHINode>(I)); ++I)
2413 if (!PN->use_empty()) {
2414 unsigned Reg;
2415 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2416 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2417 unsigned &RegOut = ConstantsOut[C];
2418 if (RegOut == 0) {
2419 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002420 UnorderedChains.push_back(
2421 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002422 }
2423 Reg = RegOut;
2424 } else {
2425 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002426 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002427 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002428 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2429 "Didn't codegen value into a register!??");
2430 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002431 UnorderedChains.push_back(
2432 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002433 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002434 }
Misha Brukman835702a2005-04-21 22:36:52 +00002435
Chris Lattner8ea875f2005-01-07 21:34:19 +00002436 // Remember that this register needs to added to the machine PHI node as
2437 // the input for this MBB.
2438 unsigned NumElements =
2439 TLI.getNumElements(TLI.getValueType(PN->getType()));
2440 for (unsigned i = 0, e = NumElements; i != e; ++i)
2441 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002442 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002443 }
2444 ConstantsOut.clear();
2445
Chris Lattner718b5c22005-01-13 17:59:43 +00002446 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002447 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002448 SDOperand Root = SDL.getRoot();
2449 if (Root.getOpcode() != ISD::EntryToken) {
2450 unsigned i = 0, e = UnorderedChains.size();
2451 for (; i != e; ++i) {
2452 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2453 if (UnorderedChains[i].Val->getOperand(0) == Root)
2454 break; // Don't add the root if we already indirectly depend on it.
2455 }
2456
2457 if (i == e)
2458 UnorderedChains.push_back(Root);
2459 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002460 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2461 }
2462
Chris Lattner7a60d912005-01-07 07:47:53 +00002463 // Lower the terminator after the copies are emitted.
2464 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002465
2466 // Make sure the root of the DAG is up-to-date.
2467 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002468}
2469
2470void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2471 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002472 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002473 CurDAG = &DAG;
2474 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2475
2476 // First step, lower LLVM code to some DAG. This DAG may use operations and
2477 // types that are not supported by the target.
2478 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2479
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002480 // Run the DAG combiner in pre-legalize mode.
2481 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002482
Chris Lattner7a60d912005-01-07 07:47:53 +00002483 DEBUG(std::cerr << "Lowered selection DAG:\n");
2484 DEBUG(DAG.dump());
2485
2486 // Second step, hack on the DAG until it only uses operations and types that
2487 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002488 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002489
2490 DEBUG(std::cerr << "Legalized selection DAG:\n");
2491 DEBUG(DAG.dump());
2492
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002493 // Run the DAG combiner in post-legalize mode.
2494 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002495
Evan Cheng739a6a42006-01-21 02:32:06 +00002496 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002497
Chris Lattner5ca31d92005-03-30 01:10:47 +00002498 // Third, instruction select all of the operations to machine code, adding the
2499 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002500 InstructionSelectBasicBlock(DAG);
2501
Chris Lattner7a60d912005-01-07 07:47:53 +00002502 DEBUG(std::cerr << "Selected machine code:\n");
2503 DEBUG(BB->dump());
2504
Chris Lattner5ca31d92005-03-30 01:10:47 +00002505 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002506 // PHI nodes in successors.
2507 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2508 MachineInstr *PHI = PHINodesToUpdate[i].first;
2509 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2510 "This is not a machine PHI node that we are updating!");
2511 PHI->addRegOperand(PHINodesToUpdate[i].second);
2512 PHI->addMachineBasicBlockOperand(BB);
2513 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002514
2515 // Finally, add the CFG edges from the last selected MBB to the successor
2516 // MBBs.
2517 TerminatorInst *TI = LLVMBB->getTerminator();
2518 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2519 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2520 BB->addSuccessor(Succ0MBB);
2521 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002522}
Evan Cheng739a6a42006-01-21 02:32:06 +00002523
2524//===----------------------------------------------------------------------===//
2525/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2526/// target node in the graph.
2527void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2528 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002529 ScheduleDAG *SL = NULL;
2530
2531 switch (ISHeuristic) {
2532 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002533 case defaultScheduling:
2534 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2535 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2536 else /* TargetLowering::SchedulingForRegPressure */
2537 SL = createBURRListDAGScheduler(DAG, BB);
2538 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002539 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002540 SL = createBFS_DAGScheduler(DAG, BB);
2541 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002542 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002543 SL = createSimpleDAGScheduler(false, DAG, BB);
2544 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002545 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002546 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002547 break;
Evan Cheng31272342006-01-23 08:26:10 +00002548 case listSchedulingBURR:
2549 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002550 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002551 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002552 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002553 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002554 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002555 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002556 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002557}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002558
Chris Lattner543832d2006-03-08 04:25:59 +00002559HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2560 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002561}
2562
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002563/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2564/// by tblgen. Others should not call it.
2565void SelectionDAGISel::
2566SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2567 std::vector<SDOperand> InOps;
2568 std::swap(InOps, Ops);
2569
2570 Ops.push_back(InOps[0]); // input chain.
2571 Ops.push_back(InOps[1]); // input asm string.
2572
2573 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2574 unsigned i = 2, e = InOps.size();
2575 if (InOps[e-1].getValueType() == MVT::Flag)
2576 --e; // Don't process a flag operand if it is here.
2577
2578 while (i != e) {
2579 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2580 if ((Flags & 7) != 4 /*MEM*/) {
2581 // Just skip over this operand, copying the operands verbatim.
2582 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2583 i += (Flags >> 3) + 1;
2584 } else {
2585 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2586 // Otherwise, this is a memory operand. Ask the target to select it.
2587 std::vector<SDOperand> SelOps;
2588 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2589 std::cerr << "Could not match memory address. Inline asm failure!\n";
2590 exit(1);
2591 }
2592
2593 // Add this to the output node.
2594 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2595 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2596 i += 2;
2597 }
2598 }
2599
2600 // Add the flag input back if present.
2601 if (e != InOps.size())
2602 Ops.push_back(InOps.back());
2603}