blob: de4d2ec686edeafe17c1a9db0e9c554ebebbfd99 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner49409cb2006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
185/// PHI nodes or outside of the basic block that defines it.
186static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
187 if (isa<PHINode>(I)) return true;
188 BasicBlock *BB = I->getParent();
189 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
190 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
191 return true;
192 return false;
193}
194
Chris Lattner6871b232005-10-30 19:42:35 +0000195/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
196/// entry block, return true.
197static bool isOnlyUsedInEntryBlock(Argument *A) {
198 BasicBlock *Entry = A->getParent()->begin();
199 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != Entry)
201 return false; // Use not in entry block.
202 return true;
203}
204
Chris Lattner7a60d912005-01-07 07:47:53 +0000205FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000206 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
208
Chris Lattner6871b232005-10-30 19:42:35 +0000209 // Create a vreg for each argument register that is not dead and is used
210 // outside of the entry block for the function.
211 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
212 AI != E; ++AI)
213 if (!isOnlyUsedInEntryBlock(AI))
214 InitializeRegForValue(AI);
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216 // Initialize the mapping of values to registers. This is only set up for
217 // instruction values that are used outside of the block that defines
218 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000219 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
222 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
223 const Type *Ty = AI->getAllocatedType();
224 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000225 unsigned Align =
226 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
227 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000228
229 // If the alignment of the value is smaller than the size of the value,
230 // and if the size of the value is particularly small (<= 8 bytes),
231 // round up to the size of the value for potentially better performance.
232 //
233 // FIXME: This could be made better with a preferred alignment hook in
234 // TargetData. It serves primarily to 8-byte align doubles for X86.
235 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000236 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000237 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000239 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 }
241
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000242 for (; BB != EB; ++BB)
243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
245 if (!isa<AllocaInst>(I) ||
246 !StaticAllocaMap.count(cast<AllocaInst>(I)))
247 InitializeRegForValue(I);
248
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000252 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
254 MBBMap[BB] = MBB;
255 MF.getBasicBlockList().push_back(MBB);
256
257 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
258 // appropriate.
259 PHINode *PN;
260 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000261 (PN = dyn_cast<PHINode>(I)); ++I)
262 if (!PN->use_empty()) {
263 unsigned NumElements =
264 TLI.getNumElements(TLI.getValueType(PN->getType()));
265 unsigned PHIReg = ValueMap[PN];
266 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
267 for (unsigned i = 0; i != NumElements; ++i)
268 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
269 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000270 }
271}
272
Chris Lattner49409cb2006-03-16 19:51:18 +0000273/// CreateRegForValue - Allocate the appropriate number of virtual registers of
274/// the correctly promoted or expanded types. Assign these registers
275/// consecutive vreg numbers and return the first assigned number.
276unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278
279 // The number of multiples of registers that we need, to, e.g., split up
280 // a <2 x int64> -> 4 x i32 registers.
281 unsigned NumVectorRegs = 1;
282
283 // If this is a packed type, figure out what type it will decompose into
284 // and how many of the elements it will use.
285 if (VT == MVT::Vector) {
286 const PackedType *PTy = cast<PackedType>(V->getType());
287 unsigned NumElts = PTy->getNumElements();
288 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
289
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
293 NumElts >>= 1;
294 NumVectorRegs <<= 1;
295 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000296 if (NumElts == 1)
297 VT = EltTy;
298 else
299 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000300 }
301
302 // The common case is that we will only create one register for this
303 // value. If we have that case, create and return the virtual register.
304 unsigned NV = TLI.getNumElements(VT);
305 if (NV == 1) {
306 // If we are promoting this value, pick the next largest supported type.
307 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
308 unsigned Reg = MakeReg(PromotedType);
309 // If this is a vector of supported or promoted types (e.g. 4 x i16),
310 // create all of the registers.
311 for (unsigned i = 1; i != NumVectorRegs; ++i)
312 MakeReg(PromotedType);
313 return Reg;
314 }
315
316 // If this value is represented with multiple target registers, make sure
317 // to create enough consecutive registers of the right (smaller) type.
318 unsigned NT = VT-1; // Find the type to use.
319 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
320 --NT;
321
322 unsigned R = MakeReg((MVT::ValueType)NT);
323 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
324 MakeReg((MVT::ValueType)NT);
325 return R;
326}
Chris Lattner7a60d912005-01-07 07:47:53 +0000327
328//===----------------------------------------------------------------------===//
329/// SelectionDAGLowering - This is the common target-independent lowering
330/// implementation that is parameterized by a TargetLowering object.
331/// Also, targets can overload any lowering method.
332///
333namespace llvm {
334class SelectionDAGLowering {
335 MachineBasicBlock *CurMBB;
336
337 std::map<const Value*, SDOperand> NodeMap;
338
Chris Lattner4d9651c2005-01-17 22:19:26 +0000339 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
340 /// them up and then emit token factor nodes when possible. This allows us to
341 /// get simple disambiguation between loads without worrying about alias
342 /// analysis.
343 std::vector<SDOperand> PendingLoads;
344
Chris Lattner7a60d912005-01-07 07:47:53 +0000345public:
346 // TLI - This is information that describes the available target features we
347 // need for lowering. This indicates when operations are unavailable,
348 // implemented with a libcall, etc.
349 TargetLowering &TLI;
350 SelectionDAG &DAG;
351 const TargetData &TD;
352
353 /// FuncInfo - Information about the function as a whole.
354 ///
355 FunctionLoweringInfo &FuncInfo;
356
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000358 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000359 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
360 FuncInfo(funcinfo) {
361 }
362
Chris Lattner4108bb02005-01-17 19:43:36 +0000363 /// getRoot - Return the current virtual root of the Selection DAG.
364 ///
365 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000366 if (PendingLoads.empty())
367 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000368
Chris Lattner4d9651c2005-01-17 22:19:26 +0000369 if (PendingLoads.size() == 1) {
370 SDOperand Root = PendingLoads[0];
371 DAG.setRoot(Root);
372 PendingLoads.clear();
373 return Root;
374 }
375
376 // Otherwise, we have to make a token factor node.
377 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
378 PendingLoads.clear();
379 DAG.setRoot(Root);
380 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000381 }
382
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 void visit(Instruction &I) { visit(I.getOpcode(), I); }
384
385 void visit(unsigned Opcode, User &I) {
386 switch (Opcode) {
387 default: assert(0 && "Unknown instruction type encountered!");
388 abort();
389 // Build the switch statement using the Instruction.def file.
390#define HANDLE_INST(NUM, OPCODE, CLASS) \
391 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
392#include "llvm/Instruction.def"
393 }
394 }
395
396 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
397
Chris Lattner4024c002006-03-15 22:19:46 +0000398 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
399 SDOperand SrcValue, SDOperand Root,
400 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000401
402 SDOperand getIntPtrConstant(uint64_t Val) {
403 return DAG.getConstant(Val, TLI.getPointerTy());
404 }
405
Chris Lattner8471b152006-03-16 19:57:50 +0000406 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407
408 const SDOperand &setValue(const Value *V, SDOperand NewN) {
409 SDOperand &N = NodeMap[V];
410 assert(N.Val == 0 && "Already set a value for this node!");
411 return N = NewN;
412 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000413
Chris Lattner6f87d182006-02-22 22:37:12 +0000414 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
415 MVT::ValueType VT,
416 bool OutReg, bool InReg,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
419
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
424
425 // These all get lowered before this pass.
426 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
427 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
428 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
429
430 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000431 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000432 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000433 void visitAdd(User &I) {
434 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000435 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000436 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000437 void visitMul(User &I) {
438 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000439 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000441 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000442 visitBinary(I,
443 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
444 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000445 }
446 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000447 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000448 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000449 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000450 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
451 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
452 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000453 void visitShl(User &I) { visitShift(I, ISD::SHL); }
454 void visitShr(User &I) {
455 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 }
457
458 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
459 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
460 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
461 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
462 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
463 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
464 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
465
Chris Lattner32206f52006-03-18 01:44:44 +0000466 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
467 void visitInsertElement(InsertElementInst &I);
468
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 void visitGetElementPtr(User &I);
470 void visitCast(User &I);
471 void visitSelect(User &I);
472 //
473
474 void visitMalloc(MallocInst &I);
475 void visitFree(FreeInst &I);
476 void visitAlloca(AllocaInst &I);
477 void visitLoad(LoadInst &I);
478 void visitStore(StoreInst &I);
479 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
480 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000481 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000482 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000483
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000485 void visitVAArg(VAArgInst &I);
486 void visitVAEnd(CallInst &I);
487 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000488 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489
Chris Lattner875def92005-01-11 05:56:49 +0000490 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000491
492 void visitUserOp1(Instruction &I) {
493 assert(0 && "UserOp1 should not exist at instruction selection time!");
494 abort();
495 }
496 void visitUserOp2(Instruction &I) {
497 assert(0 && "UserOp2 should not exist at instruction selection time!");
498 abort();
499 }
500};
501} // end namespace llvm
502
Chris Lattner8471b152006-03-16 19:57:50 +0000503SDOperand SelectionDAGLowering::getValue(const Value *V) {
504 SDOperand &N = NodeMap[V];
505 if (N.Val) return N;
506
507 const Type *VTy = V->getType();
508 MVT::ValueType VT = TLI.getValueType(VTy);
509 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
511 visit(CE->getOpcode(), *CE);
512 assert(N.Val && "visit didn't populate the ValueMap!");
513 return N;
514 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
515 return N = DAG.getGlobalAddress(GV, VT);
516 } else if (isa<ConstantPointerNull>(C)) {
517 return N = DAG.getConstant(0, TLI.getPointerTy());
518 } else if (isa<UndefValue>(C)) {
519 return N = DAG.getNode(ISD::UNDEF, VT);
520 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
521 return N = DAG.getConstantFP(CFP->getValue(), VT);
522 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
523 unsigned NumElements = PTy->getNumElements();
524 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
525 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
526
527 // Now that we know the number and type of the elements, push a
528 // Constant or ConstantFP node onto the ops list for each element of
529 // the packed constant.
530 std::vector<SDOperand> Ops;
531 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
532 if (MVT::isFloatingPoint(PVT)) {
533 for (unsigned i = 0; i != NumElements; ++i) {
534 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
535 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
536 }
537 } else {
538 for (unsigned i = 0; i != NumElements; ++i) {
539 const ConstantIntegral *El =
540 cast<ConstantIntegral>(CP->getOperand(i));
541 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
542 }
543 }
544 } else {
545 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
546 SDOperand Op;
547 if (MVT::isFloatingPoint(PVT))
548 Op = DAG.getConstantFP(0, PVT);
549 else
550 Op = DAG.getConstant(0, PVT);
551 Ops.assign(NumElements, Op);
552 }
553
Chris Lattner32206f52006-03-18 01:44:44 +0000554 // Create a ConstantVec node with generic Vector type.
555 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
556 SDOperand Typ = DAG.getValueType(PVT);
557 Ops.push_back(Num);
558 Ops.push_back(Typ);
559 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000560 } else {
561 // Canonicalize all constant ints to be unsigned.
562 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
563 }
564 }
565
566 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
567 std::map<const AllocaInst*, int>::iterator SI =
568 FuncInfo.StaticAllocaMap.find(AI);
569 if (SI != FuncInfo.StaticAllocaMap.end())
570 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
571 }
572
573 std::map<const Value*, unsigned>::const_iterator VMI =
574 FuncInfo.ValueMap.find(V);
575 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
576
577 unsigned InReg = VMI->second;
578
579 // If this type is not legal, make it so now.
580 if (VT == MVT::Vector) {
581 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
582 const PackedType *PTy = cast<PackedType>(VTy);
583 unsigned NumElements = PTy->getNumElements();
584 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
585 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
586 assert(TLI.isTypeLegal(TVT) &&
587 "FIXME: Cannot handle illegal vector types here yet!");
588 VT = TVT;
589 }
590
591 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
592
593 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
594 if (DestVT < VT) {
595 // Source must be expanded. This input value is actually coming from the
596 // register pair VMI->second and VMI->second+1.
597 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
598 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
599 } else {
600 if (DestVT > VT) { // Promotion case
601 if (MVT::isFloatingPoint(VT))
602 N = DAG.getNode(ISD::FP_ROUND, VT, N);
603 else
604 N = DAG.getNode(ISD::TRUNCATE, VT, N);
605 }
606 }
607
608 return N;
609}
610
611
Chris Lattner7a60d912005-01-07 07:47:53 +0000612void SelectionDAGLowering::visitRet(ReturnInst &I) {
613 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000614 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000615 return;
616 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000617 std::vector<SDOperand> NewValues;
618 NewValues.push_back(getRoot());
619 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
620 SDOperand RetOp = getValue(I.getOperand(i));
621
622 // If this is an integer return value, we need to promote it ourselves to
623 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
624 // than sign/zero.
625 if (MVT::isInteger(RetOp.getValueType()) &&
626 RetOp.getValueType() < MVT::i64) {
627 MVT::ValueType TmpVT;
628 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
629 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
630 else
631 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000632
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000633 if (I.getOperand(i)->getType()->isSigned())
634 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
635 else
636 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
637 }
638 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000639 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000640 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000641}
642
643void SelectionDAGLowering::visitBr(BranchInst &I) {
644 // Update machine-CFG edges.
645 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000646
647 // Figure out which block is immediately after the current one.
648 MachineBasicBlock *NextBlock = 0;
649 MachineFunction::iterator BBI = CurMBB;
650 if (++BBI != CurMBB->getParent()->end())
651 NextBlock = BBI;
652
653 if (I.isUnconditional()) {
654 // If this is not a fall-through branch, emit the branch.
655 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000656 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000657 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000658 } else {
659 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000660
661 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000662 if (Succ1MBB == NextBlock) {
663 // If the condition is false, fall through. This means we should branch
664 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000665 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000666 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000667 } else if (Succ0MBB == NextBlock) {
668 // If the condition is true, fall through. This means we should branch if
669 // the condition is false to Succ #1. Invert the condition first.
670 SDOperand True = DAG.getConstant(1, Cond.getValueType());
671 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000672 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000673 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000674 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000675 std::vector<SDOperand> Ops;
676 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000677 // If the false case is the current basic block, then this is a self
678 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
679 // adds an extra instruction in the loop. Instead, invert the
680 // condition and emit "Loop: ... br!cond Loop; br Out.
681 if (CurMBB == Succ1MBB) {
682 std::swap(Succ0MBB, Succ1MBB);
683 SDOperand True = DAG.getConstant(1, Cond.getValueType());
684 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
685 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000686 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
687 DAG.getBasicBlock(Succ0MBB));
688 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
689 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000690 }
691 }
692}
693
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000694void SelectionDAGLowering::visitSub(User &I) {
695 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000696 if (I.getType()->isFloatingPoint()) {
697 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
698 if (CFP->isExactlyValue(-0.0)) {
699 SDOperand Op2 = getValue(I.getOperand(1));
700 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
701 return;
702 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000703 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000704 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000705}
706
Nate Begemanb2e089c2005-11-19 00:36:38 +0000707void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
708 unsigned VecOp) {
709 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000710 SDOperand Op1 = getValue(I.getOperand(0));
711 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000712
Chris Lattner19baba62005-11-19 18:40:42 +0000713 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000714 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
715 } else if (Ty->isFloatingPoint()) {
716 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
717 } else {
718 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +0000719 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
720 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
721 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +0000722 }
Nate Begeman127321b2005-11-18 07:42:56 +0000723}
Chris Lattner96c26752005-01-19 22:31:21 +0000724
Nate Begeman127321b2005-11-18 07:42:56 +0000725void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
726 SDOperand Op1 = getValue(I.getOperand(0));
727 SDOperand Op2 = getValue(I.getOperand(1));
728
729 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
730
Chris Lattner7a60d912005-01-07 07:47:53 +0000731 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
732}
733
734void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
735 ISD::CondCode UnsignedOpcode) {
736 SDOperand Op1 = getValue(I.getOperand(0));
737 SDOperand Op2 = getValue(I.getOperand(1));
738 ISD::CondCode Opcode = SignedOpcode;
739 if (I.getOperand(0)->getType()->isUnsigned())
740 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000741 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000742}
743
744void SelectionDAGLowering::visitSelect(User &I) {
745 SDOperand Cond = getValue(I.getOperand(0));
746 SDOperand TrueVal = getValue(I.getOperand(1));
747 SDOperand FalseVal = getValue(I.getOperand(2));
748 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
749 TrueVal, FalseVal));
750}
751
752void SelectionDAGLowering::visitCast(User &I) {
753 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000754 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
755 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000756
Chris Lattner4024c002006-03-15 22:19:46 +0000757 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000758 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000759 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000760 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000761 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000762 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000763 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000764 } else if (isInteger(SrcVT)) {
765 if (isInteger(DestVT)) { // Int -> Int cast
766 if (DestVT < SrcVT) // Truncating cast?
767 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000768 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000769 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000770 else
Chris Lattner4024c002006-03-15 22:19:46 +0000771 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000772 } else { // Int -> FP cast
773 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000774 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000775 else
Chris Lattner4024c002006-03-15 22:19:46 +0000776 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000777 }
Chris Lattner4024c002006-03-15 22:19:46 +0000778 } else if (isFloatingPoint(SrcVT)) {
779 if (isFloatingPoint(DestVT)) { // FP -> FP cast
780 if (DestVT < SrcVT) // Rounding cast?
781 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000782 else
Chris Lattner4024c002006-03-15 22:19:46 +0000783 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000784 } else { // FP -> Int cast.
785 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000786 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000787 else
Chris Lattner4024c002006-03-15 22:19:46 +0000788 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
789 }
790 } else {
Chris Lattner32206f52006-03-18 01:44:44 +0000791 assert(0 && "Cannot bitconvert vectors yet!");
792#if 0
Chris Lattner4024c002006-03-15 22:19:46 +0000793 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
794 const PackedType *DstTy = cast<PackedType>(I.getType());
795
796 unsigned SrcNumElements = SrcTy->getNumElements();
797 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
798 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
799
800 unsigned DstNumElements = DstTy->getNumElements();
801 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
802 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
803
804 // If the input and output type are legal, convert this to a bit convert of
805 // the SrcTVT/DstTVT types.
806 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
807 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
808 assert(N.getValueType() == SrcTVT);
809 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
810 } else {
811 // Otherwise, convert this directly into a store/load.
812 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
813 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
814 // Create the stack frame object.
815 uint64_t ByteSize = TD.getTypeSize(SrcTy);
816 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
817 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
818 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
819 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
820
821 // Emit a store to the stack slot.
822 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
823 N, FIPtr, DAG.getSrcValue(NULL));
824 // Result is a load from the stack slot.
825 SDOperand Val =
826 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
827 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000828 }
Chris Lattner32206f52006-03-18 01:44:44 +0000829#endif
Chris Lattner7a60d912005-01-07 07:47:53 +0000830 }
831}
832
Chris Lattner32206f52006-03-18 01:44:44 +0000833void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
834 const PackedType *Ty = cast<PackedType>(I.getType());
835 unsigned NumElements = Ty->getNumElements();
836 MVT::ValueType PVT = TLI.getValueType(Ty->getElementType());
837 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
838
839 SDOperand InVec = getValue(I.getOperand(0));
840 SDOperand InVal = getValue(I.getOperand(1));
841 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
842 getValue(I.getOperand(2)));
843
844 // Immediately scalarize packed types containing only one element, so that
845 // the Legalize pass does not have to deal with them. Similarly, if the
846 // abstract vector is going to turn into one that the target natively
847 // supports, generate that type now so that Legalize doesn't have to deal
848 // with that either. These steps ensure that Legalize only has to handle
849 // vector types in its Expand case.
850 if (NumElements == 1) {
851 setValue(&I, InVal); // Must be insertelt(Vec, InVal, 0) -> InVal
852 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
853 TLI.isOperationLegal(ISD::INSERT_VECTOR_ELT, TVT)) {
854 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, TVT, InVec, InVal, InIdx));
855 } else {
856 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
857 SDOperand Typ = DAG.getValueType(PVT);
858 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
859 InVec, InVal, InIdx, Num, Typ));
860 }
861}
862
863
Chris Lattner7a60d912005-01-07 07:47:53 +0000864void SelectionDAGLowering::visitGetElementPtr(User &I) {
865 SDOperand N = getValue(I.getOperand(0));
866 const Type *Ty = I.getOperand(0)->getType();
867 const Type *UIntPtrTy = TD.getIntPtrType();
868
869 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
870 OI != E; ++OI) {
871 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000872 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000873 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
874 if (Field) {
875 // N = N + Offset
876 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
877 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000878 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000879 }
880 Ty = StTy->getElementType(Field);
881 } else {
882 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000883
Chris Lattner43535a12005-11-09 04:45:33 +0000884 // If this is a constant subscript, handle it quickly.
885 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
886 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000887
Chris Lattner43535a12005-11-09 04:45:33 +0000888 uint64_t Offs;
889 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
890 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
891 else
892 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
893 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
894 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000895 }
Chris Lattner43535a12005-11-09 04:45:33 +0000896
897 // N = N + Idx * ElementSize;
898 uint64_t ElementSize = TD.getTypeSize(Ty);
899 SDOperand IdxN = getValue(Idx);
900
901 // If the index is smaller or larger than intptr_t, truncate or extend
902 // it.
903 if (IdxN.getValueType() < N.getValueType()) {
904 if (Idx->getType()->isSigned())
905 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
906 else
907 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
908 } else if (IdxN.getValueType() > N.getValueType())
909 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
910
911 // If this is a multiply by a power of two, turn it into a shl
912 // immediately. This is a very common case.
913 if (isPowerOf2_64(ElementSize)) {
914 unsigned Amt = Log2_64(ElementSize);
915 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000916 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000917 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
918 continue;
919 }
920
921 SDOperand Scale = getIntPtrConstant(ElementSize);
922 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
923 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000924 }
925 }
926 setValue(&I, N);
927}
928
929void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
930 // If this is a fixed sized alloca in the entry block of the function,
931 // allocate it statically on the stack.
932 if (FuncInfo.StaticAllocaMap.count(&I))
933 return; // getValue will auto-populate this.
934
935 const Type *Ty = I.getAllocatedType();
936 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000937 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
938 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000939
940 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000941 MVT::ValueType IntPtr = TLI.getPointerTy();
942 if (IntPtr < AllocSize.getValueType())
943 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
944 else if (IntPtr > AllocSize.getValueType())
945 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000946
Chris Lattnereccb73d2005-01-22 23:04:37 +0000947 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000948 getIntPtrConstant(TySize));
949
950 // Handle alignment. If the requested alignment is less than or equal to the
951 // stack alignment, ignore it and round the size of the allocation up to the
952 // stack alignment size. If the size is greater than the stack alignment, we
953 // note this in the DYNAMIC_STACKALLOC node.
954 unsigned StackAlign =
955 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
956 if (Align <= StackAlign) {
957 Align = 0;
958 // Add SA-1 to the size.
959 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
960 getIntPtrConstant(StackAlign-1));
961 // Mask out the low bits for alignment purposes.
962 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
963 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
964 }
965
Chris Lattner96c262e2005-05-14 07:29:57 +0000966 std::vector<MVT::ValueType> VTs;
967 VTs.push_back(AllocSize.getValueType());
968 VTs.push_back(MVT::Other);
969 std::vector<SDOperand> Ops;
970 Ops.push_back(getRoot());
971 Ops.push_back(AllocSize);
972 Ops.push_back(getIntPtrConstant(Align));
973 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000974 DAG.setRoot(setValue(&I, DSA).getValue(1));
975
976 // Inform the Frame Information that we have just allocated a variable-sized
977 // object.
978 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
979}
980
Chris Lattner7a60d912005-01-07 07:47:53 +0000981void SelectionDAGLowering::visitLoad(LoadInst &I) {
982 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000983
Chris Lattner4d9651c2005-01-17 22:19:26 +0000984 SDOperand Root;
985 if (I.isVolatile())
986 Root = getRoot();
987 else {
988 // Do not serialize non-volatile loads against each other.
989 Root = DAG.getRoot();
990 }
Chris Lattner4024c002006-03-15 22:19:46 +0000991
992 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
993 Root, I.isVolatile()));
994}
995
996SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
997 SDOperand SrcValue, SDOperand Root,
998 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000999 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001000 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001001 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001002 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001003 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001004 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001005 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001006
Chris Lattner4024c002006-03-15 22:19:46 +00001007 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001008 DAG.setRoot(L.getValue(1));
1009 else
1010 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001011
1012 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001013}
1014
1015
1016void SelectionDAGLowering::visitStore(StoreInst &I) {
1017 Value *SrcV = I.getOperand(0);
1018 SDOperand Src = getValue(SrcV);
1019 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001020 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001021 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001022}
1023
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001024/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1025/// we want to emit this as a call to a named external function, return the name
1026/// otherwise lower it and return null.
1027const char *
1028SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1029 switch (Intrinsic) {
1030 case Intrinsic::vastart: visitVAStart(I); return 0;
1031 case Intrinsic::vaend: visitVAEnd(I); return 0;
1032 case Intrinsic::vacopy: visitVACopy(I); return 0;
1033 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1034 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1035 case Intrinsic::setjmp:
1036 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1037 break;
1038 case Intrinsic::longjmp:
1039 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1040 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001041 case Intrinsic::memcpy_i32:
1042 case Intrinsic::memcpy_i64:
1043 visitMemIntrinsic(I, ISD::MEMCPY);
1044 return 0;
1045 case Intrinsic::memset_i32:
1046 case Intrinsic::memset_i64:
1047 visitMemIntrinsic(I, ISD::MEMSET);
1048 return 0;
1049 case Intrinsic::memmove_i32:
1050 case Intrinsic::memmove_i64:
1051 visitMemIntrinsic(I, ISD::MEMMOVE);
1052 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001053
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001054 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001055 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001056 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001057 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001058
Jim Laskey5995d012006-02-11 01:01:30 +00001059 // Input Chain
1060 Ops.push_back(getRoot());
1061
1062 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001063 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001064
1065 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001066 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001067
Jim Laskeyacb6e342006-03-13 13:07:37 +00001068 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001069 assert(DD && "Not a debug information descriptor");
1070 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1071 assert(CompileUnit && "Not a compile unit");
1072 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1073 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1074
1075 if (Ops.size() == 5) // Found filename/workingdir.
1076 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001077 }
1078
Chris Lattner8782b782005-12-03 18:50:48 +00001079 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001080 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001081 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001082 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001083 if (I.getType() != Type::VoidTy)
1084 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1085 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001086 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001087 if (I.getType() != Type::VoidTy)
1088 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1089 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001090 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001091 if (I.getType() != Type::VoidTy)
1092 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1093 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001094
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001095 case Intrinsic::isunordered_f32:
1096 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001097 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1098 getValue(I.getOperand(2)), ISD::SETUO));
1099 return 0;
1100
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001101 case Intrinsic::sqrt_f32:
1102 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001103 setValue(&I, DAG.getNode(ISD::FSQRT,
1104 getValue(I.getOperand(1)).getValueType(),
1105 getValue(I.getOperand(1))));
1106 return 0;
1107 case Intrinsic::pcmarker: {
1108 SDOperand Tmp = getValue(I.getOperand(1));
1109 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1110 return 0;
1111 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001112 case Intrinsic::readcyclecounter: {
1113 std::vector<MVT::ValueType> VTs;
1114 VTs.push_back(MVT::i64);
1115 VTs.push_back(MVT::Other);
1116 std::vector<SDOperand> Ops;
1117 Ops.push_back(getRoot());
1118 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1119 setValue(&I, Tmp);
1120 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001121 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001122 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001123 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001124 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001125 case Intrinsic::bswap_i64:
1126 setValue(&I, DAG.getNode(ISD::BSWAP,
1127 getValue(I.getOperand(1)).getValueType(),
1128 getValue(I.getOperand(1))));
1129 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001130 case Intrinsic::cttz_i8:
1131 case Intrinsic::cttz_i16:
1132 case Intrinsic::cttz_i32:
1133 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001134 setValue(&I, DAG.getNode(ISD::CTTZ,
1135 getValue(I.getOperand(1)).getValueType(),
1136 getValue(I.getOperand(1))));
1137 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001138 case Intrinsic::ctlz_i8:
1139 case Intrinsic::ctlz_i16:
1140 case Intrinsic::ctlz_i32:
1141 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001142 setValue(&I, DAG.getNode(ISD::CTLZ,
1143 getValue(I.getOperand(1)).getValueType(),
1144 getValue(I.getOperand(1))));
1145 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001146 case Intrinsic::ctpop_i8:
1147 case Intrinsic::ctpop_i16:
1148 case Intrinsic::ctpop_i32:
1149 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001150 setValue(&I, DAG.getNode(ISD::CTPOP,
1151 getValue(I.getOperand(1)).getValueType(),
1152 getValue(I.getOperand(1))));
1153 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001154 case Intrinsic::stacksave: {
1155 std::vector<MVT::ValueType> VTs;
1156 VTs.push_back(TLI.getPointerTy());
1157 VTs.push_back(MVT::Other);
1158 std::vector<SDOperand> Ops;
1159 Ops.push_back(getRoot());
1160 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1161 setValue(&I, Tmp);
1162 DAG.setRoot(Tmp.getValue(1));
1163 return 0;
1164 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001165 case Intrinsic::stackrestore: {
1166 SDOperand Tmp = getValue(I.getOperand(1));
1167 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001168 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001169 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001170 case Intrinsic::prefetch:
1171 // FIXME: Currently discarding prefetches.
1172 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001173 default:
1174 std::cerr << I;
1175 assert(0 && "This intrinsic is not implemented yet!");
1176 return 0;
1177 }
1178}
1179
1180
Chris Lattner7a60d912005-01-07 07:47:53 +00001181void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001182 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001183 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001184 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001185 if (unsigned IID = F->getIntrinsicID()) {
1186 RenameFn = visitIntrinsicCall(I, IID);
1187 if (!RenameFn)
1188 return;
1189 } else { // Not an LLVM intrinsic.
1190 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001191 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1192 if (I.getNumOperands() == 3 && // Basic sanity checks.
1193 I.getOperand(1)->getType()->isFloatingPoint() &&
1194 I.getType() == I.getOperand(1)->getType() &&
1195 I.getType() == I.getOperand(2)->getType()) {
1196 SDOperand LHS = getValue(I.getOperand(1));
1197 SDOperand RHS = getValue(I.getOperand(2));
1198 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1199 LHS, RHS));
1200 return;
1201 }
1202 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001203 if (I.getNumOperands() == 2 && // Basic sanity checks.
1204 I.getOperand(1)->getType()->isFloatingPoint() &&
1205 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001206 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001207 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1208 return;
1209 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001210 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001211 if (I.getNumOperands() == 2 && // Basic sanity checks.
1212 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001213 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001214 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001215 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1216 return;
1217 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001218 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001219 if (I.getNumOperands() == 2 && // Basic sanity checks.
1220 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001221 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001222 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001223 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1224 return;
1225 }
1226 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001227 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001228 } else if (isa<InlineAsm>(I.getOperand(0))) {
1229 visitInlineAsm(I);
1230 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001231 }
Misha Brukman835702a2005-04-21 22:36:52 +00001232
Chris Lattner18d2b342005-01-08 22:48:57 +00001233 SDOperand Callee;
1234 if (!RenameFn)
1235 Callee = getValue(I.getOperand(0));
1236 else
1237 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001238 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001239 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001240 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1241 Value *Arg = I.getOperand(i);
1242 SDOperand ArgNode = getValue(Arg);
1243 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1244 }
Misha Brukman835702a2005-04-21 22:36:52 +00001245
Nate Begemanf6565252005-03-26 01:29:23 +00001246 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1247 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001248
Chris Lattner1f45cd72005-01-08 19:26:18 +00001249 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001250 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001251 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001252 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001253 setValue(&I, Result.first);
1254 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001255}
1256
Chris Lattner6f87d182006-02-22 22:37:12 +00001257SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001258 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001259 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1260 Chain = Val.getValue(1);
1261 Flag = Val.getValue(2);
1262
1263 // If the result was expanded, copy from the top part.
1264 if (Regs.size() > 1) {
1265 assert(Regs.size() == 2 &&
1266 "Cannot expand to more than 2 elts yet!");
1267 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1268 Chain = Val.getValue(1);
1269 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001270 if (DAG.getTargetLoweringInfo().isLittleEndian())
1271 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1272 else
1273 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001274 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001275
Chris Lattner6f87d182006-02-22 22:37:12 +00001276 // Otherwise, if the return value was promoted, truncate it to the
1277 // appropriate type.
1278 if (RegVT == ValueVT)
1279 return Val;
1280
1281 if (MVT::isInteger(RegVT))
1282 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1283 else
1284 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1285}
1286
Chris Lattner571d9642006-02-23 19:21:04 +00001287/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1288/// specified value into the registers specified by this object. This uses
1289/// Chain/Flag as the input and updates them for the output Chain/Flag.
1290void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001291 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001292 if (Regs.size() == 1) {
1293 // If there is a single register and the types differ, this must be
1294 // a promotion.
1295 if (RegVT != ValueVT) {
1296 if (MVT::isInteger(RegVT))
1297 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1298 else
1299 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1300 }
1301 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1302 Flag = Chain.getValue(1);
1303 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001304 std::vector<unsigned> R(Regs);
1305 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1306 std::reverse(R.begin(), R.end());
1307
1308 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001309 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1310 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001311 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001312 Flag = Chain.getValue(1);
1313 }
1314 }
1315}
Chris Lattner6f87d182006-02-22 22:37:12 +00001316
Chris Lattner571d9642006-02-23 19:21:04 +00001317/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1318/// operand list. This adds the code marker and includes the number of
1319/// values added into it.
1320void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001321 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001322 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1323 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1324 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1325}
Chris Lattner6f87d182006-02-22 22:37:12 +00001326
1327/// isAllocatableRegister - If the specified register is safe to allocate,
1328/// i.e. it isn't a stack pointer or some other special register, return the
1329/// register class for the register. Otherwise, return null.
1330static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001331isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1332 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1333 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1334 E = MRI->regclass_end(); RCI != E; ++RCI) {
1335 const TargetRegisterClass *RC = *RCI;
1336 // If none of the the value types for this register class are valid, we
1337 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1338 bool isLegal = false;
1339 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1340 I != E; ++I) {
1341 if (TLI.isTypeLegal(*I)) {
1342 isLegal = true;
1343 break;
1344 }
1345 }
1346
1347 if (!isLegal) continue;
1348
Chris Lattner6f87d182006-02-22 22:37:12 +00001349 // NOTE: This isn't ideal. In particular, this might allocate the
1350 // frame pointer in functions that need it (due to them not being taken
1351 // out of allocation, because a variable sized allocation hasn't been seen
1352 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001353 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1354 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001355 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001356 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001357 }
1358 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001359}
1360
1361RegsForValue SelectionDAGLowering::
1362GetRegistersForValue(const std::string &ConstrCode,
1363 MVT::ValueType VT, bool isOutReg, bool isInReg,
1364 std::set<unsigned> &OutputRegs,
1365 std::set<unsigned> &InputRegs) {
1366 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1367 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1368 std::vector<unsigned> Regs;
1369
1370 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1371 MVT::ValueType RegVT;
1372 MVT::ValueType ValueVT = VT;
1373
1374 if (PhysReg.first) {
1375 if (VT == MVT::Other)
1376 ValueVT = *PhysReg.second->vt_begin();
1377 RegVT = VT;
1378
1379 // This is a explicit reference to a physical register.
1380 Regs.push_back(PhysReg.first);
1381
1382 // If this is an expanded reference, add the rest of the regs to Regs.
1383 if (NumRegs != 1) {
1384 RegVT = *PhysReg.second->vt_begin();
1385 TargetRegisterClass::iterator I = PhysReg.second->begin();
1386 TargetRegisterClass::iterator E = PhysReg.second->end();
1387 for (; *I != PhysReg.first; ++I)
1388 assert(I != E && "Didn't find reg!");
1389
1390 // Already added the first reg.
1391 --NumRegs; ++I;
1392 for (; NumRegs; --NumRegs, ++I) {
1393 assert(I != E && "Ran out of registers to allocate!");
1394 Regs.push_back(*I);
1395 }
1396 }
1397 return RegsForValue(Regs, RegVT, ValueVT);
1398 }
1399
1400 // This is a reference to a register class. Allocate NumRegs consecutive,
1401 // available, registers from the class.
1402 std::vector<unsigned> RegClassRegs =
1403 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1404
1405 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1406 MachineFunction &MF = *CurMBB->getParent();
1407 unsigned NumAllocated = 0;
1408 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1409 unsigned Reg = RegClassRegs[i];
1410 // See if this register is available.
1411 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1412 (isInReg && InputRegs.count(Reg))) { // Already used.
1413 // Make sure we find consecutive registers.
1414 NumAllocated = 0;
1415 continue;
1416 }
1417
1418 // Check to see if this register is allocatable (i.e. don't give out the
1419 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001420 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001421 if (!RC) {
1422 // Make sure we find consecutive registers.
1423 NumAllocated = 0;
1424 continue;
1425 }
1426
1427 // Okay, this register is good, we can use it.
1428 ++NumAllocated;
1429
1430 // If we allocated enough consecutive
1431 if (NumAllocated == NumRegs) {
1432 unsigned RegStart = (i-NumAllocated)+1;
1433 unsigned RegEnd = i+1;
1434 // Mark all of the allocated registers used.
1435 for (unsigned i = RegStart; i != RegEnd; ++i) {
1436 unsigned Reg = RegClassRegs[i];
1437 Regs.push_back(Reg);
1438 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1439 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1440 }
1441
1442 return RegsForValue(Regs, *RC->vt_begin(), VT);
1443 }
1444 }
1445
1446 // Otherwise, we couldn't allocate enough registers for this.
1447 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001448}
1449
Chris Lattner6f87d182006-02-22 22:37:12 +00001450
Chris Lattner476e67b2006-01-26 22:24:51 +00001451/// visitInlineAsm - Handle a call to an InlineAsm object.
1452///
1453void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1454 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1455
1456 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1457 MVT::Other);
1458
1459 // Note, we treat inline asms both with and without side-effects as the same.
1460 // If an inline asm doesn't have side effects and doesn't access memory, we
1461 // could not choose to not chain it.
1462 bool hasSideEffects = IA->hasSideEffects();
1463
Chris Lattner3a5ed552006-02-01 01:28:23 +00001464 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001465 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001466
1467 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1468 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1469 /// if it is a def of that register.
1470 std::vector<SDOperand> AsmNodeOperands;
1471 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1472 AsmNodeOperands.push_back(AsmStr);
1473
1474 SDOperand Chain = getRoot();
1475 SDOperand Flag;
1476
Chris Lattner1558fc62006-02-01 18:59:47 +00001477 // We fully assign registers here at isel time. This is not optimal, but
1478 // should work. For register classes that correspond to LLVM classes, we
1479 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1480 // over the constraints, collecting fixed registers that we know we can't use.
1481 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001482 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001483 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1484 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1485 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001486
Chris Lattner7ad77df2006-02-22 00:56:39 +00001487 MVT::ValueType OpVT;
1488
1489 // Compute the value type for each operand and add it to ConstraintVTs.
1490 switch (Constraints[i].Type) {
1491 case InlineAsm::isOutput:
1492 if (!Constraints[i].isIndirectOutput) {
1493 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1494 OpVT = TLI.getValueType(I.getType());
1495 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001496 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001497 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1498 OpNum++; // Consumes a call operand.
1499 }
1500 break;
1501 case InlineAsm::isInput:
1502 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1503 OpNum++; // Consumes a call operand.
1504 break;
1505 case InlineAsm::isClobber:
1506 OpVT = MVT::Other;
1507 break;
1508 }
1509
1510 ConstraintVTs.push_back(OpVT);
1511
Chris Lattner6f87d182006-02-22 22:37:12 +00001512 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1513 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001514
Chris Lattner6f87d182006-02-22 22:37:12 +00001515 // Build a list of regs that this operand uses. This always has a single
1516 // element for promoted/expanded operands.
1517 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1518 false, false,
1519 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001520
1521 switch (Constraints[i].Type) {
1522 case InlineAsm::isOutput:
1523 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001524 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001525 // If this is an early-clobber output, it cannot be assigned to the same
1526 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001527 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001528 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001529 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001530 case InlineAsm::isInput:
1531 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001532 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001533 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001534 case InlineAsm::isClobber:
1535 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001536 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1537 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001538 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001539 }
1540 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001541
Chris Lattner5c79f982006-02-21 23:12:12 +00001542 // Loop over all of the inputs, copying the operand values into the
1543 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001544 RegsForValue RetValRegs;
1545 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001546 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001547
Chris Lattner2e56e892006-01-31 02:03:41 +00001548 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001549 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1550 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001551
Chris Lattner3a5ed552006-02-01 01:28:23 +00001552 switch (Constraints[i].Type) {
1553 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001554 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1555 if (ConstraintCode.size() == 1) // not a physreg name.
1556 CTy = TLI.getConstraintType(ConstraintCode[0]);
1557
1558 if (CTy == TargetLowering::C_Memory) {
1559 // Memory output.
1560 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1561
1562 // Check that the operand (the address to store to) isn't a float.
1563 if (!MVT::isInteger(InOperandVal.getValueType()))
1564 assert(0 && "MATCH FAIL!");
1565
1566 if (!Constraints[i].isIndirectOutput)
1567 assert(0 && "MATCH FAIL!");
1568
1569 OpNum++; // Consumes a call operand.
1570
1571 // Extend/truncate to the right pointer type if needed.
1572 MVT::ValueType PtrType = TLI.getPointerTy();
1573 if (InOperandVal.getValueType() < PtrType)
1574 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1575 else if (InOperandVal.getValueType() > PtrType)
1576 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1577
1578 // Add information to the INLINEASM node to know about this output.
1579 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1580 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1581 AsmNodeOperands.push_back(InOperandVal);
1582 break;
1583 }
1584
1585 // Otherwise, this is a register output.
1586 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1587
Chris Lattner6f87d182006-02-22 22:37:12 +00001588 // If this is an early-clobber output, or if there is an input
1589 // constraint that matches this, we need to reserve the input register
1590 // so no other inputs allocate to it.
1591 bool UsesInputRegister = false;
1592 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1593 UsesInputRegister = true;
1594
1595 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001596 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001597 RegsForValue Regs =
1598 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1599 true, UsesInputRegister,
1600 OutputRegs, InputRegs);
1601 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001602
Chris Lattner3a5ed552006-02-01 01:28:23 +00001603 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001604 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001605 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001606 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001607 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001608 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001609 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1610 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001611 OpNum++; // Consumes a call operand.
1612 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001613
1614 // Add information to the INLINEASM node to know that this register is
1615 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001616 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001617 break;
1618 }
1619 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001620 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001621 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001622
Chris Lattner7f5880b2006-02-02 00:25:23 +00001623 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1624 // If this is required to match an output register we have already set,
1625 // just use its register.
1626 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001627
Chris Lattner571d9642006-02-23 19:21:04 +00001628 // Scan until we find the definition we already emitted of this operand.
1629 // When we find it, create a RegsForValue operand.
1630 unsigned CurOp = 2; // The first operand.
1631 for (; OperandNo; --OperandNo) {
1632 // Advance to the next operand.
1633 unsigned NumOps =
1634 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1635 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1636 "Skipped past definitions?");
1637 CurOp += (NumOps>>3)+1;
1638 }
1639
1640 unsigned NumOps =
1641 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1642 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1643 "Skipped past definitions?");
1644
1645 // Add NumOps>>3 registers to MatchedRegs.
1646 RegsForValue MatchedRegs;
1647 MatchedRegs.ValueVT = InOperandVal.getValueType();
1648 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1649 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1650 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1651 MatchedRegs.Regs.push_back(Reg);
1652 }
1653
1654 // Use the produced MatchedRegs object to
1655 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1656 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001657 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001658 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001659
1660 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1661 if (ConstraintCode.size() == 1) // not a physreg name.
1662 CTy = TLI.getConstraintType(ConstraintCode[0]);
1663
1664 if (CTy == TargetLowering::C_Other) {
1665 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1666 assert(0 && "MATCH FAIL!");
1667
1668 // Add information to the INLINEASM node to know about this input.
1669 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1670 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1671 AsmNodeOperands.push_back(InOperandVal);
1672 break;
1673 } else if (CTy == TargetLowering::C_Memory) {
1674 // Memory input.
1675
1676 // Check that the operand isn't a float.
1677 if (!MVT::isInteger(InOperandVal.getValueType()))
1678 assert(0 && "MATCH FAIL!");
1679
1680 // Extend/truncate to the right pointer type if needed.
1681 MVT::ValueType PtrType = TLI.getPointerTy();
1682 if (InOperandVal.getValueType() < PtrType)
1683 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1684 else if (InOperandVal.getValueType() > PtrType)
1685 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1686
1687 // Add information to the INLINEASM node to know about this input.
1688 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1689 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1690 AsmNodeOperands.push_back(InOperandVal);
1691 break;
1692 }
1693
1694 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1695
1696 // Copy the input into the appropriate registers.
1697 RegsForValue InRegs =
1698 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1699 false, true, OutputRegs, InputRegs);
1700 // FIXME: should be match fail.
1701 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1702
1703 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1704
1705 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001706 break;
1707 }
Chris Lattner571d9642006-02-23 19:21:04 +00001708 case InlineAsm::isClobber: {
1709 RegsForValue ClobberedRegs =
1710 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1711 OutputRegs, InputRegs);
1712 // Add the clobbered value to the operand list, so that the register
1713 // allocator is aware that the physreg got clobbered.
1714 if (!ClobberedRegs.Regs.empty())
1715 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001716 break;
1717 }
Chris Lattner571d9642006-02-23 19:21:04 +00001718 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001719 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001720
1721 // Finish up input operands.
1722 AsmNodeOperands[0] = Chain;
1723 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1724
1725 std::vector<MVT::ValueType> VTs;
1726 VTs.push_back(MVT::Other);
1727 VTs.push_back(MVT::Flag);
1728 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1729 Flag = Chain.getValue(1);
1730
Chris Lattner2e56e892006-01-31 02:03:41 +00001731 // If this asm returns a register value, copy the result from that register
1732 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001733 if (!RetValRegs.Regs.empty())
1734 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001735
Chris Lattner2e56e892006-01-31 02:03:41 +00001736 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1737
1738 // Process indirect outputs, first output all of the flagged copies out of
1739 // physregs.
1740 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001741 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001742 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001743 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1744 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001745 }
1746
1747 // Emit the non-flagged stores from the physregs.
1748 std::vector<SDOperand> OutChains;
1749 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1750 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1751 StoresToEmit[i].first,
1752 getValue(StoresToEmit[i].second),
1753 DAG.getSrcValue(StoresToEmit[i].second)));
1754 if (!OutChains.empty())
1755 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001756 DAG.setRoot(Chain);
1757}
1758
1759
Chris Lattner7a60d912005-01-07 07:47:53 +00001760void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1761 SDOperand Src = getValue(I.getOperand(0));
1762
1763 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001764
1765 if (IntPtr < Src.getValueType())
1766 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1767 else if (IntPtr > Src.getValueType())
1768 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001769
1770 // Scale the source by the type size.
1771 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1772 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1773 Src, getIntPtrConstant(ElementSize));
1774
1775 std::vector<std::pair<SDOperand, const Type*> > Args;
1776 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001777
1778 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001779 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001780 DAG.getExternalSymbol("malloc", IntPtr),
1781 Args, DAG);
1782 setValue(&I, Result.first); // Pointers always fit in registers
1783 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001784}
1785
1786void SelectionDAGLowering::visitFree(FreeInst &I) {
1787 std::vector<std::pair<SDOperand, const Type*> > Args;
1788 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1789 TLI.getTargetData().getIntPtrType()));
1790 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001791 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001792 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001793 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1794 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001795}
1796
Chris Lattner13d7c252005-08-26 20:54:47 +00001797// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1798// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1799// instructions are special in various ways, which require special support to
1800// insert. The specified MachineInstr is created but not inserted into any
1801// basic blocks, and the scheduler passes ownership of it to this method.
1802MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1803 MachineBasicBlock *MBB) {
1804 std::cerr << "If a target marks an instruction with "
1805 "'usesCustomDAGSchedInserter', it must implement "
1806 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1807 abort();
1808 return 0;
1809}
1810
Chris Lattner58cfd792005-01-09 00:00:49 +00001811void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001812 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1813 getValue(I.getOperand(1)),
1814 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001815}
1816
1817void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001818 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1819 getValue(I.getOperand(0)),
1820 DAG.getSrcValue(I.getOperand(0)));
1821 setValue(&I, V);
1822 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001823}
1824
1825void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001826 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1827 getValue(I.getOperand(1)),
1828 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001829}
1830
1831void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001832 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1833 getValue(I.getOperand(1)),
1834 getValue(I.getOperand(2)),
1835 DAG.getSrcValue(I.getOperand(1)),
1836 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001837}
1838
Chris Lattner58cfd792005-01-09 00:00:49 +00001839// It is always conservatively correct for llvm.returnaddress and
1840// llvm.frameaddress to return 0.
1841std::pair<SDOperand, SDOperand>
1842TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1843 unsigned Depth, SelectionDAG &DAG) {
1844 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001845}
1846
Chris Lattner29dcc712005-05-14 05:50:48 +00001847SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001848 assert(0 && "LowerOperation not implemented for this target!");
1849 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001850 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001851}
1852
Nate Begeman595ec732006-01-28 03:14:31 +00001853SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1854 SelectionDAG &DAG) {
1855 assert(0 && "CustomPromoteOperation not implemented for this target!");
1856 abort();
1857 return SDOperand();
1858}
1859
Chris Lattner58cfd792005-01-09 00:00:49 +00001860void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1861 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1862 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001863 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001864 setValue(&I, Result.first);
1865 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001866}
1867
Evan Cheng6781b6e2006-02-15 21:59:04 +00001868/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001869/// operand.
1870static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001871 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001872 MVT::ValueType CurVT = VT;
1873 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1874 uint64_t Val = C->getValue() & 255;
1875 unsigned Shift = 8;
1876 while (CurVT != MVT::i8) {
1877 Val = (Val << Shift) | Val;
1878 Shift <<= 1;
1879 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001880 }
1881 return DAG.getConstant(Val, VT);
1882 } else {
1883 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1884 unsigned Shift = 8;
1885 while (CurVT != MVT::i8) {
1886 Value =
1887 DAG.getNode(ISD::OR, VT,
1888 DAG.getNode(ISD::SHL, VT, Value,
1889 DAG.getConstant(Shift, MVT::i8)), Value);
1890 Shift <<= 1;
1891 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001892 }
1893
1894 return Value;
1895 }
1896}
1897
Evan Cheng6781b6e2006-02-15 21:59:04 +00001898/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1899/// used when a memcpy is turned into a memset when the source is a constant
1900/// string ptr.
1901static SDOperand getMemsetStringVal(MVT::ValueType VT,
1902 SelectionDAG &DAG, TargetLowering &TLI,
1903 std::string &Str, unsigned Offset) {
1904 MVT::ValueType CurVT = VT;
1905 uint64_t Val = 0;
1906 unsigned MSB = getSizeInBits(VT) / 8;
1907 if (TLI.isLittleEndian())
1908 Offset = Offset + MSB - 1;
1909 for (unsigned i = 0; i != MSB; ++i) {
1910 Val = (Val << 8) | Str[Offset];
1911 Offset += TLI.isLittleEndian() ? -1 : 1;
1912 }
1913 return DAG.getConstant(Val, VT);
1914}
1915
Evan Cheng81fcea82006-02-14 08:22:34 +00001916/// getMemBasePlusOffset - Returns base and offset node for the
1917static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1918 SelectionDAG &DAG, TargetLowering &TLI) {
1919 MVT::ValueType VT = Base.getValueType();
1920 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1921}
1922
Evan Chengdb2a7a72006-02-14 20:12:38 +00001923/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001924/// to replace the memset / memcpy is below the threshold. It also returns the
1925/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001926static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1927 unsigned Limit, uint64_t Size,
1928 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001929 MVT::ValueType VT;
1930
1931 if (TLI.allowsUnalignedMemoryAccesses()) {
1932 VT = MVT::i64;
1933 } else {
1934 switch (Align & 7) {
1935 case 0:
1936 VT = MVT::i64;
1937 break;
1938 case 4:
1939 VT = MVT::i32;
1940 break;
1941 case 2:
1942 VT = MVT::i16;
1943 break;
1944 default:
1945 VT = MVT::i8;
1946 break;
1947 }
1948 }
1949
Evan Chengd5026102006-02-14 09:11:59 +00001950 MVT::ValueType LVT = MVT::i64;
1951 while (!TLI.isTypeLegal(LVT))
1952 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1953 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001954
Evan Chengd5026102006-02-14 09:11:59 +00001955 if (VT > LVT)
1956 VT = LVT;
1957
Evan Cheng04514992006-02-14 23:05:54 +00001958 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001959 while (Size != 0) {
1960 unsigned VTSize = getSizeInBits(VT) / 8;
1961 while (VTSize > Size) {
1962 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001963 VTSize >>= 1;
1964 }
Evan Chengd5026102006-02-14 09:11:59 +00001965 assert(MVT::isInteger(VT));
1966
1967 if (++NumMemOps > Limit)
1968 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001969 MemOps.push_back(VT);
1970 Size -= VTSize;
1971 }
Evan Chengd5026102006-02-14 09:11:59 +00001972
1973 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001974}
1975
Chris Lattner875def92005-01-11 05:56:49 +00001976void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001977 SDOperand Op1 = getValue(I.getOperand(1));
1978 SDOperand Op2 = getValue(I.getOperand(2));
1979 SDOperand Op3 = getValue(I.getOperand(3));
1980 SDOperand Op4 = getValue(I.getOperand(4));
1981 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1982 if (Align == 0) Align = 1;
1983
1984 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1985 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001986
1987 // Expand memset / memcpy to a series of load / store ops
1988 // if the size operand falls below a certain threshold.
1989 std::vector<SDOperand> OutChains;
1990 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001991 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001992 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001993 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1994 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001995 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001996 unsigned Offset = 0;
1997 for (unsigned i = 0; i < NumMemOps; i++) {
1998 MVT::ValueType VT = MemOps[i];
1999 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002000 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002001 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2002 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002003 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2004 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002005 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002006 Offset += VTSize;
2007 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002008 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002009 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002010 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002011 case ISD::MEMCPY: {
2012 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2013 Size->getValue(), Align, TLI)) {
2014 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002015 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002016 GlobalAddressSDNode *G = NULL;
2017 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002018 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002019
2020 if (Op2.getOpcode() == ISD::GlobalAddress)
2021 G = cast<GlobalAddressSDNode>(Op2);
2022 else if (Op2.getOpcode() == ISD::ADD &&
2023 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2024 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2025 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002026 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002027 }
2028 if (G) {
2029 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002030 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002031 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002032 if (!Str.empty()) {
2033 CopyFromStr = true;
2034 SrcOff += SrcDelta;
2035 }
2036 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002037 }
2038
Evan Chenge2038bd2006-02-15 01:54:51 +00002039 for (unsigned i = 0; i < NumMemOps; i++) {
2040 MVT::ValueType VT = MemOps[i];
2041 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002042 SDOperand Value, Chain, Store;
2043
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002044 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002045 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2046 Chain = getRoot();
2047 Store =
2048 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2049 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2050 DAG.getSrcValue(I.getOperand(1), DstOff));
2051 } else {
2052 Value = DAG.getLoad(VT, getRoot(),
2053 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2054 DAG.getSrcValue(I.getOperand(2), SrcOff));
2055 Chain = Value.getValue(1);
2056 Store =
2057 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2058 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2059 DAG.getSrcValue(I.getOperand(1), DstOff));
2060 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002061 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002062 SrcOff += VTSize;
2063 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002064 }
2065 }
2066 break;
2067 }
2068 }
2069
2070 if (!OutChains.empty()) {
2071 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2072 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002073 }
2074 }
2075
Chris Lattner875def92005-01-11 05:56:49 +00002076 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002077 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002078 Ops.push_back(Op1);
2079 Ops.push_back(Op2);
2080 Ops.push_back(Op3);
2081 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002082 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002083}
2084
Chris Lattner875def92005-01-11 05:56:49 +00002085//===----------------------------------------------------------------------===//
2086// SelectionDAGISel code
2087//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002088
2089unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2090 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2091}
2092
Chris Lattnerc9950c12005-08-17 06:37:43 +00002093void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002094 // FIXME: we only modify the CFG to split critical edges. This
2095 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002096}
Chris Lattner7a60d912005-01-07 07:47:53 +00002097
Chris Lattner35397782005-12-05 07:10:48 +00002098
2099/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2100/// casting to the type of GEPI.
2101static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2102 Value *Ptr, Value *PtrOffset) {
2103 if (V) return V; // Already computed.
2104
2105 BasicBlock::iterator InsertPt;
2106 if (BB == GEPI->getParent()) {
2107 // If insert into the GEP's block, insert right after the GEP.
2108 InsertPt = GEPI;
2109 ++InsertPt;
2110 } else {
2111 // Otherwise, insert at the top of BB, after any PHI nodes
2112 InsertPt = BB->begin();
2113 while (isa<PHINode>(InsertPt)) ++InsertPt;
2114 }
2115
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002116 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2117 // BB so that there is only one value live across basic blocks (the cast
2118 // operand).
2119 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2120 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2121 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2122
Chris Lattner35397782005-12-05 07:10:48 +00002123 // Add the offset, cast it to the right type.
2124 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2125 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2126 return V = Ptr;
2127}
2128
2129
2130/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2131/// selection, we want to be a bit careful about some things. In particular, if
2132/// we have a GEP instruction that is used in a different block than it is
2133/// defined, the addressing expression of the GEP cannot be folded into loads or
2134/// stores that use it. In this case, decompose the GEP and move constant
2135/// indices into blocks that use it.
2136static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2137 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002138 // If this GEP is only used inside the block it is defined in, there is no
2139 // need to rewrite it.
2140 bool isUsedOutsideDefBB = false;
2141 BasicBlock *DefBB = GEPI->getParent();
2142 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2143 UI != E; ++UI) {
2144 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2145 isUsedOutsideDefBB = true;
2146 break;
2147 }
2148 }
2149 if (!isUsedOutsideDefBB) return;
2150
2151 // If this GEP has no non-zero constant indices, there is nothing we can do,
2152 // ignore it.
2153 bool hasConstantIndex = false;
2154 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2155 E = GEPI->op_end(); OI != E; ++OI) {
2156 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2157 if (CI->getRawValue()) {
2158 hasConstantIndex = true;
2159 break;
2160 }
2161 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002162 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2163 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002164
2165 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2166 // constant offset (which we now know is non-zero) and deal with it later.
2167 uint64_t ConstantOffset = 0;
2168 const Type *UIntPtrTy = TD.getIntPtrType();
2169 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2170 const Type *Ty = GEPI->getOperand(0)->getType();
2171
2172 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2173 E = GEPI->op_end(); OI != E; ++OI) {
2174 Value *Idx = *OI;
2175 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2176 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2177 if (Field)
2178 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2179 Ty = StTy->getElementType(Field);
2180 } else {
2181 Ty = cast<SequentialType>(Ty)->getElementType();
2182
2183 // Handle constant subscripts.
2184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2185 if (CI->getRawValue() == 0) continue;
2186
2187 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2188 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2189 else
2190 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2191 continue;
2192 }
2193
2194 // Ptr = Ptr + Idx * ElementSize;
2195
2196 // Cast Idx to UIntPtrTy if needed.
2197 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2198
2199 uint64_t ElementSize = TD.getTypeSize(Ty);
2200 // Mask off bits that should not be set.
2201 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2202 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2203
2204 // Multiply by the element size and add to the base.
2205 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2206 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2207 }
2208 }
2209
2210 // Make sure that the offset fits in uintptr_t.
2211 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2212 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2213
2214 // Okay, we have now emitted all of the variable index parts to the BB that
2215 // the GEP is defined in. Loop over all of the using instructions, inserting
2216 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002217 // instruction to use the newly computed value, making GEPI dead. When the
2218 // user is a load or store instruction address, we emit the add into the user
2219 // block, otherwise we use a canonical version right next to the gep (these
2220 // won't be foldable as addresses, so we might as well share the computation).
2221
Chris Lattner35397782005-12-05 07:10:48 +00002222 std::map<BasicBlock*,Value*> InsertedExprs;
2223 while (!GEPI->use_empty()) {
2224 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002225
2226 // If this use is not foldable into the addressing mode, use a version
2227 // emitted in the GEP block.
2228 Value *NewVal;
2229 if (!isa<LoadInst>(User) &&
2230 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2231 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2232 Ptr, PtrOffset);
2233 } else {
2234 // Otherwise, insert the code in the User's block so it can be folded into
2235 // any users in that block.
2236 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002237 User->getParent(), GEPI,
2238 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002239 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002240 User->replaceUsesOfWith(GEPI, NewVal);
2241 }
Chris Lattner35397782005-12-05 07:10:48 +00002242
2243 // Finally, the GEP is dead, remove it.
2244 GEPI->eraseFromParent();
2245}
2246
Chris Lattner7a60d912005-01-07 07:47:53 +00002247bool SelectionDAGISel::runOnFunction(Function &Fn) {
2248 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2249 RegMap = MF.getSSARegMap();
2250 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2251
Chris Lattner35397782005-12-05 07:10:48 +00002252 // First, split all critical edges for PHI nodes with incoming values that are
2253 // constants, this way the load of the constant into a vreg will not be placed
2254 // into MBBs that are used some other way.
2255 //
2256 // In this pass we also look for GEP instructions that are used across basic
2257 // blocks and rewrites them to improve basic-block-at-a-time selection.
2258 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002259 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2260 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002261 BasicBlock::iterator BBI;
2262 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002263 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2264 if (isa<Constant>(PN->getIncomingValue(i)))
2265 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002266
2267 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2268 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2269 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002270 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002271
Chris Lattner7a60d912005-01-07 07:47:53 +00002272 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2273
2274 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2275 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002276
Chris Lattner7a60d912005-01-07 07:47:53 +00002277 return true;
2278}
2279
2280
Chris Lattner718b5c22005-01-13 17:59:43 +00002281SDOperand SelectionDAGISel::
2282CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002283 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002284 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002285 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002286 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002287
2288 // If this type is not legal, we must make sure to not create an invalid
2289 // register use.
2290 MVT::ValueType SrcVT = Op.getValueType();
2291 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2292 SelectionDAG &DAG = SDL.DAG;
2293 if (SrcVT == DestVT) {
2294 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2295 } else if (SrcVT < DestVT) {
2296 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002297 if (MVT::isFloatingPoint(SrcVT))
2298 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2299 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002300 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002301 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2302 } else {
2303 // The src value is expanded into multiple registers.
2304 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2305 Op, DAG.getConstant(0, MVT::i32));
2306 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2307 Op, DAG.getConstant(1, MVT::i32));
2308 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2309 return DAG.getCopyToReg(Op, Reg+1, Hi);
2310 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002311}
2312
Chris Lattner16f64df2005-01-17 17:15:02 +00002313void SelectionDAGISel::
2314LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2315 std::vector<SDOperand> &UnorderedChains) {
2316 // If this is the entry block, emit arguments.
2317 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002318 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002319 SDOperand OldRoot = SDL.DAG.getRoot();
2320 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002321
Chris Lattner6871b232005-10-30 19:42:35 +00002322 unsigned a = 0;
2323 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2324 AI != E; ++AI, ++a)
2325 if (!AI->use_empty()) {
2326 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002327
Chris Lattner6871b232005-10-30 19:42:35 +00002328 // If this argument is live outside of the entry block, insert a copy from
2329 // whereever we got it to the vreg that other BB's will reference it as.
2330 if (FuncInfo.ValueMap.count(AI)) {
2331 SDOperand Copy =
2332 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2333 UnorderedChains.push_back(Copy);
2334 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002335 }
Chris Lattner6871b232005-10-30 19:42:35 +00002336
2337 // Next, if the function has live ins that need to be copied into vregs,
2338 // emit the copies now, into the top of the block.
2339 MachineFunction &MF = SDL.DAG.getMachineFunction();
2340 if (MF.livein_begin() != MF.livein_end()) {
2341 SSARegMap *RegMap = MF.getSSARegMap();
2342 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2343 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2344 E = MF.livein_end(); LI != E; ++LI)
2345 if (LI->second)
2346 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2347 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002348 }
Chris Lattner6871b232005-10-30 19:42:35 +00002349
2350 // Finally, if the target has anything special to do, allow it to do so.
2351 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002352}
2353
2354
Chris Lattner7a60d912005-01-07 07:47:53 +00002355void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2356 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2357 FunctionLoweringInfo &FuncInfo) {
2358 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002359
2360 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002361
Chris Lattner6871b232005-10-30 19:42:35 +00002362 // Lower any arguments needed in this block if this is the entry block.
2363 if (LLVMBB == &LLVMBB->getParent()->front())
2364 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002365
2366 BB = FuncInfo.MBBMap[LLVMBB];
2367 SDL.setCurrentBasicBlock(BB);
2368
2369 // Lower all of the non-terminator instructions.
2370 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2371 I != E; ++I)
2372 SDL.visit(*I);
2373
2374 // Ensure that all instructions which are used outside of their defining
2375 // blocks are available as virtual registers.
2376 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002377 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002378 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002379 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002380 UnorderedChains.push_back(
2381 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002382 }
2383
2384 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2385 // ensure constants are generated when needed. Remember the virtual registers
2386 // that need to be added to the Machine PHI nodes as input. We cannot just
2387 // directly add them, because expansion might result in multiple MBB's for one
2388 // BB. As such, the start of the BB might correspond to a different MBB than
2389 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002390 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002391
2392 // Emit constants only once even if used by multiple PHI nodes.
2393 std::map<Constant*, unsigned> ConstantsOut;
2394
2395 // Check successor nodes PHI nodes that expect a constant to be available from
2396 // this block.
2397 TerminatorInst *TI = LLVMBB->getTerminator();
2398 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2399 BasicBlock *SuccBB = TI->getSuccessor(succ);
2400 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2401 PHINode *PN;
2402
2403 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2404 // nodes and Machine PHI nodes, but the incoming operands have not been
2405 // emitted yet.
2406 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002407 (PN = dyn_cast<PHINode>(I)); ++I)
2408 if (!PN->use_empty()) {
2409 unsigned Reg;
2410 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2411 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2412 unsigned &RegOut = ConstantsOut[C];
2413 if (RegOut == 0) {
2414 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002415 UnorderedChains.push_back(
2416 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002417 }
2418 Reg = RegOut;
2419 } else {
2420 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002421 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002422 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002423 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2424 "Didn't codegen value into a register!??");
2425 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002426 UnorderedChains.push_back(
2427 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002428 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002429 }
Misha Brukman835702a2005-04-21 22:36:52 +00002430
Chris Lattner8ea875f2005-01-07 21:34:19 +00002431 // Remember that this register needs to added to the machine PHI node as
2432 // the input for this MBB.
2433 unsigned NumElements =
2434 TLI.getNumElements(TLI.getValueType(PN->getType()));
2435 for (unsigned i = 0, e = NumElements; i != e; ++i)
2436 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002437 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002438 }
2439 ConstantsOut.clear();
2440
Chris Lattner718b5c22005-01-13 17:59:43 +00002441 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002442 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002443 SDOperand Root = SDL.getRoot();
2444 if (Root.getOpcode() != ISD::EntryToken) {
2445 unsigned i = 0, e = UnorderedChains.size();
2446 for (; i != e; ++i) {
2447 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2448 if (UnorderedChains[i].Val->getOperand(0) == Root)
2449 break; // Don't add the root if we already indirectly depend on it.
2450 }
2451
2452 if (i == e)
2453 UnorderedChains.push_back(Root);
2454 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002455 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2456 }
2457
Chris Lattner7a60d912005-01-07 07:47:53 +00002458 // Lower the terminator after the copies are emitted.
2459 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002460
2461 // Make sure the root of the DAG is up-to-date.
2462 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002463}
2464
2465void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2466 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002467 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002468 CurDAG = &DAG;
2469 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2470
2471 // First step, lower LLVM code to some DAG. This DAG may use operations and
2472 // types that are not supported by the target.
2473 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2474
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002475 // Run the DAG combiner in pre-legalize mode.
2476 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002477
Chris Lattner7a60d912005-01-07 07:47:53 +00002478 DEBUG(std::cerr << "Lowered selection DAG:\n");
2479 DEBUG(DAG.dump());
2480
2481 // Second step, hack on the DAG until it only uses operations and types that
2482 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002483 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002484
2485 DEBUG(std::cerr << "Legalized selection DAG:\n");
2486 DEBUG(DAG.dump());
2487
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002488 // Run the DAG combiner in post-legalize mode.
2489 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002490
Evan Cheng739a6a42006-01-21 02:32:06 +00002491 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002492
Chris Lattner5ca31d92005-03-30 01:10:47 +00002493 // Third, instruction select all of the operations to machine code, adding the
2494 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002495 InstructionSelectBasicBlock(DAG);
2496
Chris Lattner7a60d912005-01-07 07:47:53 +00002497 DEBUG(std::cerr << "Selected machine code:\n");
2498 DEBUG(BB->dump());
2499
Chris Lattner5ca31d92005-03-30 01:10:47 +00002500 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002501 // PHI nodes in successors.
2502 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2503 MachineInstr *PHI = PHINodesToUpdate[i].first;
2504 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2505 "This is not a machine PHI node that we are updating!");
2506 PHI->addRegOperand(PHINodesToUpdate[i].second);
2507 PHI->addMachineBasicBlockOperand(BB);
2508 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002509
2510 // Finally, add the CFG edges from the last selected MBB to the successor
2511 // MBBs.
2512 TerminatorInst *TI = LLVMBB->getTerminator();
2513 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2514 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2515 BB->addSuccessor(Succ0MBB);
2516 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002517}
Evan Cheng739a6a42006-01-21 02:32:06 +00002518
2519//===----------------------------------------------------------------------===//
2520/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2521/// target node in the graph.
2522void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2523 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002524 ScheduleDAG *SL = NULL;
2525
2526 switch (ISHeuristic) {
2527 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002528 case defaultScheduling:
2529 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2530 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2531 else /* TargetLowering::SchedulingForRegPressure */
2532 SL = createBURRListDAGScheduler(DAG, BB);
2533 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002534 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002535 SL = createBFS_DAGScheduler(DAG, BB);
2536 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002537 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002538 SL = createSimpleDAGScheduler(false, DAG, BB);
2539 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002540 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002541 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002542 break;
Evan Cheng31272342006-01-23 08:26:10 +00002543 case listSchedulingBURR:
2544 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002545 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002546 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002547 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002548 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002549 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002550 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002551 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002552}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002553
Chris Lattner543832d2006-03-08 04:25:59 +00002554HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2555 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002556}
2557
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002558/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2559/// by tblgen. Others should not call it.
2560void SelectionDAGISel::
2561SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2562 std::vector<SDOperand> InOps;
2563 std::swap(InOps, Ops);
2564
2565 Ops.push_back(InOps[0]); // input chain.
2566 Ops.push_back(InOps[1]); // input asm string.
2567
2568 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2569 unsigned i = 2, e = InOps.size();
2570 if (InOps[e-1].getValueType() == MVT::Flag)
2571 --e; // Don't process a flag operand if it is here.
2572
2573 while (i != e) {
2574 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2575 if ((Flags & 7) != 4 /*MEM*/) {
2576 // Just skip over this operand, copying the operands verbatim.
2577 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2578 i += (Flags >> 3) + 1;
2579 } else {
2580 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2581 // Otherwise, this is a memory operand. Ask the target to select it.
2582 std::vector<SDOperand> SelOps;
2583 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2584 std::cerr << "Could not match memory address. Inline asm failure!\n";
2585 exit(1);
2586 }
2587
2588 // Add this to the output node.
2589 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2590 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2591 i += 2;
2592 }
2593 }
2594
2595 // Add the flag input back if present.
2596 if (e != InOps.size())
2597 Ops.push_back(InOps.back());
2598}