blob: ebc77f6f1b6d4b3f96e3669867e73849d188951b [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 }
296 VT = getVectorType(EltTy, NumElts);
297 }
298
299 // The common case is that we will only create one register for this
300 // value. If we have that case, create and return the virtual register.
301 unsigned NV = TLI.getNumElements(VT);
302 if (NV == 1) {
303 // If we are promoting this value, pick the next largest supported type.
304 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
305 unsigned Reg = MakeReg(PromotedType);
306 // If this is a vector of supported or promoted types (e.g. 4 x i16),
307 // create all of the registers.
308 for (unsigned i = 1; i != NumVectorRegs; ++i)
309 MakeReg(PromotedType);
310 return Reg;
311 }
312
313 // If this value is represented with multiple target registers, make sure
314 // to create enough consecutive registers of the right (smaller) type.
315 unsigned NT = VT-1; // Find the type to use.
316 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
317 --NT;
318
319 unsigned R = MakeReg((MVT::ValueType)NT);
320 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
321 MakeReg((MVT::ValueType)NT);
322 return R;
323}
Chris Lattner7a60d912005-01-07 07:47:53 +0000324
325//===----------------------------------------------------------------------===//
326/// SelectionDAGLowering - This is the common target-independent lowering
327/// implementation that is parameterized by a TargetLowering object.
328/// Also, targets can overload any lowering method.
329///
330namespace llvm {
331class SelectionDAGLowering {
332 MachineBasicBlock *CurMBB;
333
334 std::map<const Value*, SDOperand> NodeMap;
335
Chris Lattner4d9651c2005-01-17 22:19:26 +0000336 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
337 /// them up and then emit token factor nodes when possible. This allows us to
338 /// get simple disambiguation between loads without worrying about alias
339 /// analysis.
340 std::vector<SDOperand> PendingLoads;
341
Chris Lattner7a60d912005-01-07 07:47:53 +0000342public:
343 // TLI - This is information that describes the available target features we
344 // need for lowering. This indicates when operations are unavailable,
345 // implemented with a libcall, etc.
346 TargetLowering &TLI;
347 SelectionDAG &DAG;
348 const TargetData &TD;
349
350 /// FuncInfo - Information about the function as a whole.
351 ///
352 FunctionLoweringInfo &FuncInfo;
353
354 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000355 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000356 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
357 FuncInfo(funcinfo) {
358 }
359
Chris Lattner4108bb02005-01-17 19:43:36 +0000360 /// getRoot - Return the current virtual root of the Selection DAG.
361 ///
362 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000363 if (PendingLoads.empty())
364 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000365
Chris Lattner4d9651c2005-01-17 22:19:26 +0000366 if (PendingLoads.size() == 1) {
367 SDOperand Root = PendingLoads[0];
368 DAG.setRoot(Root);
369 PendingLoads.clear();
370 return Root;
371 }
372
373 // Otherwise, we have to make a token factor node.
374 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
375 PendingLoads.clear();
376 DAG.setRoot(Root);
377 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000378 }
379
Chris Lattner7a60d912005-01-07 07:47:53 +0000380 void visit(Instruction &I) { visit(I.getOpcode(), I); }
381
382 void visit(unsigned Opcode, User &I) {
383 switch (Opcode) {
384 default: assert(0 && "Unknown instruction type encountered!");
385 abort();
386 // Build the switch statement using the Instruction.def file.
387#define HANDLE_INST(NUM, OPCODE, CLASS) \
388 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
389#include "llvm/Instruction.def"
390 }
391 }
392
393 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
394
Chris Lattner4024c002006-03-15 22:19:46 +0000395 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
396 SDOperand SrcValue, SDOperand Root,
397 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000398
399 SDOperand getIntPtrConstant(uint64_t Val) {
400 return DAG.getConstant(Val, TLI.getPointerTy());
401 }
402
403 SDOperand getValue(const Value *V) {
404 SDOperand &N = NodeMap[V];
405 if (N.Val) return N;
406
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000407 const Type *VTy = V->getType();
408 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000409 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
411 visit(CE->getOpcode(), *CE);
412 assert(N.Val && "visit didn't populate the ValueMap!");
413 return N;
414 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
415 return N = DAG.getGlobalAddress(GV, VT);
416 } else if (isa<ConstantPointerNull>(C)) {
417 return N = DAG.getConstant(0, TLI.getPointerTy());
418 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000419 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
421 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000422 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
423 unsigned NumElements = PTy->getNumElements();
424 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
425 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
426
427 // Now that we know the number and type of the elements, push a
428 // Constant or ConstantFP node onto the ops list for each element of
429 // the packed constant.
430 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000431 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
432 if (MVT::isFloatingPoint(PVT)) {
433 for (unsigned i = 0; i != NumElements; ++i) {
434 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
435 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
436 }
437 } else {
438 for (unsigned i = 0; i != NumElements; ++i) {
439 const ConstantIntegral *El =
440 cast<ConstantIntegral>(CP->getOperand(i));
441 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
442 }
443 }
444 } else {
445 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
446 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000447 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000448 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000449 else
Chris Lattner803a5752005-12-21 02:43:26 +0000450 Op = DAG.getConstant(0, PVT);
451 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000452 }
Chris Lattner803a5752005-12-21 02:43:26 +0000453
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000454 // Handle the case where we have a 1-element vector, in which
455 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000456 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000457 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000458 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
459 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
460 } else {
461 // If the packed type isn't legal, then create a ConstantVec node with
462 // generic Vector type instead.
Evan Chengb97aab42006-03-01 01:09:54 +0000463 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
464 SDOperand Typ = DAG.getValueType(PVT);
465 Ops.insert(Ops.begin(), Typ);
466 Ops.insert(Ops.begin(), Num);
467 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemanae89d862005-12-07 19:48:11 +0000468 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 } else {
470 // Canonicalize all constant ints to be unsigned.
471 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
472 }
473
474 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
475 std::map<const AllocaInst*, int>::iterator SI =
476 FuncInfo.StaticAllocaMap.find(AI);
477 if (SI != FuncInfo.StaticAllocaMap.end())
478 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
479 }
480
481 std::map<const Value*, unsigned>::const_iterator VMI =
482 FuncInfo.ValueMap.find(V);
483 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000484
Chris Lattner33182322005-08-16 21:55:35 +0000485 unsigned InReg = VMI->second;
486
487 // If this type is not legal, make it so now.
488 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
489
490 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
491 if (DestVT < VT) {
492 // Source must be expanded. This input value is actually coming from the
493 // register pair VMI->second and VMI->second+1.
494 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
495 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
496 } else {
497 if (DestVT > VT) { // Promotion case
498 if (MVT::isFloatingPoint(VT))
499 N = DAG.getNode(ISD::FP_ROUND, VT, N);
500 else
501 N = DAG.getNode(ISD::TRUNCATE, VT, N);
502 }
503 }
504
505 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000506 }
507
508 const SDOperand &setValue(const Value *V, SDOperand NewN) {
509 SDOperand &N = NodeMap[V];
510 assert(N.Val == 0 && "Already set a value for this node!");
511 return N = NewN;
512 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000513
Chris Lattner6f87d182006-02-22 22:37:12 +0000514 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
515 MVT::ValueType VT,
516 bool OutReg, bool InReg,
517 std::set<unsigned> &OutputRegs,
518 std::set<unsigned> &InputRegs);
519
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 // Terminator instructions.
521 void visitRet(ReturnInst &I);
522 void visitBr(BranchInst &I);
523 void visitUnreachable(UnreachableInst &I) { /* noop */ }
524
525 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000526 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000527 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000528 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
529 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
530 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
531
532 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000533 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000534 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000535 void visitAdd(User &I) {
536 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000537 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000538 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000539 void visitMul(User &I) {
540 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000541 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000542 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000543 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000544 visitBinary(I,
545 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
546 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000547 }
548 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000549 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000550 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000551 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000552 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
553 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
554 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000555 void visitShl(User &I) { visitShift(I, ISD::SHL); }
556 void visitShr(User &I) {
557 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000558 }
559
560 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
561 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
562 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
563 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
564 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
565 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
566 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
567
568 void visitGetElementPtr(User &I);
569 void visitCast(User &I);
570 void visitSelect(User &I);
571 //
572
573 void visitMalloc(MallocInst &I);
574 void visitFree(FreeInst &I);
575 void visitAlloca(AllocaInst &I);
576 void visitLoad(LoadInst &I);
577 void visitStore(StoreInst &I);
578 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
579 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000580 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000581 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000582
Chris Lattner7a60d912005-01-07 07:47:53 +0000583 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000584 void visitVAArg(VAArgInst &I);
585 void visitVAEnd(CallInst &I);
586 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000587 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000588
Chris Lattner875def92005-01-11 05:56:49 +0000589 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000590
591 void visitUserOp1(Instruction &I) {
592 assert(0 && "UserOp1 should not exist at instruction selection time!");
593 abort();
594 }
595 void visitUserOp2(Instruction &I) {
596 assert(0 && "UserOp2 should not exist at instruction selection time!");
597 abort();
598 }
599};
600} // end namespace llvm
601
602void SelectionDAGLowering::visitRet(ReturnInst &I) {
603 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000604 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000605 return;
606 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000607 std::vector<SDOperand> NewValues;
608 NewValues.push_back(getRoot());
609 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
610 SDOperand RetOp = getValue(I.getOperand(i));
611
612 // If this is an integer return value, we need to promote it ourselves to
613 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
614 // than sign/zero.
615 if (MVT::isInteger(RetOp.getValueType()) &&
616 RetOp.getValueType() < MVT::i64) {
617 MVT::ValueType TmpVT;
618 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
619 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
620 else
621 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000622
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000623 if (I.getOperand(i)->getType()->isSigned())
624 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
625 else
626 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
627 }
628 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000629 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000630 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000631}
632
633void SelectionDAGLowering::visitBr(BranchInst &I) {
634 // Update machine-CFG edges.
635 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000636
637 // Figure out which block is immediately after the current one.
638 MachineBasicBlock *NextBlock = 0;
639 MachineFunction::iterator BBI = CurMBB;
640 if (++BBI != CurMBB->getParent()->end())
641 NextBlock = BBI;
642
643 if (I.isUnconditional()) {
644 // If this is not a fall-through branch, emit the branch.
645 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000646 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000647 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000648 } else {
649 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000650
651 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000652 if (Succ1MBB == NextBlock) {
653 // If the condition is false, fall through. This means we should branch
654 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000655 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000656 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000657 } else if (Succ0MBB == NextBlock) {
658 // If the condition is true, fall through. This means we should branch if
659 // the condition is false to Succ #1. Invert the condition first.
660 SDOperand True = DAG.getConstant(1, Cond.getValueType());
661 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000662 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000663 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000664 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000665 std::vector<SDOperand> Ops;
666 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000667 // If the false case is the current basic block, then this is a self
668 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
669 // adds an extra instruction in the loop. Instead, invert the
670 // condition and emit "Loop: ... br!cond Loop; br Out.
671 if (CurMBB == Succ1MBB) {
672 std::swap(Succ0MBB, Succ1MBB);
673 SDOperand True = DAG.getConstant(1, Cond.getValueType());
674 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
675 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000676 Ops.push_back(Cond);
677 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
678 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
679 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000680 }
681 }
682}
683
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000684void SelectionDAGLowering::visitSub(User &I) {
685 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000686 if (I.getType()->isFloatingPoint()) {
687 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
688 if (CFP->isExactlyValue(-0.0)) {
689 SDOperand Op2 = getValue(I.getOperand(1));
690 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
691 return;
692 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000693 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000694 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000695}
696
Nate Begemanb2e089c2005-11-19 00:36:38 +0000697void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
698 unsigned VecOp) {
699 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000700 SDOperand Op1 = getValue(I.getOperand(0));
701 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000702
Chris Lattner19baba62005-11-19 18:40:42 +0000703 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000704 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
705 } else if (Ty->isFloatingPoint()) {
706 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
707 } else {
708 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000709 unsigned NumElements = PTy->getNumElements();
710 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000711 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000712
713 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000714 // the Legalize pass does not have to deal with them. Similarly, if the
715 // abstract vector is going to turn into one that the target natively
716 // supports, generate that type now so that Legalize doesn't have to deal
717 // with that either. These steps ensure that Legalize only has to handle
718 // vector types in its Expand case.
719 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000720 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000721 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Chengb97aab42006-03-01 01:09:54 +0000722 } else if (TVT != MVT::Other &&
723 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000724 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000725 } else {
726 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
727 SDOperand Typ = DAG.getValueType(PVT);
Evan Chengb97aab42006-03-01 01:09:54 +0000728 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000729 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000730 }
Nate Begeman127321b2005-11-18 07:42:56 +0000731}
Chris Lattner96c26752005-01-19 22:31:21 +0000732
Nate Begeman127321b2005-11-18 07:42:56 +0000733void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
734 SDOperand Op1 = getValue(I.getOperand(0));
735 SDOperand Op2 = getValue(I.getOperand(1));
736
737 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
738
Chris Lattner7a60d912005-01-07 07:47:53 +0000739 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
740}
741
742void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
743 ISD::CondCode UnsignedOpcode) {
744 SDOperand Op1 = getValue(I.getOperand(0));
745 SDOperand Op2 = getValue(I.getOperand(1));
746 ISD::CondCode Opcode = SignedOpcode;
747 if (I.getOperand(0)->getType()->isUnsigned())
748 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000749 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000750}
751
752void SelectionDAGLowering::visitSelect(User &I) {
753 SDOperand Cond = getValue(I.getOperand(0));
754 SDOperand TrueVal = getValue(I.getOperand(1));
755 SDOperand FalseVal = getValue(I.getOperand(2));
756 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
757 TrueVal, FalseVal));
758}
759
760void SelectionDAGLowering::visitCast(User &I) {
761 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000762 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
763 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000764
Chris Lattner4024c002006-03-15 22:19:46 +0000765 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000766 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000767 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000768 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000769 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000770 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000771 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000772 } else if (isInteger(SrcVT)) {
773 if (isInteger(DestVT)) { // Int -> Int cast
774 if (DestVT < SrcVT) // Truncating cast?
775 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000776 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000777 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000778 else
Chris Lattner4024c002006-03-15 22:19:46 +0000779 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000780 } else { // Int -> FP cast
781 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000782 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000783 else
Chris Lattner4024c002006-03-15 22:19:46 +0000784 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000785 }
Chris Lattner4024c002006-03-15 22:19:46 +0000786 } else if (isFloatingPoint(SrcVT)) {
787 if (isFloatingPoint(DestVT)) { // FP -> FP cast
788 if (DestVT < SrcVT) // Rounding cast?
789 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000790 else
Chris Lattner4024c002006-03-15 22:19:46 +0000791 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000792 } else { // FP -> Int cast.
793 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000794 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000795 else
Chris Lattner4024c002006-03-15 22:19:46 +0000796 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
797 }
798 } else {
799 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
800 const PackedType *DstTy = cast<PackedType>(I.getType());
801
802 unsigned SrcNumElements = SrcTy->getNumElements();
803 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
804 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
805
806 unsigned DstNumElements = DstTy->getNumElements();
807 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
808 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
809
810 // If the input and output type are legal, convert this to a bit convert of
811 // the SrcTVT/DstTVT types.
812 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
813 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
814 assert(N.getValueType() == SrcTVT);
815 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
816 } else {
817 // Otherwise, convert this directly into a store/load.
818 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
819 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
820 // Create the stack frame object.
821 uint64_t ByteSize = TD.getTypeSize(SrcTy);
822 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
823 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
824 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
825 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
826
827 // Emit a store to the stack slot.
828 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
829 N, FIPtr, DAG.getSrcValue(NULL));
830 // Result is a load from the stack slot.
831 SDOperand Val =
832 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
833 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000834 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000835 }
836}
837
838void SelectionDAGLowering::visitGetElementPtr(User &I) {
839 SDOperand N = getValue(I.getOperand(0));
840 const Type *Ty = I.getOperand(0)->getType();
841 const Type *UIntPtrTy = TD.getIntPtrType();
842
843 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
844 OI != E; ++OI) {
845 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000846 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000847 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
848 if (Field) {
849 // N = N + Offset
850 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
851 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000852 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000853 }
854 Ty = StTy->getElementType(Field);
855 } else {
856 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000857
Chris Lattner43535a12005-11-09 04:45:33 +0000858 // If this is a constant subscript, handle it quickly.
859 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
860 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000861
Chris Lattner43535a12005-11-09 04:45:33 +0000862 uint64_t Offs;
863 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
864 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
865 else
866 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
867 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
868 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000869 }
Chris Lattner43535a12005-11-09 04:45:33 +0000870
871 // N = N + Idx * ElementSize;
872 uint64_t ElementSize = TD.getTypeSize(Ty);
873 SDOperand IdxN = getValue(Idx);
874
875 // If the index is smaller or larger than intptr_t, truncate or extend
876 // it.
877 if (IdxN.getValueType() < N.getValueType()) {
878 if (Idx->getType()->isSigned())
879 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
880 else
881 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
882 } else if (IdxN.getValueType() > N.getValueType())
883 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
884
885 // If this is a multiply by a power of two, turn it into a shl
886 // immediately. This is a very common case.
887 if (isPowerOf2_64(ElementSize)) {
888 unsigned Amt = Log2_64(ElementSize);
889 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000890 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000891 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
892 continue;
893 }
894
895 SDOperand Scale = getIntPtrConstant(ElementSize);
896 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
897 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000898 }
899 }
900 setValue(&I, N);
901}
902
903void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
904 // If this is a fixed sized alloca in the entry block of the function,
905 // allocate it statically on the stack.
906 if (FuncInfo.StaticAllocaMap.count(&I))
907 return; // getValue will auto-populate this.
908
909 const Type *Ty = I.getAllocatedType();
910 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000911 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
912 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000913
914 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000915 MVT::ValueType IntPtr = TLI.getPointerTy();
916 if (IntPtr < AllocSize.getValueType())
917 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
918 else if (IntPtr > AllocSize.getValueType())
919 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000920
Chris Lattnereccb73d2005-01-22 23:04:37 +0000921 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000922 getIntPtrConstant(TySize));
923
924 // Handle alignment. If the requested alignment is less than or equal to the
925 // stack alignment, ignore it and round the size of the allocation up to the
926 // stack alignment size. If the size is greater than the stack alignment, we
927 // note this in the DYNAMIC_STACKALLOC node.
928 unsigned StackAlign =
929 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
930 if (Align <= StackAlign) {
931 Align = 0;
932 // Add SA-1 to the size.
933 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
934 getIntPtrConstant(StackAlign-1));
935 // Mask out the low bits for alignment purposes.
936 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
937 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
938 }
939
Chris Lattner96c262e2005-05-14 07:29:57 +0000940 std::vector<MVT::ValueType> VTs;
941 VTs.push_back(AllocSize.getValueType());
942 VTs.push_back(MVT::Other);
943 std::vector<SDOperand> Ops;
944 Ops.push_back(getRoot());
945 Ops.push_back(AllocSize);
946 Ops.push_back(getIntPtrConstant(Align));
947 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000948 DAG.setRoot(setValue(&I, DSA).getValue(1));
949
950 // Inform the Frame Information that we have just allocated a variable-sized
951 // object.
952 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
953}
954
Chris Lattner7a60d912005-01-07 07:47:53 +0000955void SelectionDAGLowering::visitLoad(LoadInst &I) {
956 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000957
Chris Lattner4d9651c2005-01-17 22:19:26 +0000958 SDOperand Root;
959 if (I.isVolatile())
960 Root = getRoot();
961 else {
962 // Do not serialize non-volatile loads against each other.
963 Root = DAG.getRoot();
964 }
Chris Lattner4024c002006-03-15 22:19:46 +0000965
966 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
967 Root, I.isVolatile()));
968}
969
970SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
971 SDOperand SrcValue, SDOperand Root,
972 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000973 SDOperand L;
974
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000975 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000976 unsigned NumElements = PTy->getNumElements();
977 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000978 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000979
980 // Immediately scalarize packed types containing only one element, so that
981 // the Legalize pass does not have to deal with them.
982 if (NumElements == 1) {
Chris Lattner4024c002006-03-15 22:19:46 +0000983 L = DAG.getLoad(PVT, Root, Ptr, SrcValue);
984 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
985 TLI.isOperationLegal(ISD::LOAD, TVT)) {
986 L = DAG.getLoad(TVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +0000987 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000988 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +0000989 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000990 } else {
Chris Lattner4024c002006-03-15 22:19:46 +0000991 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000992 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000993
Chris Lattner4024c002006-03-15 22:19:46 +0000994 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +0000995 DAG.setRoot(L.getValue(1));
996 else
997 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +0000998
999 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001000}
1001
1002
1003void SelectionDAGLowering::visitStore(StoreInst &I) {
1004 Value *SrcV = I.getOperand(0);
1005 SDOperand Src = getValue(SrcV);
1006 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001007 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001008 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001009}
1010
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001011/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1012/// we want to emit this as a call to a named external function, return the name
1013/// otherwise lower it and return null.
1014const char *
1015SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1016 switch (Intrinsic) {
1017 case Intrinsic::vastart: visitVAStart(I); return 0;
1018 case Intrinsic::vaend: visitVAEnd(I); return 0;
1019 case Intrinsic::vacopy: visitVACopy(I); return 0;
1020 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1021 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1022 case Intrinsic::setjmp:
1023 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1024 break;
1025 case Intrinsic::longjmp:
1026 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1027 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001028 case Intrinsic::memcpy_i32:
1029 case Intrinsic::memcpy_i64:
1030 visitMemIntrinsic(I, ISD::MEMCPY);
1031 return 0;
1032 case Intrinsic::memset_i32:
1033 case Intrinsic::memset_i64:
1034 visitMemIntrinsic(I, ISD::MEMSET);
1035 return 0;
1036 case Intrinsic::memmove_i32:
1037 case Intrinsic::memmove_i64:
1038 visitMemIntrinsic(I, ISD::MEMMOVE);
1039 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001040
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001041 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001042 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001043 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001044 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001045
Jim Laskey5995d012006-02-11 01:01:30 +00001046 // Input Chain
1047 Ops.push_back(getRoot());
1048
1049 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001050 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001051
1052 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001053 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001054
Jim Laskeyacb6e342006-03-13 13:07:37 +00001055 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001056 assert(DD && "Not a debug information descriptor");
1057 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1058 assert(CompileUnit && "Not a compile unit");
1059 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1060 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1061
1062 if (Ops.size() == 5) // Found filename/workingdir.
1063 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001064 }
1065
Chris Lattner8782b782005-12-03 18:50:48 +00001066 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001067 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001068 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001069 case Intrinsic::dbg_region_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 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001074 if (I.getType() != Type::VoidTy)
1075 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1076 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001077 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001078 if (I.getType() != Type::VoidTy)
1079 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1080 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001081
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001082 case Intrinsic::isunordered_f32:
1083 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001084 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1085 getValue(I.getOperand(2)), ISD::SETUO));
1086 return 0;
1087
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001088 case Intrinsic::sqrt_f32:
1089 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001090 setValue(&I, DAG.getNode(ISD::FSQRT,
1091 getValue(I.getOperand(1)).getValueType(),
1092 getValue(I.getOperand(1))));
1093 return 0;
1094 case Intrinsic::pcmarker: {
1095 SDOperand Tmp = getValue(I.getOperand(1));
1096 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1097 return 0;
1098 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001099 case Intrinsic::readcyclecounter: {
1100 std::vector<MVT::ValueType> VTs;
1101 VTs.push_back(MVT::i64);
1102 VTs.push_back(MVT::Other);
1103 std::vector<SDOperand> Ops;
1104 Ops.push_back(getRoot());
1105 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1106 setValue(&I, Tmp);
1107 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001108 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001109 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001110 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001111 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001112 case Intrinsic::bswap_i64:
1113 setValue(&I, DAG.getNode(ISD::BSWAP,
1114 getValue(I.getOperand(1)).getValueType(),
1115 getValue(I.getOperand(1))));
1116 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001117 case Intrinsic::cttz_i8:
1118 case Intrinsic::cttz_i16:
1119 case Intrinsic::cttz_i32:
1120 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001121 setValue(&I, DAG.getNode(ISD::CTTZ,
1122 getValue(I.getOperand(1)).getValueType(),
1123 getValue(I.getOperand(1))));
1124 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001125 case Intrinsic::ctlz_i8:
1126 case Intrinsic::ctlz_i16:
1127 case Intrinsic::ctlz_i32:
1128 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001129 setValue(&I, DAG.getNode(ISD::CTLZ,
1130 getValue(I.getOperand(1)).getValueType(),
1131 getValue(I.getOperand(1))));
1132 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001133 case Intrinsic::ctpop_i8:
1134 case Intrinsic::ctpop_i16:
1135 case Intrinsic::ctpop_i32:
1136 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001137 setValue(&I, DAG.getNode(ISD::CTPOP,
1138 getValue(I.getOperand(1)).getValueType(),
1139 getValue(I.getOperand(1))));
1140 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001141 case Intrinsic::stacksave: {
1142 std::vector<MVT::ValueType> VTs;
1143 VTs.push_back(TLI.getPointerTy());
1144 VTs.push_back(MVT::Other);
1145 std::vector<SDOperand> Ops;
1146 Ops.push_back(getRoot());
1147 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1148 setValue(&I, Tmp);
1149 DAG.setRoot(Tmp.getValue(1));
1150 return 0;
1151 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001152 case Intrinsic::stackrestore: {
1153 SDOperand Tmp = getValue(I.getOperand(1));
1154 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001155 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001156 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001157 case Intrinsic::prefetch:
1158 // FIXME: Currently discarding prefetches.
1159 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001160 default:
1161 std::cerr << I;
1162 assert(0 && "This intrinsic is not implemented yet!");
1163 return 0;
1164 }
1165}
1166
1167
Chris Lattner7a60d912005-01-07 07:47:53 +00001168void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001169 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001170 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001171 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001172 if (unsigned IID = F->getIntrinsicID()) {
1173 RenameFn = visitIntrinsicCall(I, IID);
1174 if (!RenameFn)
1175 return;
1176 } else { // Not an LLVM intrinsic.
1177 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001178 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1179 if (I.getNumOperands() == 3 && // Basic sanity checks.
1180 I.getOperand(1)->getType()->isFloatingPoint() &&
1181 I.getType() == I.getOperand(1)->getType() &&
1182 I.getType() == I.getOperand(2)->getType()) {
1183 SDOperand LHS = getValue(I.getOperand(1));
1184 SDOperand RHS = getValue(I.getOperand(2));
1185 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1186 LHS, RHS));
1187 return;
1188 }
1189 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001190 if (I.getNumOperands() == 2 && // Basic sanity checks.
1191 I.getOperand(1)->getType()->isFloatingPoint() &&
1192 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001193 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001194 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1195 return;
1196 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001197 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
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::FSIN, Tmp.getValueType(), Tmp));
1203 return;
1204 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001205 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001206 if (I.getNumOperands() == 2 && // Basic sanity checks.
1207 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001208 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001209 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001210 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1211 return;
1212 }
1213 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001214 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001215 } else if (isa<InlineAsm>(I.getOperand(0))) {
1216 visitInlineAsm(I);
1217 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001218 }
Misha Brukman835702a2005-04-21 22:36:52 +00001219
Chris Lattner18d2b342005-01-08 22:48:57 +00001220 SDOperand Callee;
1221 if (!RenameFn)
1222 Callee = getValue(I.getOperand(0));
1223 else
1224 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001225 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001226 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001227 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1228 Value *Arg = I.getOperand(i);
1229 SDOperand ArgNode = getValue(Arg);
1230 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1231 }
Misha Brukman835702a2005-04-21 22:36:52 +00001232
Nate Begemanf6565252005-03-26 01:29:23 +00001233 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1234 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001235
Chris Lattner1f45cd72005-01-08 19:26:18 +00001236 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001237 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001238 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001239 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001240 setValue(&I, Result.first);
1241 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001242}
1243
Chris Lattner6f87d182006-02-22 22:37:12 +00001244SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001245 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001246 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1247 Chain = Val.getValue(1);
1248 Flag = Val.getValue(2);
1249
1250 // If the result was expanded, copy from the top part.
1251 if (Regs.size() > 1) {
1252 assert(Regs.size() == 2 &&
1253 "Cannot expand to more than 2 elts yet!");
1254 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1255 Chain = Val.getValue(1);
1256 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001257 if (DAG.getTargetLoweringInfo().isLittleEndian())
1258 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1259 else
1260 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001261 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001262
Chris Lattner6f87d182006-02-22 22:37:12 +00001263 // Otherwise, if the return value was promoted, truncate it to the
1264 // appropriate type.
1265 if (RegVT == ValueVT)
1266 return Val;
1267
1268 if (MVT::isInteger(RegVT))
1269 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1270 else
1271 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1272}
1273
Chris Lattner571d9642006-02-23 19:21:04 +00001274/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1275/// specified value into the registers specified by this object. This uses
1276/// Chain/Flag as the input and updates them for the output Chain/Flag.
1277void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001278 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001279 if (Regs.size() == 1) {
1280 // If there is a single register and the types differ, this must be
1281 // a promotion.
1282 if (RegVT != ValueVT) {
1283 if (MVT::isInteger(RegVT))
1284 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1285 else
1286 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1287 }
1288 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1289 Flag = Chain.getValue(1);
1290 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001291 std::vector<unsigned> R(Regs);
1292 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1293 std::reverse(R.begin(), R.end());
1294
1295 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001296 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1297 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001298 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001299 Flag = Chain.getValue(1);
1300 }
1301 }
1302}
Chris Lattner6f87d182006-02-22 22:37:12 +00001303
Chris Lattner571d9642006-02-23 19:21:04 +00001304/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1305/// operand list. This adds the code marker and includes the number of
1306/// values added into it.
1307void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001308 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001309 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1310 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1311 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1312}
Chris Lattner6f87d182006-02-22 22:37:12 +00001313
1314/// isAllocatableRegister - If the specified register is safe to allocate,
1315/// i.e. it isn't a stack pointer or some other special register, return the
1316/// register class for the register. Otherwise, return null.
1317static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001318isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1319 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1320 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1321 E = MRI->regclass_end(); RCI != E; ++RCI) {
1322 const TargetRegisterClass *RC = *RCI;
1323 // If none of the the value types for this register class are valid, we
1324 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1325 bool isLegal = false;
1326 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1327 I != E; ++I) {
1328 if (TLI.isTypeLegal(*I)) {
1329 isLegal = true;
1330 break;
1331 }
1332 }
1333
1334 if (!isLegal) continue;
1335
Chris Lattner6f87d182006-02-22 22:37:12 +00001336 // NOTE: This isn't ideal. In particular, this might allocate the
1337 // frame pointer in functions that need it (due to them not being taken
1338 // out of allocation, because a variable sized allocation hasn't been seen
1339 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001340 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1341 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001342 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001343 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001344 }
1345 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001346}
1347
1348RegsForValue SelectionDAGLowering::
1349GetRegistersForValue(const std::string &ConstrCode,
1350 MVT::ValueType VT, bool isOutReg, bool isInReg,
1351 std::set<unsigned> &OutputRegs,
1352 std::set<unsigned> &InputRegs) {
1353 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1354 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1355 std::vector<unsigned> Regs;
1356
1357 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1358 MVT::ValueType RegVT;
1359 MVT::ValueType ValueVT = VT;
1360
1361 if (PhysReg.first) {
1362 if (VT == MVT::Other)
1363 ValueVT = *PhysReg.second->vt_begin();
1364 RegVT = VT;
1365
1366 // This is a explicit reference to a physical register.
1367 Regs.push_back(PhysReg.first);
1368
1369 // If this is an expanded reference, add the rest of the regs to Regs.
1370 if (NumRegs != 1) {
1371 RegVT = *PhysReg.second->vt_begin();
1372 TargetRegisterClass::iterator I = PhysReg.second->begin();
1373 TargetRegisterClass::iterator E = PhysReg.second->end();
1374 for (; *I != PhysReg.first; ++I)
1375 assert(I != E && "Didn't find reg!");
1376
1377 // Already added the first reg.
1378 --NumRegs; ++I;
1379 for (; NumRegs; --NumRegs, ++I) {
1380 assert(I != E && "Ran out of registers to allocate!");
1381 Regs.push_back(*I);
1382 }
1383 }
1384 return RegsForValue(Regs, RegVT, ValueVT);
1385 }
1386
1387 // This is a reference to a register class. Allocate NumRegs consecutive,
1388 // available, registers from the class.
1389 std::vector<unsigned> RegClassRegs =
1390 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1391
1392 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1393 MachineFunction &MF = *CurMBB->getParent();
1394 unsigned NumAllocated = 0;
1395 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1396 unsigned Reg = RegClassRegs[i];
1397 // See if this register is available.
1398 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1399 (isInReg && InputRegs.count(Reg))) { // Already used.
1400 // Make sure we find consecutive registers.
1401 NumAllocated = 0;
1402 continue;
1403 }
1404
1405 // Check to see if this register is allocatable (i.e. don't give out the
1406 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001407 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001408 if (!RC) {
1409 // Make sure we find consecutive registers.
1410 NumAllocated = 0;
1411 continue;
1412 }
1413
1414 // Okay, this register is good, we can use it.
1415 ++NumAllocated;
1416
1417 // If we allocated enough consecutive
1418 if (NumAllocated == NumRegs) {
1419 unsigned RegStart = (i-NumAllocated)+1;
1420 unsigned RegEnd = i+1;
1421 // Mark all of the allocated registers used.
1422 for (unsigned i = RegStart; i != RegEnd; ++i) {
1423 unsigned Reg = RegClassRegs[i];
1424 Regs.push_back(Reg);
1425 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1426 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1427 }
1428
1429 return RegsForValue(Regs, *RC->vt_begin(), VT);
1430 }
1431 }
1432
1433 // Otherwise, we couldn't allocate enough registers for this.
1434 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001435}
1436
Chris Lattner6f87d182006-02-22 22:37:12 +00001437
Chris Lattner476e67b2006-01-26 22:24:51 +00001438/// visitInlineAsm - Handle a call to an InlineAsm object.
1439///
1440void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1441 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1442
1443 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1444 MVT::Other);
1445
1446 // Note, we treat inline asms both with and without side-effects as the same.
1447 // If an inline asm doesn't have side effects and doesn't access memory, we
1448 // could not choose to not chain it.
1449 bool hasSideEffects = IA->hasSideEffects();
1450
Chris Lattner3a5ed552006-02-01 01:28:23 +00001451 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001452 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001453
1454 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1455 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1456 /// if it is a def of that register.
1457 std::vector<SDOperand> AsmNodeOperands;
1458 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1459 AsmNodeOperands.push_back(AsmStr);
1460
1461 SDOperand Chain = getRoot();
1462 SDOperand Flag;
1463
Chris Lattner1558fc62006-02-01 18:59:47 +00001464 // We fully assign registers here at isel time. This is not optimal, but
1465 // should work. For register classes that correspond to LLVM classes, we
1466 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1467 // over the constraints, collecting fixed registers that we know we can't use.
1468 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001469 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001470 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1471 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1472 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001473
Chris Lattner7ad77df2006-02-22 00:56:39 +00001474 MVT::ValueType OpVT;
1475
1476 // Compute the value type for each operand and add it to ConstraintVTs.
1477 switch (Constraints[i].Type) {
1478 case InlineAsm::isOutput:
1479 if (!Constraints[i].isIndirectOutput) {
1480 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1481 OpVT = TLI.getValueType(I.getType());
1482 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001483 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001484 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1485 OpNum++; // Consumes a call operand.
1486 }
1487 break;
1488 case InlineAsm::isInput:
1489 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1490 OpNum++; // Consumes a call operand.
1491 break;
1492 case InlineAsm::isClobber:
1493 OpVT = MVT::Other;
1494 break;
1495 }
1496
1497 ConstraintVTs.push_back(OpVT);
1498
Chris Lattner6f87d182006-02-22 22:37:12 +00001499 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1500 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001501
Chris Lattner6f87d182006-02-22 22:37:12 +00001502 // Build a list of regs that this operand uses. This always has a single
1503 // element for promoted/expanded operands.
1504 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1505 false, false,
1506 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001507
1508 switch (Constraints[i].Type) {
1509 case InlineAsm::isOutput:
1510 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001511 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001512 // If this is an early-clobber output, it cannot be assigned to the same
1513 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001514 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001515 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001516 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001517 case InlineAsm::isInput:
1518 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001519 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001520 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001521 case InlineAsm::isClobber:
1522 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001523 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1524 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001525 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001526 }
1527 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001528
Chris Lattner5c79f982006-02-21 23:12:12 +00001529 // Loop over all of the inputs, copying the operand values into the
1530 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001531 RegsForValue RetValRegs;
1532 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001533 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001534
Chris Lattner2e56e892006-01-31 02:03:41 +00001535 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001536 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1537 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001538
Chris Lattner3a5ed552006-02-01 01:28:23 +00001539 switch (Constraints[i].Type) {
1540 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001541 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1542 if (ConstraintCode.size() == 1) // not a physreg name.
1543 CTy = TLI.getConstraintType(ConstraintCode[0]);
1544
1545 if (CTy == TargetLowering::C_Memory) {
1546 // Memory output.
1547 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1548
1549 // Check that the operand (the address to store to) isn't a float.
1550 if (!MVT::isInteger(InOperandVal.getValueType()))
1551 assert(0 && "MATCH FAIL!");
1552
1553 if (!Constraints[i].isIndirectOutput)
1554 assert(0 && "MATCH FAIL!");
1555
1556 OpNum++; // Consumes a call operand.
1557
1558 // Extend/truncate to the right pointer type if needed.
1559 MVT::ValueType PtrType = TLI.getPointerTy();
1560 if (InOperandVal.getValueType() < PtrType)
1561 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1562 else if (InOperandVal.getValueType() > PtrType)
1563 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1564
1565 // Add information to the INLINEASM node to know about this output.
1566 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1567 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1568 AsmNodeOperands.push_back(InOperandVal);
1569 break;
1570 }
1571
1572 // Otherwise, this is a register output.
1573 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1574
Chris Lattner6f87d182006-02-22 22:37:12 +00001575 // If this is an early-clobber output, or if there is an input
1576 // constraint that matches this, we need to reserve the input register
1577 // so no other inputs allocate to it.
1578 bool UsesInputRegister = false;
1579 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1580 UsesInputRegister = true;
1581
1582 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001583 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001584 RegsForValue Regs =
1585 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1586 true, UsesInputRegister,
1587 OutputRegs, InputRegs);
1588 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001589
Chris Lattner3a5ed552006-02-01 01:28:23 +00001590 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001591 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001592 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001593 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001594 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001595 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001596 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1597 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001598 OpNum++; // Consumes a call operand.
1599 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001600
1601 // Add information to the INLINEASM node to know that this register is
1602 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001603 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001604 break;
1605 }
1606 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001607 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001608 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001609
Chris Lattner7f5880b2006-02-02 00:25:23 +00001610 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1611 // If this is required to match an output register we have already set,
1612 // just use its register.
1613 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001614
Chris Lattner571d9642006-02-23 19:21:04 +00001615 // Scan until we find the definition we already emitted of this operand.
1616 // When we find it, create a RegsForValue operand.
1617 unsigned CurOp = 2; // The first operand.
1618 for (; OperandNo; --OperandNo) {
1619 // Advance to the next operand.
1620 unsigned NumOps =
1621 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1622 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1623 "Skipped past definitions?");
1624 CurOp += (NumOps>>3)+1;
1625 }
1626
1627 unsigned NumOps =
1628 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1629 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1630 "Skipped past definitions?");
1631
1632 // Add NumOps>>3 registers to MatchedRegs.
1633 RegsForValue MatchedRegs;
1634 MatchedRegs.ValueVT = InOperandVal.getValueType();
1635 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1636 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1637 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1638 MatchedRegs.Regs.push_back(Reg);
1639 }
1640
1641 // Use the produced MatchedRegs object to
1642 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1643 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001644 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001645 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001646
1647 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1648 if (ConstraintCode.size() == 1) // not a physreg name.
1649 CTy = TLI.getConstraintType(ConstraintCode[0]);
1650
1651 if (CTy == TargetLowering::C_Other) {
1652 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1653 assert(0 && "MATCH FAIL!");
1654
1655 // Add information to the INLINEASM node to know about this input.
1656 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1657 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1658 AsmNodeOperands.push_back(InOperandVal);
1659 break;
1660 } else if (CTy == TargetLowering::C_Memory) {
1661 // Memory input.
1662
1663 // Check that the operand isn't a float.
1664 if (!MVT::isInteger(InOperandVal.getValueType()))
1665 assert(0 && "MATCH FAIL!");
1666
1667 // Extend/truncate to the right pointer type if needed.
1668 MVT::ValueType PtrType = TLI.getPointerTy();
1669 if (InOperandVal.getValueType() < PtrType)
1670 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1671 else if (InOperandVal.getValueType() > PtrType)
1672 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1673
1674 // Add information to the INLINEASM node to know about this input.
1675 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1676 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1677 AsmNodeOperands.push_back(InOperandVal);
1678 break;
1679 }
1680
1681 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1682
1683 // Copy the input into the appropriate registers.
1684 RegsForValue InRegs =
1685 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1686 false, true, OutputRegs, InputRegs);
1687 // FIXME: should be match fail.
1688 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1689
1690 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1691
1692 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001693 break;
1694 }
Chris Lattner571d9642006-02-23 19:21:04 +00001695 case InlineAsm::isClobber: {
1696 RegsForValue ClobberedRegs =
1697 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1698 OutputRegs, InputRegs);
1699 // Add the clobbered value to the operand list, so that the register
1700 // allocator is aware that the physreg got clobbered.
1701 if (!ClobberedRegs.Regs.empty())
1702 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001703 break;
1704 }
Chris Lattner571d9642006-02-23 19:21:04 +00001705 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001706 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001707
1708 // Finish up input operands.
1709 AsmNodeOperands[0] = Chain;
1710 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1711
1712 std::vector<MVT::ValueType> VTs;
1713 VTs.push_back(MVT::Other);
1714 VTs.push_back(MVT::Flag);
1715 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1716 Flag = Chain.getValue(1);
1717
Chris Lattner2e56e892006-01-31 02:03:41 +00001718 // If this asm returns a register value, copy the result from that register
1719 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001720 if (!RetValRegs.Regs.empty())
1721 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001722
Chris Lattner2e56e892006-01-31 02:03:41 +00001723 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1724
1725 // Process indirect outputs, first output all of the flagged copies out of
1726 // physregs.
1727 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001728 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001729 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001730 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1731 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001732 }
1733
1734 // Emit the non-flagged stores from the physregs.
1735 std::vector<SDOperand> OutChains;
1736 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1737 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1738 StoresToEmit[i].first,
1739 getValue(StoresToEmit[i].second),
1740 DAG.getSrcValue(StoresToEmit[i].second)));
1741 if (!OutChains.empty())
1742 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001743 DAG.setRoot(Chain);
1744}
1745
1746
Chris Lattner7a60d912005-01-07 07:47:53 +00001747void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1748 SDOperand Src = getValue(I.getOperand(0));
1749
1750 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001751
1752 if (IntPtr < Src.getValueType())
1753 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1754 else if (IntPtr > Src.getValueType())
1755 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001756
1757 // Scale the source by the type size.
1758 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1759 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1760 Src, getIntPtrConstant(ElementSize));
1761
1762 std::vector<std::pair<SDOperand, const Type*> > Args;
1763 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001764
1765 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001766 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001767 DAG.getExternalSymbol("malloc", IntPtr),
1768 Args, DAG);
1769 setValue(&I, Result.first); // Pointers always fit in registers
1770 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001771}
1772
1773void SelectionDAGLowering::visitFree(FreeInst &I) {
1774 std::vector<std::pair<SDOperand, const Type*> > Args;
1775 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1776 TLI.getTargetData().getIntPtrType()));
1777 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001778 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001779 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001780 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1781 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001782}
1783
Chris Lattner13d7c252005-08-26 20:54:47 +00001784// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1785// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1786// instructions are special in various ways, which require special support to
1787// insert. The specified MachineInstr is created but not inserted into any
1788// basic blocks, and the scheduler passes ownership of it to this method.
1789MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1790 MachineBasicBlock *MBB) {
1791 std::cerr << "If a target marks an instruction with "
1792 "'usesCustomDAGSchedInserter', it must implement "
1793 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1794 abort();
1795 return 0;
1796}
1797
Chris Lattner58cfd792005-01-09 00:00:49 +00001798void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001799 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1800 getValue(I.getOperand(1)),
1801 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001802}
1803
1804void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001805 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1806 getValue(I.getOperand(0)),
1807 DAG.getSrcValue(I.getOperand(0)));
1808 setValue(&I, V);
1809 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001810}
1811
1812void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001813 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1814 getValue(I.getOperand(1)),
1815 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001816}
1817
1818void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001819 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1820 getValue(I.getOperand(1)),
1821 getValue(I.getOperand(2)),
1822 DAG.getSrcValue(I.getOperand(1)),
1823 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001824}
1825
Chris Lattner58cfd792005-01-09 00:00:49 +00001826// It is always conservatively correct for llvm.returnaddress and
1827// llvm.frameaddress to return 0.
1828std::pair<SDOperand, SDOperand>
1829TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1830 unsigned Depth, SelectionDAG &DAG) {
1831 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001832}
1833
Chris Lattner29dcc712005-05-14 05:50:48 +00001834SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001835 assert(0 && "LowerOperation not implemented for this target!");
1836 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001837 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001838}
1839
Nate Begeman595ec732006-01-28 03:14:31 +00001840SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1841 SelectionDAG &DAG) {
1842 assert(0 && "CustomPromoteOperation not implemented for this target!");
1843 abort();
1844 return SDOperand();
1845}
1846
Chris Lattner58cfd792005-01-09 00:00:49 +00001847void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1848 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1849 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001850 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001851 setValue(&I, Result.first);
1852 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001853}
1854
Evan Cheng6781b6e2006-02-15 21:59:04 +00001855/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001856/// operand.
1857static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001858 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001859 MVT::ValueType CurVT = VT;
1860 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1861 uint64_t Val = C->getValue() & 255;
1862 unsigned Shift = 8;
1863 while (CurVT != MVT::i8) {
1864 Val = (Val << Shift) | Val;
1865 Shift <<= 1;
1866 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001867 }
1868 return DAG.getConstant(Val, VT);
1869 } else {
1870 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1871 unsigned Shift = 8;
1872 while (CurVT != MVT::i8) {
1873 Value =
1874 DAG.getNode(ISD::OR, VT,
1875 DAG.getNode(ISD::SHL, VT, Value,
1876 DAG.getConstant(Shift, MVT::i8)), Value);
1877 Shift <<= 1;
1878 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001879 }
1880
1881 return Value;
1882 }
1883}
1884
Evan Cheng6781b6e2006-02-15 21:59:04 +00001885/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1886/// used when a memcpy is turned into a memset when the source is a constant
1887/// string ptr.
1888static SDOperand getMemsetStringVal(MVT::ValueType VT,
1889 SelectionDAG &DAG, TargetLowering &TLI,
1890 std::string &Str, unsigned Offset) {
1891 MVT::ValueType CurVT = VT;
1892 uint64_t Val = 0;
1893 unsigned MSB = getSizeInBits(VT) / 8;
1894 if (TLI.isLittleEndian())
1895 Offset = Offset + MSB - 1;
1896 for (unsigned i = 0; i != MSB; ++i) {
1897 Val = (Val << 8) | Str[Offset];
1898 Offset += TLI.isLittleEndian() ? -1 : 1;
1899 }
1900 return DAG.getConstant(Val, VT);
1901}
1902
Evan Cheng81fcea82006-02-14 08:22:34 +00001903/// getMemBasePlusOffset - Returns base and offset node for the
1904static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1905 SelectionDAG &DAG, TargetLowering &TLI) {
1906 MVT::ValueType VT = Base.getValueType();
1907 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1908}
1909
Evan Chengdb2a7a72006-02-14 20:12:38 +00001910/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001911/// to replace the memset / memcpy is below the threshold. It also returns the
1912/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001913static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1914 unsigned Limit, uint64_t Size,
1915 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001916 MVT::ValueType VT;
1917
1918 if (TLI.allowsUnalignedMemoryAccesses()) {
1919 VT = MVT::i64;
1920 } else {
1921 switch (Align & 7) {
1922 case 0:
1923 VT = MVT::i64;
1924 break;
1925 case 4:
1926 VT = MVT::i32;
1927 break;
1928 case 2:
1929 VT = MVT::i16;
1930 break;
1931 default:
1932 VT = MVT::i8;
1933 break;
1934 }
1935 }
1936
Evan Chengd5026102006-02-14 09:11:59 +00001937 MVT::ValueType LVT = MVT::i64;
1938 while (!TLI.isTypeLegal(LVT))
1939 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1940 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001941
Evan Chengd5026102006-02-14 09:11:59 +00001942 if (VT > LVT)
1943 VT = LVT;
1944
Evan Cheng04514992006-02-14 23:05:54 +00001945 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001946 while (Size != 0) {
1947 unsigned VTSize = getSizeInBits(VT) / 8;
1948 while (VTSize > Size) {
1949 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001950 VTSize >>= 1;
1951 }
Evan Chengd5026102006-02-14 09:11:59 +00001952 assert(MVT::isInteger(VT));
1953
1954 if (++NumMemOps > Limit)
1955 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001956 MemOps.push_back(VT);
1957 Size -= VTSize;
1958 }
Evan Chengd5026102006-02-14 09:11:59 +00001959
1960 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001961}
1962
Chris Lattner875def92005-01-11 05:56:49 +00001963void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001964 SDOperand Op1 = getValue(I.getOperand(1));
1965 SDOperand Op2 = getValue(I.getOperand(2));
1966 SDOperand Op3 = getValue(I.getOperand(3));
1967 SDOperand Op4 = getValue(I.getOperand(4));
1968 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1969 if (Align == 0) Align = 1;
1970
1971 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1972 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001973
1974 // Expand memset / memcpy to a series of load / store ops
1975 // if the size operand falls below a certain threshold.
1976 std::vector<SDOperand> OutChains;
1977 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001978 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001979 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001980 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1981 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001982 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001983 unsigned Offset = 0;
1984 for (unsigned i = 0; i < NumMemOps; i++) {
1985 MVT::ValueType VT = MemOps[i];
1986 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001987 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001988 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1989 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001990 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1991 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001992 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001993 Offset += VTSize;
1994 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001995 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001996 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001997 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001998 case ISD::MEMCPY: {
1999 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2000 Size->getValue(), Align, TLI)) {
2001 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002002 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002003 GlobalAddressSDNode *G = NULL;
2004 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002005 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002006
2007 if (Op2.getOpcode() == ISD::GlobalAddress)
2008 G = cast<GlobalAddressSDNode>(Op2);
2009 else if (Op2.getOpcode() == ISD::ADD &&
2010 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2011 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2012 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002013 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002014 }
2015 if (G) {
2016 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002017 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002018 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002019 if (!Str.empty()) {
2020 CopyFromStr = true;
2021 SrcOff += SrcDelta;
2022 }
2023 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002024 }
2025
Evan Chenge2038bd2006-02-15 01:54:51 +00002026 for (unsigned i = 0; i < NumMemOps; i++) {
2027 MVT::ValueType VT = MemOps[i];
2028 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002029 SDOperand Value, Chain, Store;
2030
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002031 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002032 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2033 Chain = getRoot();
2034 Store =
2035 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2036 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2037 DAG.getSrcValue(I.getOperand(1), DstOff));
2038 } else {
2039 Value = DAG.getLoad(VT, getRoot(),
2040 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2041 DAG.getSrcValue(I.getOperand(2), SrcOff));
2042 Chain = Value.getValue(1);
2043 Store =
2044 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2045 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2046 DAG.getSrcValue(I.getOperand(1), DstOff));
2047 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002048 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002049 SrcOff += VTSize;
2050 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002051 }
2052 }
2053 break;
2054 }
2055 }
2056
2057 if (!OutChains.empty()) {
2058 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2059 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002060 }
2061 }
2062
Chris Lattner875def92005-01-11 05:56:49 +00002063 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002064 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002065 Ops.push_back(Op1);
2066 Ops.push_back(Op2);
2067 Ops.push_back(Op3);
2068 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002069 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002070}
2071
Chris Lattner875def92005-01-11 05:56:49 +00002072//===----------------------------------------------------------------------===//
2073// SelectionDAGISel code
2074//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002075
2076unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2077 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2078}
2079
Chris Lattnerc9950c12005-08-17 06:37:43 +00002080void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002081 // FIXME: we only modify the CFG to split critical edges. This
2082 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002083}
Chris Lattner7a60d912005-01-07 07:47:53 +00002084
Chris Lattner35397782005-12-05 07:10:48 +00002085
2086/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2087/// casting to the type of GEPI.
2088static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2089 Value *Ptr, Value *PtrOffset) {
2090 if (V) return V; // Already computed.
2091
2092 BasicBlock::iterator InsertPt;
2093 if (BB == GEPI->getParent()) {
2094 // If insert into the GEP's block, insert right after the GEP.
2095 InsertPt = GEPI;
2096 ++InsertPt;
2097 } else {
2098 // Otherwise, insert at the top of BB, after any PHI nodes
2099 InsertPt = BB->begin();
2100 while (isa<PHINode>(InsertPt)) ++InsertPt;
2101 }
2102
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002103 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2104 // BB so that there is only one value live across basic blocks (the cast
2105 // operand).
2106 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2107 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2108 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2109
Chris Lattner35397782005-12-05 07:10:48 +00002110 // Add the offset, cast it to the right type.
2111 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2112 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2113 return V = Ptr;
2114}
2115
2116
2117/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2118/// selection, we want to be a bit careful about some things. In particular, if
2119/// we have a GEP instruction that is used in a different block than it is
2120/// defined, the addressing expression of the GEP cannot be folded into loads or
2121/// stores that use it. In this case, decompose the GEP and move constant
2122/// indices into blocks that use it.
2123static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2124 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002125 // If this GEP is only used inside the block it is defined in, there is no
2126 // need to rewrite it.
2127 bool isUsedOutsideDefBB = false;
2128 BasicBlock *DefBB = GEPI->getParent();
2129 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2130 UI != E; ++UI) {
2131 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2132 isUsedOutsideDefBB = true;
2133 break;
2134 }
2135 }
2136 if (!isUsedOutsideDefBB) return;
2137
2138 // If this GEP has no non-zero constant indices, there is nothing we can do,
2139 // ignore it.
2140 bool hasConstantIndex = false;
2141 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2142 E = GEPI->op_end(); OI != E; ++OI) {
2143 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2144 if (CI->getRawValue()) {
2145 hasConstantIndex = true;
2146 break;
2147 }
2148 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002149 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2150 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002151
2152 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2153 // constant offset (which we now know is non-zero) and deal with it later.
2154 uint64_t ConstantOffset = 0;
2155 const Type *UIntPtrTy = TD.getIntPtrType();
2156 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2157 const Type *Ty = GEPI->getOperand(0)->getType();
2158
2159 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2160 E = GEPI->op_end(); OI != E; ++OI) {
2161 Value *Idx = *OI;
2162 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2163 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2164 if (Field)
2165 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2166 Ty = StTy->getElementType(Field);
2167 } else {
2168 Ty = cast<SequentialType>(Ty)->getElementType();
2169
2170 // Handle constant subscripts.
2171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2172 if (CI->getRawValue() == 0) continue;
2173
2174 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2175 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2176 else
2177 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2178 continue;
2179 }
2180
2181 // Ptr = Ptr + Idx * ElementSize;
2182
2183 // Cast Idx to UIntPtrTy if needed.
2184 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2185
2186 uint64_t ElementSize = TD.getTypeSize(Ty);
2187 // Mask off bits that should not be set.
2188 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2189 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2190
2191 // Multiply by the element size and add to the base.
2192 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2193 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2194 }
2195 }
2196
2197 // Make sure that the offset fits in uintptr_t.
2198 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2199 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2200
2201 // Okay, we have now emitted all of the variable index parts to the BB that
2202 // the GEP is defined in. Loop over all of the using instructions, inserting
2203 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002204 // instruction to use the newly computed value, making GEPI dead. When the
2205 // user is a load or store instruction address, we emit the add into the user
2206 // block, otherwise we use a canonical version right next to the gep (these
2207 // won't be foldable as addresses, so we might as well share the computation).
2208
Chris Lattner35397782005-12-05 07:10:48 +00002209 std::map<BasicBlock*,Value*> InsertedExprs;
2210 while (!GEPI->use_empty()) {
2211 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002212
2213 // If this use is not foldable into the addressing mode, use a version
2214 // emitted in the GEP block.
2215 Value *NewVal;
2216 if (!isa<LoadInst>(User) &&
2217 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2218 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2219 Ptr, PtrOffset);
2220 } else {
2221 // Otherwise, insert the code in the User's block so it can be folded into
2222 // any users in that block.
2223 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002224 User->getParent(), GEPI,
2225 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002226 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002227 User->replaceUsesOfWith(GEPI, NewVal);
2228 }
Chris Lattner35397782005-12-05 07:10:48 +00002229
2230 // Finally, the GEP is dead, remove it.
2231 GEPI->eraseFromParent();
2232}
2233
Chris Lattner7a60d912005-01-07 07:47:53 +00002234bool SelectionDAGISel::runOnFunction(Function &Fn) {
2235 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2236 RegMap = MF.getSSARegMap();
2237 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2238
Chris Lattner35397782005-12-05 07:10:48 +00002239 // First, split all critical edges for PHI nodes with incoming values that are
2240 // constants, this way the load of the constant into a vreg will not be placed
2241 // into MBBs that are used some other way.
2242 //
2243 // In this pass we also look for GEP instructions that are used across basic
2244 // blocks and rewrites them to improve basic-block-at-a-time selection.
2245 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002246 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2247 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002248 BasicBlock::iterator BBI;
2249 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002250 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2251 if (isa<Constant>(PN->getIncomingValue(i)))
2252 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002253
2254 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2255 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2256 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002257 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002258
Chris Lattner7a60d912005-01-07 07:47:53 +00002259 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2260
2261 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2262 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002263
Chris Lattner7a60d912005-01-07 07:47:53 +00002264 return true;
2265}
2266
2267
Chris Lattner718b5c22005-01-13 17:59:43 +00002268SDOperand SelectionDAGISel::
2269CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002270 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002271 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002272 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002273 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002274
2275 // If this type is not legal, we must make sure to not create an invalid
2276 // register use.
2277 MVT::ValueType SrcVT = Op.getValueType();
2278 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2279 SelectionDAG &DAG = SDL.DAG;
2280 if (SrcVT == DestVT) {
2281 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2282 } else if (SrcVT < DestVT) {
2283 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002284 if (MVT::isFloatingPoint(SrcVT))
2285 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2286 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002287 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002288 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2289 } else {
2290 // The src value is expanded into multiple registers.
2291 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2292 Op, DAG.getConstant(0, MVT::i32));
2293 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2294 Op, DAG.getConstant(1, MVT::i32));
2295 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2296 return DAG.getCopyToReg(Op, Reg+1, Hi);
2297 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002298}
2299
Chris Lattner16f64df2005-01-17 17:15:02 +00002300void SelectionDAGISel::
2301LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2302 std::vector<SDOperand> &UnorderedChains) {
2303 // If this is the entry block, emit arguments.
2304 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002305 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002306 SDOperand OldRoot = SDL.DAG.getRoot();
2307 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002308
Chris Lattner6871b232005-10-30 19:42:35 +00002309 unsigned a = 0;
2310 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2311 AI != E; ++AI, ++a)
2312 if (!AI->use_empty()) {
2313 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002314
Chris Lattner6871b232005-10-30 19:42:35 +00002315 // If this argument is live outside of the entry block, insert a copy from
2316 // whereever we got it to the vreg that other BB's will reference it as.
2317 if (FuncInfo.ValueMap.count(AI)) {
2318 SDOperand Copy =
2319 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2320 UnorderedChains.push_back(Copy);
2321 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002322 }
Chris Lattner6871b232005-10-30 19:42:35 +00002323
2324 // Next, if the function has live ins that need to be copied into vregs,
2325 // emit the copies now, into the top of the block.
2326 MachineFunction &MF = SDL.DAG.getMachineFunction();
2327 if (MF.livein_begin() != MF.livein_end()) {
2328 SSARegMap *RegMap = MF.getSSARegMap();
2329 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2330 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2331 E = MF.livein_end(); LI != E; ++LI)
2332 if (LI->second)
2333 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2334 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002335 }
Chris Lattner6871b232005-10-30 19:42:35 +00002336
2337 // Finally, if the target has anything special to do, allow it to do so.
2338 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002339}
2340
2341
Chris Lattner7a60d912005-01-07 07:47:53 +00002342void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2343 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2344 FunctionLoweringInfo &FuncInfo) {
2345 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002346
2347 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002348
Chris Lattner6871b232005-10-30 19:42:35 +00002349 // Lower any arguments needed in this block if this is the entry block.
2350 if (LLVMBB == &LLVMBB->getParent()->front())
2351 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002352
2353 BB = FuncInfo.MBBMap[LLVMBB];
2354 SDL.setCurrentBasicBlock(BB);
2355
2356 // Lower all of the non-terminator instructions.
2357 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2358 I != E; ++I)
2359 SDL.visit(*I);
2360
2361 // Ensure that all instructions which are used outside of their defining
2362 // blocks are available as virtual registers.
2363 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002364 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002365 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002366 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002367 UnorderedChains.push_back(
2368 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002369 }
2370
2371 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2372 // ensure constants are generated when needed. Remember the virtual registers
2373 // that need to be added to the Machine PHI nodes as input. We cannot just
2374 // directly add them, because expansion might result in multiple MBB's for one
2375 // BB. As such, the start of the BB might correspond to a different MBB than
2376 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002377 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002378
2379 // Emit constants only once even if used by multiple PHI nodes.
2380 std::map<Constant*, unsigned> ConstantsOut;
2381
2382 // Check successor nodes PHI nodes that expect a constant to be available from
2383 // this block.
2384 TerminatorInst *TI = LLVMBB->getTerminator();
2385 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2386 BasicBlock *SuccBB = TI->getSuccessor(succ);
2387 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2388 PHINode *PN;
2389
2390 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2391 // nodes and Machine PHI nodes, but the incoming operands have not been
2392 // emitted yet.
2393 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002394 (PN = dyn_cast<PHINode>(I)); ++I)
2395 if (!PN->use_empty()) {
2396 unsigned Reg;
2397 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2398 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2399 unsigned &RegOut = ConstantsOut[C];
2400 if (RegOut == 0) {
2401 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002402 UnorderedChains.push_back(
2403 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002404 }
2405 Reg = RegOut;
2406 } else {
2407 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002408 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002409 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002410 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2411 "Didn't codegen value into a register!??");
2412 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002413 UnorderedChains.push_back(
2414 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002415 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002416 }
Misha Brukman835702a2005-04-21 22:36:52 +00002417
Chris Lattner8ea875f2005-01-07 21:34:19 +00002418 // Remember that this register needs to added to the machine PHI node as
2419 // the input for this MBB.
2420 unsigned NumElements =
2421 TLI.getNumElements(TLI.getValueType(PN->getType()));
2422 for (unsigned i = 0, e = NumElements; i != e; ++i)
2423 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002424 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002425 }
2426 ConstantsOut.clear();
2427
Chris Lattner718b5c22005-01-13 17:59:43 +00002428 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002429 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002430 SDOperand Root = SDL.getRoot();
2431 if (Root.getOpcode() != ISD::EntryToken) {
2432 unsigned i = 0, e = UnorderedChains.size();
2433 for (; i != e; ++i) {
2434 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2435 if (UnorderedChains[i].Val->getOperand(0) == Root)
2436 break; // Don't add the root if we already indirectly depend on it.
2437 }
2438
2439 if (i == e)
2440 UnorderedChains.push_back(Root);
2441 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002442 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2443 }
2444
Chris Lattner7a60d912005-01-07 07:47:53 +00002445 // Lower the terminator after the copies are emitted.
2446 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002447
2448 // Make sure the root of the DAG is up-to-date.
2449 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002450}
2451
2452void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2453 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002454 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002455 CurDAG = &DAG;
2456 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2457
2458 // First step, lower LLVM code to some DAG. This DAG may use operations and
2459 // types that are not supported by the target.
2460 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2461
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002462 // Run the DAG combiner in pre-legalize mode.
2463 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002464
Chris Lattner7a60d912005-01-07 07:47:53 +00002465 DEBUG(std::cerr << "Lowered selection DAG:\n");
2466 DEBUG(DAG.dump());
2467
2468 // Second step, hack on the DAG until it only uses operations and types that
2469 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002470 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002471
2472 DEBUG(std::cerr << "Legalized selection DAG:\n");
2473 DEBUG(DAG.dump());
2474
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002475 // Run the DAG combiner in post-legalize mode.
2476 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002477
Evan Cheng739a6a42006-01-21 02:32:06 +00002478 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002479
Chris Lattner5ca31d92005-03-30 01:10:47 +00002480 // Third, instruction select all of the operations to machine code, adding the
2481 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002482 InstructionSelectBasicBlock(DAG);
2483
Chris Lattner7a60d912005-01-07 07:47:53 +00002484 DEBUG(std::cerr << "Selected machine code:\n");
2485 DEBUG(BB->dump());
2486
Chris Lattner5ca31d92005-03-30 01:10:47 +00002487 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002488 // PHI nodes in successors.
2489 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2490 MachineInstr *PHI = PHINodesToUpdate[i].first;
2491 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2492 "This is not a machine PHI node that we are updating!");
2493 PHI->addRegOperand(PHINodesToUpdate[i].second);
2494 PHI->addMachineBasicBlockOperand(BB);
2495 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002496
2497 // Finally, add the CFG edges from the last selected MBB to the successor
2498 // MBBs.
2499 TerminatorInst *TI = LLVMBB->getTerminator();
2500 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2501 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2502 BB->addSuccessor(Succ0MBB);
2503 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002504}
Evan Cheng739a6a42006-01-21 02:32:06 +00002505
2506//===----------------------------------------------------------------------===//
2507/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2508/// target node in the graph.
2509void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2510 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002511 ScheduleDAG *SL = NULL;
2512
2513 switch (ISHeuristic) {
2514 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002515 case defaultScheduling:
2516 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2517 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2518 else /* TargetLowering::SchedulingForRegPressure */
2519 SL = createBURRListDAGScheduler(DAG, BB);
2520 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002521 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002522 SL = createBFS_DAGScheduler(DAG, BB);
2523 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002524 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002525 SL = createSimpleDAGScheduler(false, DAG, BB);
2526 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002527 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002528 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002529 break;
Evan Cheng31272342006-01-23 08:26:10 +00002530 case listSchedulingBURR:
2531 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002532 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002533 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002534 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002535 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002536 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002537 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002538 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002539}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002540
Chris Lattner543832d2006-03-08 04:25:59 +00002541HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2542 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002543}
2544
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002545/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2546/// by tblgen. Others should not call it.
2547void SelectionDAGISel::
2548SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2549 std::vector<SDOperand> InOps;
2550 std::swap(InOps, Ops);
2551
2552 Ops.push_back(InOps[0]); // input chain.
2553 Ops.push_back(InOps[1]); // input asm string.
2554
2555 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2556 unsigned i = 2, e = InOps.size();
2557 if (InOps[e-1].getValueType() == MVT::Flag)
2558 --e; // Don't process a flag operand if it is here.
2559
2560 while (i != e) {
2561 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2562 if ((Flags & 7) != 4 /*MEM*/) {
2563 // Just skip over this operand, copying the operands verbatim.
2564 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2565 i += (Flags >> 3) + 1;
2566 } else {
2567 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2568 // Otherwise, this is a memory operand. Ask the target to select it.
2569 std::vector<SDOperand> SelOps;
2570 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2571 std::cerr << "Could not match memory address. Inline asm failure!\n";
2572 exit(1);
2573 }
2574
2575 // Add this to the output node.
2576 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2577 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2578 i += 2;
2579 }
2580 }
2581
2582 // Add the flag input back if present.
2583 if (e != InOps.size())
2584 Ops.push_back(InOps.back());
2585}