blob: f1afeb93e3d525cfab1c1d5ad00f39a2f9fd0b94 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-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 Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-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 Lattnerfa577022005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-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 Lattner495a0b52005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000043#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattnerda8abb02005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Chenga9c20912006-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 Lattner7944d9d2005-01-12 03:41:21 +000055#else
Evan Chenga9c20912006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Chris Lattner20a49212006-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 Cheng4ef10862006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000076 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-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 Cheng3f239522006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner03fc53c2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Cheng4ef10862006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner864635a2006-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 Lattner9f6637d2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-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 Lattner9f6637d2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-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 Lattner9f6637d2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000141 };
142}
Evan Cheng4ef10862006-01-23 07:01:07 +0000143
Chris Lattner1c08c712005-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 Lattnerf26bc8e2005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +0000173
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 unsigned CreateRegForValue(const Value *V) {
175 MVT::ValueType VT = TLI.getValueType(V->getType());
176 // The common case is that we will only create one register for this
177 // value. If we have that case, create and return the virtual register.
178 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000179 if (NV == 1) {
180 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000181 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000182 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000183
Chris Lattner1c08c712005-01-07 07:47:53 +0000184 // If this value is represented with multiple target registers, make sure
Chris Lattner864635a2006-02-22 22:37:12 +0000185 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner1c08c712005-01-07 07:47:53 +0000186 unsigned NT = VT-1; // Find the type to use.
187 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
188 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000189
Chris Lattner1c08c712005-01-07 07:47:53 +0000190 unsigned R = MakeReg((MVT::ValueType)NT);
191 for (unsigned i = 1; i != NV; ++i)
192 MakeReg((MVT::ValueType)NT);
193 return R;
194 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000195
Chris Lattner1c08c712005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
205/// PHI nodes or outside of the basic block that defines it.
206static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
207 if (isa<PHINode>(I)) return true;
208 BasicBlock *BB = I->getParent();
209 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
210 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216/// entry block, return true.
217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
220 if (cast<Instruction>(*UI)->getParent() != Entry)
221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner1c08c712005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattnerbf209482005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner1c08c712005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
242 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
243 const Type *Ty = AI->getAllocatedType();
244 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000245 unsigned Align =
246 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
247 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000248
249 // If the alignment of the value is smaller than the size of the value,
250 // and if the size of the value is particularly small (<= 8 bytes),
251 // round up to the size of the value for potentially better performance.
252 //
253 // FIXME: This could be made better with a preferred alignment hook in
254 // TargetData. It serves primarily to 8-byte align doubles for X86.
255 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000256 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000257 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000259 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 }
261
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000262 for (; BB != EB; ++BB)
263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000264 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
265 if (!isa<AllocaInst>(I) ||
266 !StaticAllocaMap.count(cast<AllocaInst>(I)))
267 InitializeRegForValue(I);
268
269 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
270 // also creates the initial PHI MachineInstrs, though none of the input
271 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000272 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000273 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
274 MBBMap[BB] = MBB;
275 MF.getBasicBlockList().push_back(MBB);
276
277 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
278 // appropriate.
279 PHINode *PN;
280 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000281 (PN = dyn_cast<PHINode>(I)); ++I)
282 if (!PN->use_empty()) {
283 unsigned NumElements =
284 TLI.getNumElements(TLI.getValueType(PN->getType()));
285 unsigned PHIReg = ValueMap[PN];
286 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
287 for (unsigned i = 0; i != NumElements; ++i)
288 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
289 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000290 }
291}
292
293
294
295//===----------------------------------------------------------------------===//
296/// SelectionDAGLowering - This is the common target-independent lowering
297/// implementation that is parameterized by a TargetLowering object.
298/// Also, targets can overload any lowering method.
299///
300namespace llvm {
301class SelectionDAGLowering {
302 MachineBasicBlock *CurMBB;
303
304 std::map<const Value*, SDOperand> NodeMap;
305
Chris Lattnerd3948112005-01-17 22:19:26 +0000306 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
307 /// them up and then emit token factor nodes when possible. This allows us to
308 /// get simple disambiguation between loads without worrying about alias
309 /// analysis.
310 std::vector<SDOperand> PendingLoads;
311
Chris Lattner1c08c712005-01-07 07:47:53 +0000312public:
313 // TLI - This is information that describes the available target features we
314 // need for lowering. This indicates when operations are unavailable,
315 // implemented with a libcall, etc.
316 TargetLowering &TLI;
317 SelectionDAG &DAG;
318 const TargetData &TD;
319
320 /// FuncInfo - Information about the function as a whole.
321 ///
322 FunctionLoweringInfo &FuncInfo;
323
324 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000325 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000326 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
327 FuncInfo(funcinfo) {
328 }
329
Chris Lattnera651cf62005-01-17 19:43:36 +0000330 /// getRoot - Return the current virtual root of the Selection DAG.
331 ///
332 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000333 if (PendingLoads.empty())
334 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000335
Chris Lattnerd3948112005-01-17 22:19:26 +0000336 if (PendingLoads.size() == 1) {
337 SDOperand Root = PendingLoads[0];
338 DAG.setRoot(Root);
339 PendingLoads.clear();
340 return Root;
341 }
342
343 // Otherwise, we have to make a token factor node.
344 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
345 PendingLoads.clear();
346 DAG.setRoot(Root);
347 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000348 }
349
Chris Lattner1c08c712005-01-07 07:47:53 +0000350 void visit(Instruction &I) { visit(I.getOpcode(), I); }
351
352 void visit(unsigned Opcode, User &I) {
353 switch (Opcode) {
354 default: assert(0 && "Unknown instruction type encountered!");
355 abort();
356 // Build the switch statement using the Instruction.def file.
357#define HANDLE_INST(NUM, OPCODE, CLASS) \
358 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
359#include "llvm/Instruction.def"
360 }
361 }
362
363 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
364
365
366 SDOperand getIntPtrConstant(uint64_t Val) {
367 return DAG.getConstant(Val, TLI.getPointerTy());
368 }
369
370 SDOperand getValue(const Value *V) {
371 SDOperand &N = NodeMap[V];
372 if (N.Val) return N;
373
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000374 const Type *VTy = V->getType();
375 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000376 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
378 visit(CE->getOpcode(), *CE);
379 assert(N.Val && "visit didn't populate the ValueMap!");
380 return N;
381 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
382 return N = DAG.getGlobalAddress(GV, VT);
383 } else if (isa<ConstantPointerNull>(C)) {
384 return N = DAG.getConstant(0, TLI.getPointerTy());
385 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000386 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000387 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
388 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000389 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
390 unsigned NumElements = PTy->getNumElements();
391 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
392 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
393
394 // Now that we know the number and type of the elements, push a
395 // Constant or ConstantFP node onto the ops list for each element of
396 // the packed constant.
397 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000398 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
399 if (MVT::isFloatingPoint(PVT)) {
400 for (unsigned i = 0; i != NumElements; ++i) {
401 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
402 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
403 }
404 } else {
405 for (unsigned i = 0; i != NumElements; ++i) {
406 const ConstantIntegral *El =
407 cast<ConstantIntegral>(CP->getOperand(i));
408 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
409 }
410 }
411 } else {
412 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
413 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000414 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000415 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000416 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000417 Op = DAG.getConstant(0, PVT);
418 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000419 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000420
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000421 // Handle the case where we have a 1-element vector, in which
422 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000423 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000424 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000425 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
426 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
427 } else {
428 // If the packed type isn't legal, then create a ConstantVec node with
429 // generic Vector type instead.
Evan Cheng860771d2006-03-01 01:09:54 +0000430 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
431 SDOperand Typ = DAG.getValueType(PVT);
432 Ops.insert(Ops.begin(), Typ);
433 Ops.insert(Ops.begin(), Num);
434 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemancc827e62005-12-07 19:48:11 +0000435 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000436 } else {
437 // Canonicalize all constant ints to be unsigned.
438 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
439 }
440
441 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
442 std::map<const AllocaInst*, int>::iterator SI =
443 FuncInfo.StaticAllocaMap.find(AI);
444 if (SI != FuncInfo.StaticAllocaMap.end())
445 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
446 }
447
448 std::map<const Value*, unsigned>::const_iterator VMI =
449 FuncInfo.ValueMap.find(V);
450 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000451
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000452 unsigned InReg = VMI->second;
453
454 // If this type is not legal, make it so now.
455 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
456
457 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
458 if (DestVT < VT) {
459 // Source must be expanded. This input value is actually coming from the
460 // register pair VMI->second and VMI->second+1.
461 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
462 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
463 } else {
464 if (DestVT > VT) { // Promotion case
465 if (MVT::isFloatingPoint(VT))
466 N = DAG.getNode(ISD::FP_ROUND, VT, N);
467 else
468 N = DAG.getNode(ISD::TRUNCATE, VT, N);
469 }
470 }
471
472 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 }
474
475 const SDOperand &setValue(const Value *V, SDOperand NewN) {
476 SDOperand &N = NodeMap[V];
477 assert(N.Val == 0 && "Already set a value for this node!");
478 return N = NewN;
479 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000480
Chris Lattner864635a2006-02-22 22:37:12 +0000481 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
482 MVT::ValueType VT,
483 bool OutReg, bool InReg,
484 std::set<unsigned> &OutputRegs,
485 std::set<unsigned> &InputRegs);
486
Chris Lattner1c08c712005-01-07 07:47:53 +0000487 // Terminator instructions.
488 void visitRet(ReturnInst &I);
489 void visitBr(BranchInst &I);
490 void visitUnreachable(UnreachableInst &I) { /* noop */ }
491
492 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000493 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000494 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000495 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
496 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
497 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
498
499 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000500 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000501 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000502 void visitAdd(User &I) {
503 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000504 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000505 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000506 void visitMul(User &I) {
507 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000508 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000509 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000510 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000511 visitBinary(I,
512 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
513 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000514 }
515 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000516 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000517 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000518 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000519 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
520 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
521 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000522 void visitShl(User &I) { visitShift(I, ISD::SHL); }
523 void visitShr(User &I) {
524 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000525 }
526
527 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
528 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
529 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
530 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
531 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
532 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
533 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
534
535 void visitGetElementPtr(User &I);
536 void visitCast(User &I);
537 void visitSelect(User &I);
538 //
539
540 void visitMalloc(MallocInst &I);
541 void visitFree(FreeInst &I);
542 void visitAlloca(AllocaInst &I);
543 void visitLoad(LoadInst &I);
544 void visitStore(StoreInst &I);
545 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
546 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000547 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000548 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000549
Chris Lattner1c08c712005-01-07 07:47:53 +0000550 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000551 void visitVAArg(VAArgInst &I);
552 void visitVAEnd(CallInst &I);
553 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000554 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000555
Chris Lattner7041ee32005-01-11 05:56:49 +0000556 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557
558 void visitUserOp1(Instruction &I) {
559 assert(0 && "UserOp1 should not exist at instruction selection time!");
560 abort();
561 }
562 void visitUserOp2(Instruction &I) {
563 assert(0 && "UserOp2 should not exist at instruction selection time!");
564 abort();
565 }
566};
567} // end namespace llvm
568
569void SelectionDAGLowering::visitRet(ReturnInst &I) {
570 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000571 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000572 return;
573 }
Nate Begemanee625572006-01-27 21:09:22 +0000574 std::vector<SDOperand> NewValues;
575 NewValues.push_back(getRoot());
576 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
577 SDOperand RetOp = getValue(I.getOperand(i));
578
579 // If this is an integer return value, we need to promote it ourselves to
580 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
581 // than sign/zero.
582 if (MVT::isInteger(RetOp.getValueType()) &&
583 RetOp.getValueType() < MVT::i64) {
584 MVT::ValueType TmpVT;
585 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
586 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
587 else
588 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000589
Nate Begemanee625572006-01-27 21:09:22 +0000590 if (I.getOperand(i)->getType()->isSigned())
591 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
592 else
593 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
594 }
595 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000596 }
Nate Begemanee625572006-01-27 21:09:22 +0000597 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000598}
599
600void SelectionDAGLowering::visitBr(BranchInst &I) {
601 // Update machine-CFG edges.
602 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000603
604 // Figure out which block is immediately after the current one.
605 MachineBasicBlock *NextBlock = 0;
606 MachineFunction::iterator BBI = CurMBB;
607 if (++BBI != CurMBB->getParent()->end())
608 NextBlock = BBI;
609
610 if (I.isUnconditional()) {
611 // If this is not a fall-through branch, emit the branch.
612 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000613 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000614 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000615 } else {
616 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000617
618 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000619 if (Succ1MBB == NextBlock) {
620 // If the condition is false, fall through. This means we should branch
621 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000622 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000623 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000624 } else if (Succ0MBB == NextBlock) {
625 // If the condition is true, fall through. This means we should branch if
626 // the condition is false to Succ #1. Invert the condition first.
627 SDOperand True = DAG.getConstant(1, Cond.getValueType());
628 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000629 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000630 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000631 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000632 std::vector<SDOperand> Ops;
633 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000634 // If the false case is the current basic block, then this is a self
635 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
636 // adds an extra instruction in the loop. Instead, invert the
637 // condition and emit "Loop: ... br!cond Loop; br Out.
638 if (CurMBB == Succ1MBB) {
639 std::swap(Succ0MBB, Succ1MBB);
640 SDOperand True = DAG.getConstant(1, Cond.getValueType());
641 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
642 }
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000643 Ops.push_back(Cond);
644 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
645 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
646 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000647 }
648 }
649}
650
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000651void SelectionDAGLowering::visitSub(User &I) {
652 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000653 if (I.getType()->isFloatingPoint()) {
654 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
655 if (CFP->isExactlyValue(-0.0)) {
656 SDOperand Op2 = getValue(I.getOperand(1));
657 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
658 return;
659 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000660 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000661 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000662}
663
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000664void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
665 unsigned VecOp) {
666 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000667 SDOperand Op1 = getValue(I.getOperand(0));
668 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000669
Chris Lattnerb67eb912005-11-19 18:40:42 +0000670 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000671 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
672 } else if (Ty->isFloatingPoint()) {
673 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
674 } else {
675 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000676 unsigned NumElements = PTy->getNumElements();
677 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000678 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000679
680 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000681 // the Legalize pass does not have to deal with them. Similarly, if the
682 // abstract vector is going to turn into one that the target natively
683 // supports, generate that type now so that Legalize doesn't have to deal
684 // with that either. These steps ensure that Legalize only has to handle
685 // vector types in its Expand case.
686 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000687 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000688 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Cheng860771d2006-03-01 01:09:54 +0000689 } else if (TVT != MVT::Other &&
690 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000691 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000692 } else {
693 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
694 SDOperand Typ = DAG.getValueType(PVT);
Evan Cheng860771d2006-03-01 01:09:54 +0000695 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000696 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000697 }
Nate Begemane21ea612005-11-18 07:42:56 +0000698}
Chris Lattner2c49f272005-01-19 22:31:21 +0000699
Nate Begemane21ea612005-11-18 07:42:56 +0000700void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
701 SDOperand Op1 = getValue(I.getOperand(0));
702 SDOperand Op2 = getValue(I.getOperand(1));
703
704 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
705
Chris Lattner1c08c712005-01-07 07:47:53 +0000706 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
707}
708
709void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
710 ISD::CondCode UnsignedOpcode) {
711 SDOperand Op1 = getValue(I.getOperand(0));
712 SDOperand Op2 = getValue(I.getOperand(1));
713 ISD::CondCode Opcode = SignedOpcode;
714 if (I.getOperand(0)->getType()->isUnsigned())
715 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000716 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000717}
718
719void SelectionDAGLowering::visitSelect(User &I) {
720 SDOperand Cond = getValue(I.getOperand(0));
721 SDOperand TrueVal = getValue(I.getOperand(1));
722 SDOperand FalseVal = getValue(I.getOperand(2));
723 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
724 TrueVal, FalseVal));
725}
726
727void SelectionDAGLowering::visitCast(User &I) {
728 SDOperand N = getValue(I.getOperand(0));
729 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
730 MVT::ValueType DestTy = TLI.getValueType(I.getType());
731
732 if (N.getValueType() == DestTy) {
733 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000734 } else if (DestTy == MVT::i1) {
735 // Cast to bool is a comparison against zero, not truncation to zero.
736 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
737 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000738 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000739 } else if (isInteger(SrcTy)) {
740 if (isInteger(DestTy)) { // Int -> Int cast
741 if (DestTy < SrcTy) // Truncating cast?
742 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
743 else if (I.getOperand(0)->getType()->isSigned())
744 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
745 else
746 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
747 } else { // Int -> FP cast
748 if (I.getOperand(0)->getType()->isSigned())
749 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
750 else
751 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
752 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000753 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000754 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
755 if (isFloatingPoint(DestTy)) { // FP -> FP cast
756 if (DestTy < SrcTy) // Rounding cast?
757 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
758 else
759 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
760 } else { // FP -> Int cast.
761 if (I.getType()->isSigned())
762 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
763 else
764 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
765 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000766 }
767}
768
769void SelectionDAGLowering::visitGetElementPtr(User &I) {
770 SDOperand N = getValue(I.getOperand(0));
771 const Type *Ty = I.getOperand(0)->getType();
772 const Type *UIntPtrTy = TD.getIntPtrType();
773
774 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
775 OI != E; ++OI) {
776 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000777 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000778 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
779 if (Field) {
780 // N = N + Offset
781 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
782 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000783 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000784 }
785 Ty = StTy->getElementType(Field);
786 } else {
787 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000788
Chris Lattner7c0104b2005-11-09 04:45:33 +0000789 // If this is a constant subscript, handle it quickly.
790 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
791 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000792
Chris Lattner7c0104b2005-11-09 04:45:33 +0000793 uint64_t Offs;
794 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
795 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
796 else
797 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
798 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
799 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000800 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000801
802 // N = N + Idx * ElementSize;
803 uint64_t ElementSize = TD.getTypeSize(Ty);
804 SDOperand IdxN = getValue(Idx);
805
806 // If the index is smaller or larger than intptr_t, truncate or extend
807 // it.
808 if (IdxN.getValueType() < N.getValueType()) {
809 if (Idx->getType()->isSigned())
810 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
811 else
812 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
813 } else if (IdxN.getValueType() > N.getValueType())
814 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
815
816 // If this is a multiply by a power of two, turn it into a shl
817 // immediately. This is a very common case.
818 if (isPowerOf2_64(ElementSize)) {
819 unsigned Amt = Log2_64(ElementSize);
820 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000821 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000822 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
823 continue;
824 }
825
826 SDOperand Scale = getIntPtrConstant(ElementSize);
827 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
828 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000829 }
830 }
831 setValue(&I, N);
832}
833
834void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
835 // If this is a fixed sized alloca in the entry block of the function,
836 // allocate it statically on the stack.
837 if (FuncInfo.StaticAllocaMap.count(&I))
838 return; // getValue will auto-populate this.
839
840 const Type *Ty = I.getAllocatedType();
841 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000842 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
843 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000844
845 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000846 MVT::ValueType IntPtr = TLI.getPointerTy();
847 if (IntPtr < AllocSize.getValueType())
848 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
849 else if (IntPtr > AllocSize.getValueType())
850 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000851
Chris Lattner68cd65e2005-01-22 23:04:37 +0000852 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000853 getIntPtrConstant(TySize));
854
855 // Handle alignment. If the requested alignment is less than or equal to the
856 // stack alignment, ignore it and round the size of the allocation up to the
857 // stack alignment size. If the size is greater than the stack alignment, we
858 // note this in the DYNAMIC_STACKALLOC node.
859 unsigned StackAlign =
860 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
861 if (Align <= StackAlign) {
862 Align = 0;
863 // Add SA-1 to the size.
864 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
865 getIntPtrConstant(StackAlign-1));
866 // Mask out the low bits for alignment purposes.
867 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
868 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
869 }
870
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000871 std::vector<MVT::ValueType> VTs;
872 VTs.push_back(AllocSize.getValueType());
873 VTs.push_back(MVT::Other);
874 std::vector<SDOperand> Ops;
875 Ops.push_back(getRoot());
876 Ops.push_back(AllocSize);
877 Ops.push_back(getIntPtrConstant(Align));
878 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000879 DAG.setRoot(setValue(&I, DSA).getValue(1));
880
881 // Inform the Frame Information that we have just allocated a variable-sized
882 // object.
883 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
884}
885
Chris Lattner1c08c712005-01-07 07:47:53 +0000886void SelectionDAGLowering::visitLoad(LoadInst &I) {
887 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000888
Chris Lattnerd3948112005-01-17 22:19:26 +0000889 SDOperand Root;
890 if (I.isVolatile())
891 Root = getRoot();
892 else {
893 // Do not serialize non-volatile loads against each other.
894 Root = DAG.getRoot();
895 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000896
897 const Type *Ty = I.getType();
898 SDOperand L;
899
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000900 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000901 unsigned NumElements = PTy->getNumElements();
902 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000903 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000904
905 // Immediately scalarize packed types containing only one element, so that
906 // the Legalize pass does not have to deal with them.
907 if (NumElements == 1) {
908 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Evan Cheng860771d2006-03-01 01:09:54 +0000909 } else if (TVT != MVT::Other &&
910 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000911 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000912 } else {
913 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
914 DAG.getSrcValue(I.getOperand(0)));
915 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000916 } else {
917 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
918 DAG.getSrcValue(I.getOperand(0)));
919 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000920 setValue(&I, L);
921
922 if (I.isVolatile())
923 DAG.setRoot(L.getValue(1));
924 else
925 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000926}
927
928
929void SelectionDAGLowering::visitStore(StoreInst &I) {
930 Value *SrcV = I.getOperand(0);
931 SDOperand Src = getValue(SrcV);
932 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000933 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000934 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000935}
936
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000937/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
938/// we want to emit this as a call to a named external function, return the name
939/// otherwise lower it and return null.
940const char *
941SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
942 switch (Intrinsic) {
943 case Intrinsic::vastart: visitVAStart(I); return 0;
944 case Intrinsic::vaend: visitVAEnd(I); return 0;
945 case Intrinsic::vacopy: visitVACopy(I); return 0;
946 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
947 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
948 case Intrinsic::setjmp:
949 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
950 break;
951 case Intrinsic::longjmp:
952 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
953 break;
Chris Lattner03dd4652006-03-03 00:00:25 +0000954 case Intrinsic::memcpy_i32:
955 case Intrinsic::memcpy_i64:
956 visitMemIntrinsic(I, ISD::MEMCPY);
957 return 0;
958 case Intrinsic::memset_i32:
959 case Intrinsic::memset_i64:
960 visitMemIntrinsic(I, ISD::MEMSET);
961 return 0;
962 case Intrinsic::memmove_i32:
963 case Intrinsic::memmove_i64:
964 visitMemIntrinsic(I, ISD::MEMMOVE);
965 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000966
Chris Lattner86cb6432005-12-13 17:40:33 +0000967 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +0000968 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
969 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
970 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +0000971
Jim Laskeyce72b172006-02-11 01:01:30 +0000972 // Input Chain
973 Ops.push_back(getRoot());
974
975 // line number
976 Ops.push_back(getValue(I.getOperand(2)));
977
978 // column
979 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner36ce6912005-11-29 06:21:05 +0000980
Jim Laskeyd96185a2006-02-13 12:50:39 +0000981 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskeyce72b172006-02-11 01:01:30 +0000982 assert(DD && "Not a debug information descriptor");
983 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
984 assert(CompileUnit && "Not a compile unit");
985 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
986 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
987
988 if (Ops.size() == 5) // Found filename/workingdir.
989 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +0000990 }
991
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000992 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000993 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000994 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000995 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000996 if (I.getType() != Type::VoidTy)
997 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
998 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000999 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001000 if (I.getType() != Type::VoidTy)
1001 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1002 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001003 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001004 if (I.getType() != Type::VoidTy)
1005 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1006 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001007
Reid Spencer0b118202006-01-16 21:12:35 +00001008 case Intrinsic::isunordered_f32:
1009 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001010 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1011 getValue(I.getOperand(2)), ISD::SETUO));
1012 return 0;
1013
Reid Spencer0b118202006-01-16 21:12:35 +00001014 case Intrinsic::sqrt_f32:
1015 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001016 setValue(&I, DAG.getNode(ISD::FSQRT,
1017 getValue(I.getOperand(1)).getValueType(),
1018 getValue(I.getOperand(1))));
1019 return 0;
1020 case Intrinsic::pcmarker: {
1021 SDOperand Tmp = getValue(I.getOperand(1));
1022 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1023 return 0;
1024 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001025 case Intrinsic::readcyclecounter: {
1026 std::vector<MVT::ValueType> VTs;
1027 VTs.push_back(MVT::i64);
1028 VTs.push_back(MVT::Other);
1029 std::vector<SDOperand> Ops;
1030 Ops.push_back(getRoot());
1031 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1032 setValue(&I, Tmp);
1033 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001034 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001035 }
Nate Begemand88fc032006-01-14 03:14:10 +00001036 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001037 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001038 case Intrinsic::bswap_i64:
1039 setValue(&I, DAG.getNode(ISD::BSWAP,
1040 getValue(I.getOperand(1)).getValueType(),
1041 getValue(I.getOperand(1))));
1042 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001043 case Intrinsic::cttz_i8:
1044 case Intrinsic::cttz_i16:
1045 case Intrinsic::cttz_i32:
1046 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001047 setValue(&I, DAG.getNode(ISD::CTTZ,
1048 getValue(I.getOperand(1)).getValueType(),
1049 getValue(I.getOperand(1))));
1050 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001051 case Intrinsic::ctlz_i8:
1052 case Intrinsic::ctlz_i16:
1053 case Intrinsic::ctlz_i32:
1054 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001055 setValue(&I, DAG.getNode(ISD::CTLZ,
1056 getValue(I.getOperand(1)).getValueType(),
1057 getValue(I.getOperand(1))));
1058 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001059 case Intrinsic::ctpop_i8:
1060 case Intrinsic::ctpop_i16:
1061 case Intrinsic::ctpop_i32:
1062 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001063 setValue(&I, DAG.getNode(ISD::CTPOP,
1064 getValue(I.getOperand(1)).getValueType(),
1065 getValue(I.getOperand(1))));
1066 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001067 case Intrinsic::stacksave: {
1068 std::vector<MVT::ValueType> VTs;
1069 VTs.push_back(TLI.getPointerTy());
1070 VTs.push_back(MVT::Other);
1071 std::vector<SDOperand> Ops;
1072 Ops.push_back(getRoot());
1073 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1074 setValue(&I, Tmp);
1075 DAG.setRoot(Tmp.getValue(1));
1076 return 0;
1077 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001078 case Intrinsic::stackrestore: {
1079 SDOperand Tmp = getValue(I.getOperand(1));
1080 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001081 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001082 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001083 case Intrinsic::prefetch:
1084 // FIXME: Currently discarding prefetches.
1085 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001086 default:
1087 std::cerr << I;
1088 assert(0 && "This intrinsic is not implemented yet!");
1089 return 0;
1090 }
1091}
1092
1093
Chris Lattner1c08c712005-01-07 07:47:53 +00001094void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001095 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001096 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001097 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001098 if (unsigned IID = F->getIntrinsicID()) {
1099 RenameFn = visitIntrinsicCall(I, IID);
1100 if (!RenameFn)
1101 return;
1102 } else { // Not an LLVM intrinsic.
1103 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001104 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1105 if (I.getNumOperands() == 3 && // Basic sanity checks.
1106 I.getOperand(1)->getType()->isFloatingPoint() &&
1107 I.getType() == I.getOperand(1)->getType() &&
1108 I.getType() == I.getOperand(2)->getType()) {
1109 SDOperand LHS = getValue(I.getOperand(1));
1110 SDOperand RHS = getValue(I.getOperand(2));
1111 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1112 LHS, RHS));
1113 return;
1114 }
1115 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001116 if (I.getNumOperands() == 2 && // Basic sanity checks.
1117 I.getOperand(1)->getType()->isFloatingPoint() &&
1118 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001119 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001120 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1121 return;
1122 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001123 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001124 if (I.getNumOperands() == 2 && // Basic sanity checks.
1125 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001126 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001127 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001128 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1129 return;
1130 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001131 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001132 if (I.getNumOperands() == 2 && // Basic sanity checks.
1133 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001134 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001135 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001136 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1137 return;
1138 }
1139 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001140 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001141 } else if (isa<InlineAsm>(I.getOperand(0))) {
1142 visitInlineAsm(I);
1143 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001144 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001145
Chris Lattner64e14b12005-01-08 22:48:57 +00001146 SDOperand Callee;
1147 if (!RenameFn)
1148 Callee = getValue(I.getOperand(0));
1149 else
1150 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001151 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001152 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001153 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1154 Value *Arg = I.getOperand(i);
1155 SDOperand ArgNode = getValue(Arg);
1156 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1157 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001158
Nate Begeman8e21e712005-03-26 01:29:23 +00001159 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1160 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001161
Chris Lattnercf5734d2005-01-08 19:26:18 +00001162 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001163 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001164 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001165 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001166 setValue(&I, Result.first);
1167 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001168}
1169
Chris Lattner864635a2006-02-22 22:37:12 +00001170SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001171 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001172 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1173 Chain = Val.getValue(1);
1174 Flag = Val.getValue(2);
1175
1176 // If the result was expanded, copy from the top part.
1177 if (Regs.size() > 1) {
1178 assert(Regs.size() == 2 &&
1179 "Cannot expand to more than 2 elts yet!");
1180 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1181 Chain = Val.getValue(1);
1182 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001183 if (DAG.getTargetLoweringInfo().isLittleEndian())
1184 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1185 else
1186 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001187 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001188
Chris Lattner864635a2006-02-22 22:37:12 +00001189 // Otherwise, if the return value was promoted, truncate it to the
1190 // appropriate type.
1191 if (RegVT == ValueVT)
1192 return Val;
1193
1194 if (MVT::isInteger(RegVT))
1195 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1196 else
1197 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1198}
1199
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001200/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1201/// specified value into the registers specified by this object. This uses
1202/// Chain/Flag as the input and updates them for the output Chain/Flag.
1203void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001204 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001205 if (Regs.size() == 1) {
1206 // If there is a single register and the types differ, this must be
1207 // a promotion.
1208 if (RegVT != ValueVT) {
1209 if (MVT::isInteger(RegVT))
1210 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1211 else
1212 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1213 }
1214 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1215 Flag = Chain.getValue(1);
1216 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001217 std::vector<unsigned> R(Regs);
1218 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1219 std::reverse(R.begin(), R.end());
1220
1221 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001222 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1223 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001224 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001225 Flag = Chain.getValue(1);
1226 }
1227 }
1228}
Chris Lattner864635a2006-02-22 22:37:12 +00001229
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001230/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1231/// operand list. This adds the code marker and includes the number of
1232/// values added into it.
1233void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001234 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001235 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1236 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1237 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1238}
Chris Lattner864635a2006-02-22 22:37:12 +00001239
1240/// isAllocatableRegister - If the specified register is safe to allocate,
1241/// i.e. it isn't a stack pointer or some other special register, return the
1242/// register class for the register. Otherwise, return null.
1243static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001244isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1245 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1246 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1247 E = MRI->regclass_end(); RCI != E; ++RCI) {
1248 const TargetRegisterClass *RC = *RCI;
1249 // If none of the the value types for this register class are valid, we
1250 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1251 bool isLegal = false;
1252 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1253 I != E; ++I) {
1254 if (TLI.isTypeLegal(*I)) {
1255 isLegal = true;
1256 break;
1257 }
1258 }
1259
1260 if (!isLegal) continue;
1261
Chris Lattner864635a2006-02-22 22:37:12 +00001262 // NOTE: This isn't ideal. In particular, this might allocate the
1263 // frame pointer in functions that need it (due to them not being taken
1264 // out of allocation, because a variable sized allocation hasn't been seen
1265 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001266 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1267 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner864635a2006-02-22 22:37:12 +00001268 if (*I == Reg)
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001269 return RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001270 }
1271 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001272}
1273
1274RegsForValue SelectionDAGLowering::
1275GetRegistersForValue(const std::string &ConstrCode,
1276 MVT::ValueType VT, bool isOutReg, bool isInReg,
1277 std::set<unsigned> &OutputRegs,
1278 std::set<unsigned> &InputRegs) {
1279 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1280 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1281 std::vector<unsigned> Regs;
1282
1283 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1284 MVT::ValueType RegVT;
1285 MVT::ValueType ValueVT = VT;
1286
1287 if (PhysReg.first) {
1288 if (VT == MVT::Other)
1289 ValueVT = *PhysReg.second->vt_begin();
1290 RegVT = VT;
1291
1292 // This is a explicit reference to a physical register.
1293 Regs.push_back(PhysReg.first);
1294
1295 // If this is an expanded reference, add the rest of the regs to Regs.
1296 if (NumRegs != 1) {
1297 RegVT = *PhysReg.second->vt_begin();
1298 TargetRegisterClass::iterator I = PhysReg.second->begin();
1299 TargetRegisterClass::iterator E = PhysReg.second->end();
1300 for (; *I != PhysReg.first; ++I)
1301 assert(I != E && "Didn't find reg!");
1302
1303 // Already added the first reg.
1304 --NumRegs; ++I;
1305 for (; NumRegs; --NumRegs, ++I) {
1306 assert(I != E && "Ran out of registers to allocate!");
1307 Regs.push_back(*I);
1308 }
1309 }
1310 return RegsForValue(Regs, RegVT, ValueVT);
1311 }
1312
1313 // This is a reference to a register class. Allocate NumRegs consecutive,
1314 // available, registers from the class.
1315 std::vector<unsigned> RegClassRegs =
1316 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1317
1318 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1319 MachineFunction &MF = *CurMBB->getParent();
1320 unsigned NumAllocated = 0;
1321 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1322 unsigned Reg = RegClassRegs[i];
1323 // See if this register is available.
1324 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1325 (isInReg && InputRegs.count(Reg))) { // Already used.
1326 // Make sure we find consecutive registers.
1327 NumAllocated = 0;
1328 continue;
1329 }
1330
1331 // Check to see if this register is allocatable (i.e. don't give out the
1332 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001333 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001334 if (!RC) {
1335 // Make sure we find consecutive registers.
1336 NumAllocated = 0;
1337 continue;
1338 }
1339
1340 // Okay, this register is good, we can use it.
1341 ++NumAllocated;
1342
1343 // If we allocated enough consecutive
1344 if (NumAllocated == NumRegs) {
1345 unsigned RegStart = (i-NumAllocated)+1;
1346 unsigned RegEnd = i+1;
1347 // Mark all of the allocated registers used.
1348 for (unsigned i = RegStart; i != RegEnd; ++i) {
1349 unsigned Reg = RegClassRegs[i];
1350 Regs.push_back(Reg);
1351 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1352 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1353 }
1354
1355 return RegsForValue(Regs, *RC->vt_begin(), VT);
1356 }
1357 }
1358
1359 // Otherwise, we couldn't allocate enough registers for this.
1360 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001361}
1362
Chris Lattner864635a2006-02-22 22:37:12 +00001363
Chris Lattnerce7518c2006-01-26 22:24:51 +00001364/// visitInlineAsm - Handle a call to an InlineAsm object.
1365///
1366void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1367 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1368
1369 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1370 MVT::Other);
1371
1372 // Note, we treat inline asms both with and without side-effects as the same.
1373 // If an inline asm doesn't have side effects and doesn't access memory, we
1374 // could not choose to not chain it.
1375 bool hasSideEffects = IA->hasSideEffects();
1376
Chris Lattner2cc2f662006-02-01 01:28:23 +00001377 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001378 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001379
1380 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1381 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1382 /// if it is a def of that register.
1383 std::vector<SDOperand> AsmNodeOperands;
1384 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1385 AsmNodeOperands.push_back(AsmStr);
1386
1387 SDOperand Chain = getRoot();
1388 SDOperand Flag;
1389
Chris Lattner4e4b5762006-02-01 18:59:47 +00001390 // We fully assign registers here at isel time. This is not optimal, but
1391 // should work. For register classes that correspond to LLVM classes, we
1392 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1393 // over the constraints, collecting fixed registers that we know we can't use.
1394 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001395 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001396 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1397 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1398 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001399
Chris Lattner1efa40f2006-02-22 00:56:39 +00001400 MVT::ValueType OpVT;
1401
1402 // Compute the value type for each operand and add it to ConstraintVTs.
1403 switch (Constraints[i].Type) {
1404 case InlineAsm::isOutput:
1405 if (!Constraints[i].isIndirectOutput) {
1406 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1407 OpVT = TLI.getValueType(I.getType());
1408 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001409 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001410 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1411 OpNum++; // Consumes a call operand.
1412 }
1413 break;
1414 case InlineAsm::isInput:
1415 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1416 OpNum++; // Consumes a call operand.
1417 break;
1418 case InlineAsm::isClobber:
1419 OpVT = MVT::Other;
1420 break;
1421 }
1422
1423 ConstraintVTs.push_back(OpVT);
1424
Chris Lattner864635a2006-02-22 22:37:12 +00001425 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1426 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001427
Chris Lattner864635a2006-02-22 22:37:12 +00001428 // Build a list of regs that this operand uses. This always has a single
1429 // element for promoted/expanded operands.
1430 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1431 false, false,
1432 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001433
1434 switch (Constraints[i].Type) {
1435 case InlineAsm::isOutput:
1436 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001437 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001438 // If this is an early-clobber output, it cannot be assigned to the same
1439 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001440 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001441 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001442 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001443 case InlineAsm::isInput:
1444 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001445 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001446 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001447 case InlineAsm::isClobber:
1448 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001449 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1450 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001451 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001452 }
1453 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001454
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001455 // Loop over all of the inputs, copying the operand values into the
1456 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001457 RegsForValue RetValRegs;
1458 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001459 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001460
Chris Lattner6656dd12006-01-31 02:03:41 +00001461 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001462 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1463 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001464
Chris Lattner2cc2f662006-02-01 01:28:23 +00001465 switch (Constraints[i].Type) {
1466 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001467 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1468 if (ConstraintCode.size() == 1) // not a physreg name.
1469 CTy = TLI.getConstraintType(ConstraintCode[0]);
1470
1471 if (CTy == TargetLowering::C_Memory) {
1472 // Memory output.
1473 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1474
1475 // Check that the operand (the address to store to) isn't a float.
1476 if (!MVT::isInteger(InOperandVal.getValueType()))
1477 assert(0 && "MATCH FAIL!");
1478
1479 if (!Constraints[i].isIndirectOutput)
1480 assert(0 && "MATCH FAIL!");
1481
1482 OpNum++; // Consumes a call operand.
1483
1484 // Extend/truncate to the right pointer type if needed.
1485 MVT::ValueType PtrType = TLI.getPointerTy();
1486 if (InOperandVal.getValueType() < PtrType)
1487 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1488 else if (InOperandVal.getValueType() > PtrType)
1489 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1490
1491 // Add information to the INLINEASM node to know about this output.
1492 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1493 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1494 AsmNodeOperands.push_back(InOperandVal);
1495 break;
1496 }
1497
1498 // Otherwise, this is a register output.
1499 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1500
Chris Lattner864635a2006-02-22 22:37:12 +00001501 // If this is an early-clobber output, or if there is an input
1502 // constraint that matches this, we need to reserve the input register
1503 // so no other inputs allocate to it.
1504 bool UsesInputRegister = false;
1505 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1506 UsesInputRegister = true;
1507
1508 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001509 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001510 RegsForValue Regs =
1511 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1512 true, UsesInputRegister,
1513 OutputRegs, InputRegs);
1514 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001515
Chris Lattner2cc2f662006-02-01 01:28:23 +00001516 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001517 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001518 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001519 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001520 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001521 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001522 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1523 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001524 OpNum++; // Consumes a call operand.
1525 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001526
1527 // Add information to the INLINEASM node to know that this register is
1528 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001529 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001530 break;
1531 }
1532 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001533 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001534 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001535
Chris Lattner2223aea2006-02-02 00:25:23 +00001536 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1537 // If this is required to match an output register we have already set,
1538 // just use its register.
1539 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001540
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001541 // Scan until we find the definition we already emitted of this operand.
1542 // When we find it, create a RegsForValue operand.
1543 unsigned CurOp = 2; // The first operand.
1544 for (; OperandNo; --OperandNo) {
1545 // Advance to the next operand.
1546 unsigned NumOps =
1547 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1548 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1549 "Skipped past definitions?");
1550 CurOp += (NumOps>>3)+1;
1551 }
1552
1553 unsigned NumOps =
1554 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1555 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1556 "Skipped past definitions?");
1557
1558 // Add NumOps>>3 registers to MatchedRegs.
1559 RegsForValue MatchedRegs;
1560 MatchedRegs.ValueVT = InOperandVal.getValueType();
1561 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1562 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1563 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1564 MatchedRegs.Regs.push_back(Reg);
1565 }
1566
1567 // Use the produced MatchedRegs object to
1568 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1569 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001570 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00001571 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00001572
1573 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1574 if (ConstraintCode.size() == 1) // not a physreg name.
1575 CTy = TLI.getConstraintType(ConstraintCode[0]);
1576
1577 if (CTy == TargetLowering::C_Other) {
1578 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1579 assert(0 && "MATCH FAIL!");
1580
1581 // Add information to the INLINEASM node to know about this input.
1582 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1583 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1584 AsmNodeOperands.push_back(InOperandVal);
1585 break;
1586 } else if (CTy == TargetLowering::C_Memory) {
1587 // Memory input.
1588
1589 // Check that the operand isn't a float.
1590 if (!MVT::isInteger(InOperandVal.getValueType()))
1591 assert(0 && "MATCH FAIL!");
1592
1593 // Extend/truncate to the right pointer type if needed.
1594 MVT::ValueType PtrType = TLI.getPointerTy();
1595 if (InOperandVal.getValueType() < PtrType)
1596 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1597 else if (InOperandVal.getValueType() > PtrType)
1598 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1599
1600 // Add information to the INLINEASM node to know about this input.
1601 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1602 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1603 AsmNodeOperands.push_back(InOperandVal);
1604 break;
1605 }
1606
1607 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1608
1609 // Copy the input into the appropriate registers.
1610 RegsForValue InRegs =
1611 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1612 false, true, OutputRegs, InputRegs);
1613 // FIXME: should be match fail.
1614 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1615
1616 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1617
1618 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001619 break;
1620 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001621 case InlineAsm::isClobber: {
1622 RegsForValue ClobberedRegs =
1623 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1624 OutputRegs, InputRegs);
1625 // Add the clobbered value to the operand list, so that the register
1626 // allocator is aware that the physreg got clobbered.
1627 if (!ClobberedRegs.Regs.empty())
1628 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001629 break;
1630 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001631 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001632 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001633
1634 // Finish up input operands.
1635 AsmNodeOperands[0] = Chain;
1636 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1637
1638 std::vector<MVT::ValueType> VTs;
1639 VTs.push_back(MVT::Other);
1640 VTs.push_back(MVT::Flag);
1641 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1642 Flag = Chain.getValue(1);
1643
Chris Lattner6656dd12006-01-31 02:03:41 +00001644 // If this asm returns a register value, copy the result from that register
1645 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001646 if (!RetValRegs.Regs.empty())
1647 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001648
Chris Lattner6656dd12006-01-31 02:03:41 +00001649 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1650
1651 // Process indirect outputs, first output all of the flagged copies out of
1652 // physregs.
1653 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001654 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001655 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001656 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1657 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001658 }
1659
1660 // Emit the non-flagged stores from the physregs.
1661 std::vector<SDOperand> OutChains;
1662 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1663 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1664 StoresToEmit[i].first,
1665 getValue(StoresToEmit[i].second),
1666 DAG.getSrcValue(StoresToEmit[i].second)));
1667 if (!OutChains.empty())
1668 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001669 DAG.setRoot(Chain);
1670}
1671
1672
Chris Lattner1c08c712005-01-07 07:47:53 +00001673void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1674 SDOperand Src = getValue(I.getOperand(0));
1675
1676 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001677
1678 if (IntPtr < Src.getValueType())
1679 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1680 else if (IntPtr > Src.getValueType())
1681 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001682
1683 // Scale the source by the type size.
1684 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1685 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1686 Src, getIntPtrConstant(ElementSize));
1687
1688 std::vector<std::pair<SDOperand, const Type*> > Args;
1689 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001690
1691 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001692 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001693 DAG.getExternalSymbol("malloc", IntPtr),
1694 Args, DAG);
1695 setValue(&I, Result.first); // Pointers always fit in registers
1696 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001697}
1698
1699void SelectionDAGLowering::visitFree(FreeInst &I) {
1700 std::vector<std::pair<SDOperand, const Type*> > Args;
1701 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1702 TLI.getTargetData().getIntPtrType()));
1703 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001704 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001705 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001706 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1707 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001708}
1709
Chris Lattner025c39b2005-08-26 20:54:47 +00001710// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1711// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1712// instructions are special in various ways, which require special support to
1713// insert. The specified MachineInstr is created but not inserted into any
1714// basic blocks, and the scheduler passes ownership of it to this method.
1715MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1716 MachineBasicBlock *MBB) {
1717 std::cerr << "If a target marks an instruction with "
1718 "'usesCustomDAGSchedInserter', it must implement "
1719 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1720 abort();
1721 return 0;
1722}
1723
Chris Lattner39ae3622005-01-09 00:00:49 +00001724void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001725 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1726 getValue(I.getOperand(1)),
1727 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001728}
1729
1730void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001731 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1732 getValue(I.getOperand(0)),
1733 DAG.getSrcValue(I.getOperand(0)));
1734 setValue(&I, V);
1735 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001736}
1737
1738void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001739 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1740 getValue(I.getOperand(1)),
1741 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001742}
1743
1744void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001745 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1746 getValue(I.getOperand(1)),
1747 getValue(I.getOperand(2)),
1748 DAG.getSrcValue(I.getOperand(1)),
1749 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001750}
1751
Chris Lattner39ae3622005-01-09 00:00:49 +00001752// It is always conservatively correct for llvm.returnaddress and
1753// llvm.frameaddress to return 0.
1754std::pair<SDOperand, SDOperand>
1755TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1756 unsigned Depth, SelectionDAG &DAG) {
1757 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001758}
1759
Chris Lattner50381b62005-05-14 05:50:48 +00001760SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001761 assert(0 && "LowerOperation not implemented for this target!");
1762 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001763 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001764}
1765
Nate Begeman0aed7842006-01-28 03:14:31 +00001766SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1767 SelectionDAG &DAG) {
1768 assert(0 && "CustomPromoteOperation not implemented for this target!");
1769 abort();
1770 return SDOperand();
1771}
1772
Chris Lattner39ae3622005-01-09 00:00:49 +00001773void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1774 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1775 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001776 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001777 setValue(&I, Result.first);
1778 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001779}
1780
Evan Cheng74d0aa92006-02-15 21:59:04 +00001781/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001782/// operand.
1783static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001784 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001785 MVT::ValueType CurVT = VT;
1786 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1787 uint64_t Val = C->getValue() & 255;
1788 unsigned Shift = 8;
1789 while (CurVT != MVT::i8) {
1790 Val = (Val << Shift) | Val;
1791 Shift <<= 1;
1792 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001793 }
1794 return DAG.getConstant(Val, VT);
1795 } else {
1796 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1797 unsigned Shift = 8;
1798 while (CurVT != MVT::i8) {
1799 Value =
1800 DAG.getNode(ISD::OR, VT,
1801 DAG.getNode(ISD::SHL, VT, Value,
1802 DAG.getConstant(Shift, MVT::i8)), Value);
1803 Shift <<= 1;
1804 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001805 }
1806
1807 return Value;
1808 }
1809}
1810
Evan Cheng74d0aa92006-02-15 21:59:04 +00001811/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1812/// used when a memcpy is turned into a memset when the source is a constant
1813/// string ptr.
1814static SDOperand getMemsetStringVal(MVT::ValueType VT,
1815 SelectionDAG &DAG, TargetLowering &TLI,
1816 std::string &Str, unsigned Offset) {
1817 MVT::ValueType CurVT = VT;
1818 uint64_t Val = 0;
1819 unsigned MSB = getSizeInBits(VT) / 8;
1820 if (TLI.isLittleEndian())
1821 Offset = Offset + MSB - 1;
1822 for (unsigned i = 0; i != MSB; ++i) {
1823 Val = (Val << 8) | Str[Offset];
1824 Offset += TLI.isLittleEndian() ? -1 : 1;
1825 }
1826 return DAG.getConstant(Val, VT);
1827}
1828
Evan Cheng1db92f92006-02-14 08:22:34 +00001829/// getMemBasePlusOffset - Returns base and offset node for the
1830static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1831 SelectionDAG &DAG, TargetLowering &TLI) {
1832 MVT::ValueType VT = Base.getValueType();
1833 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1834}
1835
Evan Chengc4f8eee2006-02-14 20:12:38 +00001836/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001837/// to replace the memset / memcpy is below the threshold. It also returns the
1838/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001839static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1840 unsigned Limit, uint64_t Size,
1841 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001842 MVT::ValueType VT;
1843
1844 if (TLI.allowsUnalignedMemoryAccesses()) {
1845 VT = MVT::i64;
1846 } else {
1847 switch (Align & 7) {
1848 case 0:
1849 VT = MVT::i64;
1850 break;
1851 case 4:
1852 VT = MVT::i32;
1853 break;
1854 case 2:
1855 VT = MVT::i16;
1856 break;
1857 default:
1858 VT = MVT::i8;
1859 break;
1860 }
1861 }
1862
Evan Cheng80e89d72006-02-14 09:11:59 +00001863 MVT::ValueType LVT = MVT::i64;
1864 while (!TLI.isTypeLegal(LVT))
1865 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1866 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001867
Evan Cheng80e89d72006-02-14 09:11:59 +00001868 if (VT > LVT)
1869 VT = LVT;
1870
Evan Chengdea72452006-02-14 23:05:54 +00001871 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001872 while (Size != 0) {
1873 unsigned VTSize = getSizeInBits(VT) / 8;
1874 while (VTSize > Size) {
1875 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001876 VTSize >>= 1;
1877 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001878 assert(MVT::isInteger(VT));
1879
1880 if (++NumMemOps > Limit)
1881 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001882 MemOps.push_back(VT);
1883 Size -= VTSize;
1884 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001885
1886 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001887}
1888
Chris Lattner7041ee32005-01-11 05:56:49 +00001889void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001890 SDOperand Op1 = getValue(I.getOperand(1));
1891 SDOperand Op2 = getValue(I.getOperand(2));
1892 SDOperand Op3 = getValue(I.getOperand(3));
1893 SDOperand Op4 = getValue(I.getOperand(4));
1894 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1895 if (Align == 0) Align = 1;
1896
1897 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1898 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001899
1900 // Expand memset / memcpy to a series of load / store ops
1901 // if the size operand falls below a certain threshold.
1902 std::vector<SDOperand> OutChains;
1903 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001904 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001905 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001906 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1907 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00001908 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00001909 unsigned Offset = 0;
1910 for (unsigned i = 0; i < NumMemOps; i++) {
1911 MVT::ValueType VT = MemOps[i];
1912 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00001913 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00001914 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1915 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00001916 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1917 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00001918 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00001919 Offset += VTSize;
1920 }
Evan Cheng1db92f92006-02-14 08:22:34 +00001921 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001922 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00001923 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001924 case ISD::MEMCPY: {
1925 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1926 Size->getValue(), Align, TLI)) {
1927 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00001928 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001929 GlobalAddressSDNode *G = NULL;
1930 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00001931 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001932
1933 if (Op2.getOpcode() == ISD::GlobalAddress)
1934 G = cast<GlobalAddressSDNode>(Op2);
1935 else if (Op2.getOpcode() == ISD::ADD &&
1936 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1937 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1938 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00001939 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00001940 }
1941 if (G) {
1942 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00001943 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00001944 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00001945 if (!Str.empty()) {
1946 CopyFromStr = true;
1947 SrcOff += SrcDelta;
1948 }
1949 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00001950 }
1951
Evan Chengc080d6f2006-02-15 01:54:51 +00001952 for (unsigned i = 0; i < NumMemOps; i++) {
1953 MVT::ValueType VT = MemOps[i];
1954 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001955 SDOperand Value, Chain, Store;
1956
Evan Chengcffbb512006-02-16 23:11:42 +00001957 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001958 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1959 Chain = getRoot();
1960 Store =
1961 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1962 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1963 DAG.getSrcValue(I.getOperand(1), DstOff));
1964 } else {
1965 Value = DAG.getLoad(VT, getRoot(),
1966 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1967 DAG.getSrcValue(I.getOperand(2), SrcOff));
1968 Chain = Value.getValue(1);
1969 Store =
1970 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1971 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1972 DAG.getSrcValue(I.getOperand(1), DstOff));
1973 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001974 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00001975 SrcOff += VTSize;
1976 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00001977 }
1978 }
1979 break;
1980 }
1981 }
1982
1983 if (!OutChains.empty()) {
1984 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1985 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00001986 }
1987 }
1988
Chris Lattner7041ee32005-01-11 05:56:49 +00001989 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001990 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00001991 Ops.push_back(Op1);
1992 Ops.push_back(Op2);
1993 Ops.push_back(Op3);
1994 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00001995 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001996}
1997
Chris Lattner7041ee32005-01-11 05:56:49 +00001998//===----------------------------------------------------------------------===//
1999// SelectionDAGISel code
2000//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002001
2002unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2003 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2004}
2005
Chris Lattner495a0b52005-08-17 06:37:43 +00002006void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002007 // FIXME: we only modify the CFG to split critical edges. This
2008 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002009}
Chris Lattner1c08c712005-01-07 07:47:53 +00002010
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002011
2012/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2013/// casting to the type of GEPI.
2014static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2015 Value *Ptr, Value *PtrOffset) {
2016 if (V) return V; // Already computed.
2017
2018 BasicBlock::iterator InsertPt;
2019 if (BB == GEPI->getParent()) {
2020 // If insert into the GEP's block, insert right after the GEP.
2021 InsertPt = GEPI;
2022 ++InsertPt;
2023 } else {
2024 // Otherwise, insert at the top of BB, after any PHI nodes
2025 InsertPt = BB->begin();
2026 while (isa<PHINode>(InsertPt)) ++InsertPt;
2027 }
2028
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002029 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2030 // BB so that there is only one value live across basic blocks (the cast
2031 // operand).
2032 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2033 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2034 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2035
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002036 // Add the offset, cast it to the right type.
2037 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2038 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2039 return V = Ptr;
2040}
2041
2042
2043/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2044/// selection, we want to be a bit careful about some things. In particular, if
2045/// we have a GEP instruction that is used in a different block than it is
2046/// defined, the addressing expression of the GEP cannot be folded into loads or
2047/// stores that use it. In this case, decompose the GEP and move constant
2048/// indices into blocks that use it.
2049static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2050 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002051 // If this GEP is only used inside the block it is defined in, there is no
2052 // need to rewrite it.
2053 bool isUsedOutsideDefBB = false;
2054 BasicBlock *DefBB = GEPI->getParent();
2055 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2056 UI != E; ++UI) {
2057 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2058 isUsedOutsideDefBB = true;
2059 break;
2060 }
2061 }
2062 if (!isUsedOutsideDefBB) return;
2063
2064 // If this GEP has no non-zero constant indices, there is nothing we can do,
2065 // ignore it.
2066 bool hasConstantIndex = false;
2067 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2068 E = GEPI->op_end(); OI != E; ++OI) {
2069 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2070 if (CI->getRawValue()) {
2071 hasConstantIndex = true;
2072 break;
2073 }
2074 }
Chris Lattner3802c252005-12-11 09:05:13 +00002075 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2076 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002077
2078 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2079 // constant offset (which we now know is non-zero) and deal with it later.
2080 uint64_t ConstantOffset = 0;
2081 const Type *UIntPtrTy = TD.getIntPtrType();
2082 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2083 const Type *Ty = GEPI->getOperand(0)->getType();
2084
2085 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2086 E = GEPI->op_end(); OI != E; ++OI) {
2087 Value *Idx = *OI;
2088 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2089 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2090 if (Field)
2091 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2092 Ty = StTy->getElementType(Field);
2093 } else {
2094 Ty = cast<SequentialType>(Ty)->getElementType();
2095
2096 // Handle constant subscripts.
2097 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2098 if (CI->getRawValue() == 0) continue;
2099
2100 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2101 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2102 else
2103 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2104 continue;
2105 }
2106
2107 // Ptr = Ptr + Idx * ElementSize;
2108
2109 // Cast Idx to UIntPtrTy if needed.
2110 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2111
2112 uint64_t ElementSize = TD.getTypeSize(Ty);
2113 // Mask off bits that should not be set.
2114 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2115 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2116
2117 // Multiply by the element size and add to the base.
2118 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2119 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2120 }
2121 }
2122
2123 // Make sure that the offset fits in uintptr_t.
2124 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2125 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2126
2127 // Okay, we have now emitted all of the variable index parts to the BB that
2128 // the GEP is defined in. Loop over all of the using instructions, inserting
2129 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002130 // instruction to use the newly computed value, making GEPI dead. When the
2131 // user is a load or store instruction address, we emit the add into the user
2132 // block, otherwise we use a canonical version right next to the gep (these
2133 // won't be foldable as addresses, so we might as well share the computation).
2134
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002135 std::map<BasicBlock*,Value*> InsertedExprs;
2136 while (!GEPI->use_empty()) {
2137 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002138
2139 // If this use is not foldable into the addressing mode, use a version
2140 // emitted in the GEP block.
2141 Value *NewVal;
2142 if (!isa<LoadInst>(User) &&
2143 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2144 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2145 Ptr, PtrOffset);
2146 } else {
2147 // Otherwise, insert the code in the User's block so it can be folded into
2148 // any users in that block.
2149 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002150 User->getParent(), GEPI,
2151 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002152 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002153 User->replaceUsesOfWith(GEPI, NewVal);
2154 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002155
2156 // Finally, the GEP is dead, remove it.
2157 GEPI->eraseFromParent();
2158}
2159
Chris Lattner1c08c712005-01-07 07:47:53 +00002160bool SelectionDAGISel::runOnFunction(Function &Fn) {
2161 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2162 RegMap = MF.getSSARegMap();
2163 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2164
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002165 // First, split all critical edges for PHI nodes with incoming values that are
2166 // constants, this way the load of the constant into a vreg will not be placed
2167 // into MBBs that are used some other way.
2168 //
2169 // In this pass we also look for GEP instructions that are used across basic
2170 // blocks and rewrites them to improve basic-block-at-a-time selection.
2171 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002172 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2173 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002174 BasicBlock::iterator BBI;
2175 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002176 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2177 if (isa<Constant>(PN->getIncomingValue(i)))
2178 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002179
2180 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2181 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2182 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002183 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002184
Chris Lattner1c08c712005-01-07 07:47:53 +00002185 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2186
2187 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2188 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002189
Chris Lattner1c08c712005-01-07 07:47:53 +00002190 return true;
2191}
2192
2193
Chris Lattnerddb870b2005-01-13 17:59:43 +00002194SDOperand SelectionDAGISel::
2195CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002196 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002197 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002198 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002199 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002200
2201 // If this type is not legal, we must make sure to not create an invalid
2202 // register use.
2203 MVT::ValueType SrcVT = Op.getValueType();
2204 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2205 SelectionDAG &DAG = SDL.DAG;
2206 if (SrcVT == DestVT) {
2207 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2208 } else if (SrcVT < DestVT) {
2209 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002210 if (MVT::isFloatingPoint(SrcVT))
2211 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2212 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002213 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002214 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2215 } else {
2216 // The src value is expanded into multiple registers.
2217 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2218 Op, DAG.getConstant(0, MVT::i32));
2219 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2220 Op, DAG.getConstant(1, MVT::i32));
2221 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2222 return DAG.getCopyToReg(Op, Reg+1, Hi);
2223 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002224}
2225
Chris Lattner068a81e2005-01-17 17:15:02 +00002226void SelectionDAGISel::
2227LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2228 std::vector<SDOperand> &UnorderedChains) {
2229 // If this is the entry block, emit arguments.
2230 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002231 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002232 SDOperand OldRoot = SDL.DAG.getRoot();
2233 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002234
Chris Lattnerbf209482005-10-30 19:42:35 +00002235 unsigned a = 0;
2236 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2237 AI != E; ++AI, ++a)
2238 if (!AI->use_empty()) {
2239 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002240
Chris Lattnerbf209482005-10-30 19:42:35 +00002241 // If this argument is live outside of the entry block, insert a copy from
2242 // whereever we got it to the vreg that other BB's will reference it as.
2243 if (FuncInfo.ValueMap.count(AI)) {
2244 SDOperand Copy =
2245 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2246 UnorderedChains.push_back(Copy);
2247 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002248 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002249
2250 // Next, if the function has live ins that need to be copied into vregs,
2251 // emit the copies now, into the top of the block.
2252 MachineFunction &MF = SDL.DAG.getMachineFunction();
2253 if (MF.livein_begin() != MF.livein_end()) {
2254 SSARegMap *RegMap = MF.getSSARegMap();
2255 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2256 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2257 E = MF.livein_end(); LI != E; ++LI)
2258 if (LI->second)
2259 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2260 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002261 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002262
2263 // Finally, if the target has anything special to do, allow it to do so.
2264 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002265}
2266
2267
Chris Lattner1c08c712005-01-07 07:47:53 +00002268void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2269 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2270 FunctionLoweringInfo &FuncInfo) {
2271 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002272
2273 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002274
Chris Lattnerbf209482005-10-30 19:42:35 +00002275 // Lower any arguments needed in this block if this is the entry block.
2276 if (LLVMBB == &LLVMBB->getParent()->front())
2277 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002278
2279 BB = FuncInfo.MBBMap[LLVMBB];
2280 SDL.setCurrentBasicBlock(BB);
2281
2282 // Lower all of the non-terminator instructions.
2283 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2284 I != E; ++I)
2285 SDL.visit(*I);
2286
2287 // Ensure that all instructions which are used outside of their defining
2288 // blocks are available as virtual registers.
2289 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002290 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002291 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002292 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002293 UnorderedChains.push_back(
2294 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002295 }
2296
2297 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2298 // ensure constants are generated when needed. Remember the virtual registers
2299 // that need to be added to the Machine PHI nodes as input. We cannot just
2300 // directly add them, because expansion might result in multiple MBB's for one
2301 // BB. As such, the start of the BB might correspond to a different MBB than
2302 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002303 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002304
2305 // Emit constants only once even if used by multiple PHI nodes.
2306 std::map<Constant*, unsigned> ConstantsOut;
2307
2308 // Check successor nodes PHI nodes that expect a constant to be available from
2309 // this block.
2310 TerminatorInst *TI = LLVMBB->getTerminator();
2311 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2312 BasicBlock *SuccBB = TI->getSuccessor(succ);
2313 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2314 PHINode *PN;
2315
2316 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2317 // nodes and Machine PHI nodes, but the incoming operands have not been
2318 // emitted yet.
2319 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002320 (PN = dyn_cast<PHINode>(I)); ++I)
2321 if (!PN->use_empty()) {
2322 unsigned Reg;
2323 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2324 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2325 unsigned &RegOut = ConstantsOut[C];
2326 if (RegOut == 0) {
2327 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002328 UnorderedChains.push_back(
2329 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002330 }
2331 Reg = RegOut;
2332 } else {
2333 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002334 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002335 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002336 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2337 "Didn't codegen value into a register!??");
2338 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002339 UnorderedChains.push_back(
2340 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002341 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002342 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002343
Chris Lattnerf44fd882005-01-07 21:34:19 +00002344 // Remember that this register needs to added to the machine PHI node as
2345 // the input for this MBB.
2346 unsigned NumElements =
2347 TLI.getNumElements(TLI.getValueType(PN->getType()));
2348 for (unsigned i = 0, e = NumElements; i != e; ++i)
2349 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002350 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002351 }
2352 ConstantsOut.clear();
2353
Chris Lattnerddb870b2005-01-13 17:59:43 +00002354 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002355 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002356 SDOperand Root = SDL.getRoot();
2357 if (Root.getOpcode() != ISD::EntryToken) {
2358 unsigned i = 0, e = UnorderedChains.size();
2359 for (; i != e; ++i) {
2360 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2361 if (UnorderedChains[i].Val->getOperand(0) == Root)
2362 break; // Don't add the root if we already indirectly depend on it.
2363 }
2364
2365 if (i == e)
2366 UnorderedChains.push_back(Root);
2367 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002368 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2369 }
2370
Chris Lattner1c08c712005-01-07 07:47:53 +00002371 // Lower the terminator after the copies are emitted.
2372 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002373
2374 // Make sure the root of the DAG is up-to-date.
2375 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002376}
2377
2378void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2379 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002380 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002381 CurDAG = &DAG;
2382 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2383
2384 // First step, lower LLVM code to some DAG. This DAG may use operations and
2385 // types that are not supported by the target.
2386 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2387
Chris Lattneraf21d552005-10-10 16:47:10 +00002388 // Run the DAG combiner in pre-legalize mode.
2389 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002390
Chris Lattner1c08c712005-01-07 07:47:53 +00002391 DEBUG(std::cerr << "Lowered selection DAG:\n");
2392 DEBUG(DAG.dump());
2393
2394 // Second step, hack on the DAG until it only uses operations and types that
2395 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002396 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002397
2398 DEBUG(std::cerr << "Legalized selection DAG:\n");
2399 DEBUG(DAG.dump());
2400
Chris Lattneraf21d552005-10-10 16:47:10 +00002401 // Run the DAG combiner in post-legalize mode.
2402 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002403
Evan Chenga9c20912006-01-21 02:32:06 +00002404 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002405
Chris Lattnera33ef482005-03-30 01:10:47 +00002406 // Third, instruction select all of the operations to machine code, adding the
2407 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002408 InstructionSelectBasicBlock(DAG);
2409
Chris Lattner1c08c712005-01-07 07:47:53 +00002410 DEBUG(std::cerr << "Selected machine code:\n");
2411 DEBUG(BB->dump());
2412
Chris Lattnera33ef482005-03-30 01:10:47 +00002413 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002414 // PHI nodes in successors.
2415 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2416 MachineInstr *PHI = PHINodesToUpdate[i].first;
2417 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2418 "This is not a machine PHI node that we are updating!");
2419 PHI->addRegOperand(PHINodesToUpdate[i].second);
2420 PHI->addMachineBasicBlockOperand(BB);
2421 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002422
2423 // Finally, add the CFG edges from the last selected MBB to the successor
2424 // MBBs.
2425 TerminatorInst *TI = LLVMBB->getTerminator();
2426 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2427 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2428 BB->addSuccessor(Succ0MBB);
2429 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002430}
Evan Chenga9c20912006-01-21 02:32:06 +00002431
2432//===----------------------------------------------------------------------===//
2433/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2434/// target node in the graph.
2435void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2436 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002437 ScheduleDAG *SL = NULL;
2438
2439 switch (ISHeuristic) {
2440 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002441 case defaultScheduling:
2442 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2443 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2444 else /* TargetLowering::SchedulingForRegPressure */
2445 SL = createBURRListDAGScheduler(DAG, BB);
2446 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002447 case noScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002448 SL = createBFS_DAGScheduler(DAG, BB);
2449 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002450 case simpleScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002451 SL = createSimpleDAGScheduler(false, DAG, BB);
2452 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002453 case simpleNoItinScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002454 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002455 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002456 case listSchedulingBURR:
2457 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnera5de4842006-03-05 21:10:33 +00002458 break;
Chris Lattner03fc53c2006-03-06 00:22:00 +00002459 case listSchedulingTD:
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002460 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattnera5de4842006-03-05 21:10:33 +00002461 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002462 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002463 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002464 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002465}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002466
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002467HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2468 return new HazardRecognizer();
Chris Lattner03fc53c2006-03-06 00:22:00 +00002469}
2470
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002471/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2472/// by tblgen. Others should not call it.
2473void SelectionDAGISel::
2474SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2475 std::vector<SDOperand> InOps;
2476 std::swap(InOps, Ops);
2477
2478 Ops.push_back(InOps[0]); // input chain.
2479 Ops.push_back(InOps[1]); // input asm string.
2480
2481 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2482 unsigned i = 2, e = InOps.size();
2483 if (InOps[e-1].getValueType() == MVT::Flag)
2484 --e; // Don't process a flag operand if it is here.
2485
2486 while (i != e) {
2487 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2488 if ((Flags & 7) != 4 /*MEM*/) {
2489 // Just skip over this operand, copying the operands verbatim.
2490 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2491 i += (Flags >> 3) + 1;
2492 } else {
2493 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2494 // Otherwise, this is a memory operand. Ask the target to select it.
2495 std::vector<SDOperand> SelOps;
2496 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2497 std::cerr << "Could not match memory address. Inline asm failure!\n";
2498 exit(1);
2499 }
2500
2501 // Add this to the output node.
2502 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2503 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2504 i += 2;
2505 }
2506 }
2507
2508 // Add the flag input back if present.
2509 if (e != InOps.size())
2510 Ops.push_back(InOps.back());
2511}