blob: 0060de4a4acd154e8dc38e126f8451ae447bb078 [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>
45using namespace llvm;
46
Chris Lattnerda8abb02005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000048static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000049ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51static cl::opt<bool>
52ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000054#else
Evan Chenga9c20912006-01-21 02:32:06 +000055static const bool ViewISelDAGs = 0;
56static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#endif
58
Evan Cheng4ef10862006-01-23 07:01:07 +000059namespace {
60 cl::opt<SchedHeuristics>
61 ISHeuristic(
62 "sched",
63 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000064 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000065 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000066 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000068 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000069 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000070 clEnumValN(simpleScheduling, "simple",
71 "Simple two pass scheduling: minimize critical path "
72 "and maximize processor utilization"),
73 clEnumValN(simpleNoItinScheduling, "simple-noitin",
74 "Simple two pass scheduling: Same as simple "
75 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000076 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000077 "Bottom up register reduction list scheduling"),
Evan Cheng4ef10862006-01-23 07:01:07 +000078 clEnumValEnd));
79} // namespace
80
Chris Lattner864635a2006-02-22 22:37:12 +000081namespace {
82 /// RegsForValue - This struct represents the physical registers that a
83 /// particular value is assigned and the type information about the value.
84 /// This is needed because values can be promoted into larger registers and
85 /// expanded into multiple smaller registers than the value.
86 struct RegsForValue {
87 /// Regs - This list hold the register (for legal and promoted values)
88 /// or register set (for expanded values) that the value should be assigned
89 /// to.
90 std::vector<unsigned> Regs;
91
92 /// RegVT - The value type of each register.
93 ///
94 MVT::ValueType RegVT;
95
96 /// ValueVT - The value type of the LLVM value, which may be promoted from
97 /// RegVT or made from merging the two expanded parts.
98 MVT::ValueType ValueVT;
99
100 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
101
102 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
103 : RegVT(regvt), ValueVT(valuevt) {
104 Regs.push_back(Reg);
105 }
106 RegsForValue(const std::vector<unsigned> &regs,
107 MVT::ValueType regvt, MVT::ValueType valuevt)
108 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
109 }
110
111 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
112 /// this value and returns the result as a ValueVT value. This uses
113 /// Chain/Flag as the input and updates them for the output Chain/Flag.
114 SDOperand getCopyFromRegs(SelectionDAG &DAG,
115 SDOperand &Chain, SDOperand &Flag);
116 };
117}
Evan Cheng4ef10862006-01-23 07:01:07 +0000118
Chris Lattner1c08c712005-01-07 07:47:53 +0000119namespace llvm {
120 //===--------------------------------------------------------------------===//
121 /// FunctionLoweringInfo - This contains information that is global to a
122 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000123 class FunctionLoweringInfo {
124 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000125 TargetLowering &TLI;
126 Function &Fn;
127 MachineFunction &MF;
128 SSARegMap *RegMap;
129
130 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
131
132 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
133 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
134
135 /// ValueMap - Since we emit code for the function a basic block at a time,
136 /// we must remember which virtual registers hold the values for
137 /// cross-basic-block values.
138 std::map<const Value*, unsigned> ValueMap;
139
140 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
141 /// the entry block. This allows the allocas to be efficiently referenced
142 /// anywhere in the function.
143 std::map<const AllocaInst*, int> StaticAllocaMap;
144
145 unsigned MakeReg(MVT::ValueType VT) {
146 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
147 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000148
Chris Lattner1c08c712005-01-07 07:47:53 +0000149 unsigned CreateRegForValue(const Value *V) {
150 MVT::ValueType VT = TLI.getValueType(V->getType());
151 // The common case is that we will only create one register for this
152 // value. If we have that case, create and return the virtual register.
153 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000154 if (NV == 1) {
155 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000156 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000157 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000158
Chris Lattner1c08c712005-01-07 07:47:53 +0000159 // If this value is represented with multiple target registers, make sure
Chris Lattner864635a2006-02-22 22:37:12 +0000160 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 unsigned NT = VT-1; // Find the type to use.
162 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
163 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000164
Chris Lattner1c08c712005-01-07 07:47:53 +0000165 unsigned R = MakeReg((MVT::ValueType)NT);
166 for (unsigned i = 1; i != NV; ++i)
167 MakeReg((MVT::ValueType)NT);
168 return R;
169 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000170
Chris Lattner1c08c712005-01-07 07:47:53 +0000171 unsigned InitializeRegForValue(const Value *V) {
172 unsigned &R = ValueMap[V];
173 assert(R == 0 && "Already initialized this value register!");
174 return R = CreateRegForValue(V);
175 }
176 };
177}
178
179/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
180/// PHI nodes or outside of the basic block that defines it.
181static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
182 if (isa<PHINode>(I)) return true;
183 BasicBlock *BB = I->getParent();
184 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
185 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
186 return true;
187 return false;
188}
189
Chris Lattnerbf209482005-10-30 19:42:35 +0000190/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
191/// entry block, return true.
192static bool isOnlyUsedInEntryBlock(Argument *A) {
193 BasicBlock *Entry = A->getParent()->begin();
194 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
195 if (cast<Instruction>(*UI)->getParent() != Entry)
196 return false; // Use not in entry block.
197 return true;
198}
199
Chris Lattner1c08c712005-01-07 07:47:53 +0000200FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000201 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000202 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
203
Chris Lattnerbf209482005-10-30 19:42:35 +0000204 // Create a vreg for each argument register that is not dead and is used
205 // outside of the entry block for the function.
206 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
207 AI != E; ++AI)
208 if (!isOnlyUsedInEntryBlock(AI))
209 InitializeRegForValue(AI);
210
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 // Initialize the mapping of values to registers. This is only set up for
212 // instruction values that are used outside of the block that defines
213 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000214 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000215 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
216 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
217 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
218 const Type *Ty = AI->getAllocatedType();
219 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000220 unsigned Align =
221 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
222 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000223
224 // If the alignment of the value is smaller than the size of the value,
225 // and if the size of the value is particularly small (<= 8 bytes),
226 // round up to the size of the value for potentially better performance.
227 //
228 // FIXME: This could be made better with a preferred alignment hook in
229 // TargetData. It serves primarily to 8-byte align doubles for X86.
230 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000231 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000232 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000233 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000234 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000235 }
236
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000237 for (; BB != EB; ++BB)
238 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000239 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
240 if (!isa<AllocaInst>(I) ||
241 !StaticAllocaMap.count(cast<AllocaInst>(I)))
242 InitializeRegForValue(I);
243
244 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
245 // also creates the initial PHI MachineInstrs, though none of the input
246 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000247 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000248 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
249 MBBMap[BB] = MBB;
250 MF.getBasicBlockList().push_back(MBB);
251
252 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
253 // appropriate.
254 PHINode *PN;
255 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000256 (PN = dyn_cast<PHINode>(I)); ++I)
257 if (!PN->use_empty()) {
258 unsigned NumElements =
259 TLI.getNumElements(TLI.getValueType(PN->getType()));
260 unsigned PHIReg = ValueMap[PN];
261 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
262 for (unsigned i = 0; i != NumElements; ++i)
263 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
264 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000265 }
266}
267
268
269
270//===----------------------------------------------------------------------===//
271/// SelectionDAGLowering - This is the common target-independent lowering
272/// implementation that is parameterized by a TargetLowering object.
273/// Also, targets can overload any lowering method.
274///
275namespace llvm {
276class SelectionDAGLowering {
277 MachineBasicBlock *CurMBB;
278
279 std::map<const Value*, SDOperand> NodeMap;
280
Chris Lattnerd3948112005-01-17 22:19:26 +0000281 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
282 /// them up and then emit token factor nodes when possible. This allows us to
283 /// get simple disambiguation between loads without worrying about alias
284 /// analysis.
285 std::vector<SDOperand> PendingLoads;
286
Chris Lattner1c08c712005-01-07 07:47:53 +0000287public:
288 // TLI - This is information that describes the available target features we
289 // need for lowering. This indicates when operations are unavailable,
290 // implemented with a libcall, etc.
291 TargetLowering &TLI;
292 SelectionDAG &DAG;
293 const TargetData &TD;
294
295 /// FuncInfo - Information about the function as a whole.
296 ///
297 FunctionLoweringInfo &FuncInfo;
298
299 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000300 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000301 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
302 FuncInfo(funcinfo) {
303 }
304
Chris Lattnera651cf62005-01-17 19:43:36 +0000305 /// getRoot - Return the current virtual root of the Selection DAG.
306 ///
307 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000308 if (PendingLoads.empty())
309 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000310
Chris Lattnerd3948112005-01-17 22:19:26 +0000311 if (PendingLoads.size() == 1) {
312 SDOperand Root = PendingLoads[0];
313 DAG.setRoot(Root);
314 PendingLoads.clear();
315 return Root;
316 }
317
318 // Otherwise, we have to make a token factor node.
319 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
320 PendingLoads.clear();
321 DAG.setRoot(Root);
322 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000323 }
324
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 void visit(Instruction &I) { visit(I.getOpcode(), I); }
326
327 void visit(unsigned Opcode, User &I) {
328 switch (Opcode) {
329 default: assert(0 && "Unknown instruction type encountered!");
330 abort();
331 // Build the switch statement using the Instruction.def file.
332#define HANDLE_INST(NUM, OPCODE, CLASS) \
333 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
334#include "llvm/Instruction.def"
335 }
336 }
337
338 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
339
340
341 SDOperand getIntPtrConstant(uint64_t Val) {
342 return DAG.getConstant(Val, TLI.getPointerTy());
343 }
344
345 SDOperand getValue(const Value *V) {
346 SDOperand &N = NodeMap[V];
347 if (N.Val) return N;
348
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000349 const Type *VTy = V->getType();
350 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000351 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
352 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
353 visit(CE->getOpcode(), *CE);
354 assert(N.Val && "visit didn't populate the ValueMap!");
355 return N;
356 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
357 return N = DAG.getGlobalAddress(GV, VT);
358 } else if (isa<ConstantPointerNull>(C)) {
359 return N = DAG.getConstant(0, TLI.getPointerTy());
360 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000361 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000362 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
363 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000364 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
365 unsigned NumElements = PTy->getNumElements();
366 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
367 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
368
369 // Now that we know the number and type of the elements, push a
370 // Constant or ConstantFP node onto the ops list for each element of
371 // the packed constant.
372 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000373 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
374 if (MVT::isFloatingPoint(PVT)) {
375 for (unsigned i = 0; i != NumElements; ++i) {
376 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
377 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
378 }
379 } else {
380 for (unsigned i = 0; i != NumElements; ++i) {
381 const ConstantIntegral *El =
382 cast<ConstantIntegral>(CP->getOperand(i));
383 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
384 }
385 }
386 } else {
387 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
388 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000389 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000390 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000391 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000392 Op = DAG.getConstant(0, PVT);
393 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000394 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000395
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000396 // Handle the case where we have a 1-element vector, in which
397 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000398 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000399 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000400 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
401 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
402 } else {
403 // If the packed type isn't legal, then create a ConstantVec node with
404 // generic Vector type instead.
405 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
406 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000407 } else {
408 // Canonicalize all constant ints to be unsigned.
409 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
410 }
411
412 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
413 std::map<const AllocaInst*, int>::iterator SI =
414 FuncInfo.StaticAllocaMap.find(AI);
415 if (SI != FuncInfo.StaticAllocaMap.end())
416 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
417 }
418
419 std::map<const Value*, unsigned>::const_iterator VMI =
420 FuncInfo.ValueMap.find(V);
421 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000422
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000423 unsigned InReg = VMI->second;
424
425 // If this type is not legal, make it so now.
426 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
427
428 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
429 if (DestVT < VT) {
430 // Source must be expanded. This input value is actually coming from the
431 // register pair VMI->second and VMI->second+1.
432 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
433 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
434 } else {
435 if (DestVT > VT) { // Promotion case
436 if (MVT::isFloatingPoint(VT))
437 N = DAG.getNode(ISD::FP_ROUND, VT, N);
438 else
439 N = DAG.getNode(ISD::TRUNCATE, VT, N);
440 }
441 }
442
443 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000444 }
445
446 const SDOperand &setValue(const Value *V, SDOperand NewN) {
447 SDOperand &N = NodeMap[V];
448 assert(N.Val == 0 && "Already set a value for this node!");
449 return N = NewN;
450 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000451
Chris Lattner864635a2006-02-22 22:37:12 +0000452 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
453 MVT::ValueType VT,
454 bool OutReg, bool InReg,
455 std::set<unsigned> &OutputRegs,
456 std::set<unsigned> &InputRegs);
457
Chris Lattner1c08c712005-01-07 07:47:53 +0000458 // Terminator instructions.
459 void visitRet(ReturnInst &I);
460 void visitBr(BranchInst &I);
461 void visitUnreachable(UnreachableInst &I) { /* noop */ }
462
463 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000464 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000465 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000466 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
467 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
468 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
469
470 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000471 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000472 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000473 void visitAdd(User &I) {
474 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000475 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000476 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000477 void visitMul(User &I) {
478 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000479 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000480 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000481 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000482 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000483 }
484 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000485 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000486 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000487 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000488 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
489 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
490 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000491 void visitShl(User &I) { visitShift(I, ISD::SHL); }
492 void visitShr(User &I) {
493 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000494 }
495
496 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
497 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
498 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
499 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
500 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
501 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
502 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
503
504 void visitGetElementPtr(User &I);
505 void visitCast(User &I);
506 void visitSelect(User &I);
507 //
508
509 void visitMalloc(MallocInst &I);
510 void visitFree(FreeInst &I);
511 void visitAlloca(AllocaInst &I);
512 void visitLoad(LoadInst &I);
513 void visitStore(StoreInst &I);
514 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
515 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000516 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000517 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000518
Chris Lattner1c08c712005-01-07 07:47:53 +0000519 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000520 void visitVAArg(VAArgInst &I);
521 void visitVAEnd(CallInst &I);
522 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000523 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000524
Chris Lattner7041ee32005-01-11 05:56:49 +0000525 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000526
527 void visitUserOp1(Instruction &I) {
528 assert(0 && "UserOp1 should not exist at instruction selection time!");
529 abort();
530 }
531 void visitUserOp2(Instruction &I) {
532 assert(0 && "UserOp2 should not exist at instruction selection time!");
533 abort();
534 }
535};
536} // end namespace llvm
537
538void SelectionDAGLowering::visitRet(ReturnInst &I) {
539 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000540 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000541 return;
542 }
Nate Begemanee625572006-01-27 21:09:22 +0000543 std::vector<SDOperand> NewValues;
544 NewValues.push_back(getRoot());
545 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
546 SDOperand RetOp = getValue(I.getOperand(i));
547
548 // If this is an integer return value, we need to promote it ourselves to
549 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
550 // than sign/zero.
551 if (MVT::isInteger(RetOp.getValueType()) &&
552 RetOp.getValueType() < MVT::i64) {
553 MVT::ValueType TmpVT;
554 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
555 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
556 else
557 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000558
Nate Begemanee625572006-01-27 21:09:22 +0000559 if (I.getOperand(i)->getType()->isSigned())
560 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
561 else
562 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
563 }
564 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000565 }
Nate Begemanee625572006-01-27 21:09:22 +0000566 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000567}
568
569void SelectionDAGLowering::visitBr(BranchInst &I) {
570 // Update machine-CFG edges.
571 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000572
573 // Figure out which block is immediately after the current one.
574 MachineBasicBlock *NextBlock = 0;
575 MachineFunction::iterator BBI = CurMBB;
576 if (++BBI != CurMBB->getParent()->end())
577 NextBlock = BBI;
578
579 if (I.isUnconditional()) {
580 // If this is not a fall-through branch, emit the branch.
581 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000582 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000583 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000584 } else {
585 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000586
587 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000588 if (Succ1MBB == NextBlock) {
589 // If the condition is false, fall through. This means we should branch
590 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000591 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000592 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000593 } else if (Succ0MBB == NextBlock) {
594 // If the condition is true, fall through. This means we should branch if
595 // the condition is false to Succ #1. Invert the condition first.
596 SDOperand True = DAG.getConstant(1, Cond.getValueType());
597 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000598 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000599 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000600 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000601 std::vector<SDOperand> Ops;
602 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000603 // If the false case is the current basic block, then this is a self
604 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
605 // adds an extra instruction in the loop. Instead, invert the
606 // condition and emit "Loop: ... br!cond Loop; br Out.
607 if (CurMBB == Succ1MBB) {
608 std::swap(Succ0MBB, Succ1MBB);
609 SDOperand True = DAG.getConstant(1, Cond.getValueType());
610 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
611 }
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000612 Ops.push_back(Cond);
613 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
614 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
615 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000616 }
617 }
618}
619
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000620void SelectionDAGLowering::visitSub(User &I) {
621 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000622 if (I.getType()->isFloatingPoint()) {
623 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
624 if (CFP->isExactlyValue(-0.0)) {
625 SDOperand Op2 = getValue(I.getOperand(1));
626 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
627 return;
628 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000629 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000630 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000631}
632
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000633void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
634 unsigned VecOp) {
635 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000636 SDOperand Op1 = getValue(I.getOperand(0));
637 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000638
Chris Lattnerb67eb912005-11-19 18:40:42 +0000639 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000640 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
641 } else if (Ty->isFloatingPoint()) {
642 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
643 } else {
644 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000645 unsigned NumElements = PTy->getNumElements();
646 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000647 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000648
649 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000650 // the Legalize pass does not have to deal with them. Similarly, if the
651 // abstract vector is going to turn into one that the target natively
652 // supports, generate that type now so that Legalize doesn't have to deal
653 // with that either. These steps ensure that Legalize only has to handle
654 // vector types in its Expand case.
655 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000656 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000657 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000658 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
659 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000660 } else {
661 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
662 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000663 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000664 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000665 }
Nate Begemane21ea612005-11-18 07:42:56 +0000666}
Chris Lattner2c49f272005-01-19 22:31:21 +0000667
Nate Begemane21ea612005-11-18 07:42:56 +0000668void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
669 SDOperand Op1 = getValue(I.getOperand(0));
670 SDOperand Op2 = getValue(I.getOperand(1));
671
672 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
673
Chris Lattner1c08c712005-01-07 07:47:53 +0000674 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
675}
676
677void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
678 ISD::CondCode UnsignedOpcode) {
679 SDOperand Op1 = getValue(I.getOperand(0));
680 SDOperand Op2 = getValue(I.getOperand(1));
681 ISD::CondCode Opcode = SignedOpcode;
682 if (I.getOperand(0)->getType()->isUnsigned())
683 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000684 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000685}
686
687void SelectionDAGLowering::visitSelect(User &I) {
688 SDOperand Cond = getValue(I.getOperand(0));
689 SDOperand TrueVal = getValue(I.getOperand(1));
690 SDOperand FalseVal = getValue(I.getOperand(2));
691 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
692 TrueVal, FalseVal));
693}
694
695void SelectionDAGLowering::visitCast(User &I) {
696 SDOperand N = getValue(I.getOperand(0));
697 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
698 MVT::ValueType DestTy = TLI.getValueType(I.getType());
699
700 if (N.getValueType() == DestTy) {
701 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000702 } else if (DestTy == MVT::i1) {
703 // Cast to bool is a comparison against zero, not truncation to zero.
704 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
705 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000706 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000707 } else if (isInteger(SrcTy)) {
708 if (isInteger(DestTy)) { // Int -> Int cast
709 if (DestTy < SrcTy) // Truncating cast?
710 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
711 else if (I.getOperand(0)->getType()->isSigned())
712 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
713 else
714 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
715 } else { // Int -> FP cast
716 if (I.getOperand(0)->getType()->isSigned())
717 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
718 else
719 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
720 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000722 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
723 if (isFloatingPoint(DestTy)) { // FP -> FP cast
724 if (DestTy < SrcTy) // Rounding cast?
725 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
726 else
727 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
728 } else { // FP -> Int cast.
729 if (I.getType()->isSigned())
730 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
731 else
732 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
733 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000734 }
735}
736
737void SelectionDAGLowering::visitGetElementPtr(User &I) {
738 SDOperand N = getValue(I.getOperand(0));
739 const Type *Ty = I.getOperand(0)->getType();
740 const Type *UIntPtrTy = TD.getIntPtrType();
741
742 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
743 OI != E; ++OI) {
744 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000745 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000746 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
747 if (Field) {
748 // N = N + Offset
749 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
750 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000751 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000752 }
753 Ty = StTy->getElementType(Field);
754 } else {
755 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000756
Chris Lattner7c0104b2005-11-09 04:45:33 +0000757 // If this is a constant subscript, handle it quickly.
758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
759 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000760
Chris Lattner7c0104b2005-11-09 04:45:33 +0000761 uint64_t Offs;
762 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
763 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
764 else
765 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
766 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
767 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000768 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000769
770 // N = N + Idx * ElementSize;
771 uint64_t ElementSize = TD.getTypeSize(Ty);
772 SDOperand IdxN = getValue(Idx);
773
774 // If the index is smaller or larger than intptr_t, truncate or extend
775 // it.
776 if (IdxN.getValueType() < N.getValueType()) {
777 if (Idx->getType()->isSigned())
778 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
779 else
780 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
781 } else if (IdxN.getValueType() > N.getValueType())
782 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
783
784 // If this is a multiply by a power of two, turn it into a shl
785 // immediately. This is a very common case.
786 if (isPowerOf2_64(ElementSize)) {
787 unsigned Amt = Log2_64(ElementSize);
788 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000789 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000790 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
791 continue;
792 }
793
794 SDOperand Scale = getIntPtrConstant(ElementSize);
795 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
796 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000797 }
798 }
799 setValue(&I, N);
800}
801
802void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
803 // If this is a fixed sized alloca in the entry block of the function,
804 // allocate it statically on the stack.
805 if (FuncInfo.StaticAllocaMap.count(&I))
806 return; // getValue will auto-populate this.
807
808 const Type *Ty = I.getAllocatedType();
809 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000810 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
811 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000812
813 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000814 MVT::ValueType IntPtr = TLI.getPointerTy();
815 if (IntPtr < AllocSize.getValueType())
816 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
817 else if (IntPtr > AllocSize.getValueType())
818 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000819
Chris Lattner68cd65e2005-01-22 23:04:37 +0000820 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000821 getIntPtrConstant(TySize));
822
823 // Handle alignment. If the requested alignment is less than or equal to the
824 // stack alignment, ignore it and round the size of the allocation up to the
825 // stack alignment size. If the size is greater than the stack alignment, we
826 // note this in the DYNAMIC_STACKALLOC node.
827 unsigned StackAlign =
828 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
829 if (Align <= StackAlign) {
830 Align = 0;
831 // Add SA-1 to the size.
832 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
833 getIntPtrConstant(StackAlign-1));
834 // Mask out the low bits for alignment purposes.
835 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
836 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
837 }
838
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000839 std::vector<MVT::ValueType> VTs;
840 VTs.push_back(AllocSize.getValueType());
841 VTs.push_back(MVT::Other);
842 std::vector<SDOperand> Ops;
843 Ops.push_back(getRoot());
844 Ops.push_back(AllocSize);
845 Ops.push_back(getIntPtrConstant(Align));
846 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000847 DAG.setRoot(setValue(&I, DSA).getValue(1));
848
849 // Inform the Frame Information that we have just allocated a variable-sized
850 // object.
851 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
852}
853
Chris Lattner36ce6912005-11-29 06:21:05 +0000854/// getStringValue - Turn an LLVM constant pointer that eventually points to a
855/// global into a string value. Return an empty string if we can't do it.
856///
Evan Cheng74d0aa92006-02-15 21:59:04 +0000857static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
858 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
859 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
860 if (Init->isString()) {
861 std::string Result = Init->getAsString();
862 if (Offset < Result.size()) {
863 // If we are pointing INTO The string, erase the beginning...
864 Result.erase(Result.begin(), Result.begin()+Offset);
865 return Result;
Chris Lattner36ce6912005-11-29 06:21:05 +0000866 }
867 }
868 }
869 return "";
870}
Chris Lattner1c08c712005-01-07 07:47:53 +0000871
872void SelectionDAGLowering::visitLoad(LoadInst &I) {
873 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000874
Chris Lattnerd3948112005-01-17 22:19:26 +0000875 SDOperand Root;
876 if (I.isVolatile())
877 Root = getRoot();
878 else {
879 // Do not serialize non-volatile loads against each other.
880 Root = DAG.getRoot();
881 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000882
883 const Type *Ty = I.getType();
884 SDOperand L;
885
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000886 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000887 unsigned NumElements = PTy->getNumElements();
888 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000889 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000890
891 // Immediately scalarize packed types containing only one element, so that
892 // the Legalize pass does not have to deal with them.
893 if (NumElements == 1) {
894 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000895 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
896 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000897 } else {
898 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
899 DAG.getSrcValue(I.getOperand(0)));
900 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000901 } else {
902 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
903 DAG.getSrcValue(I.getOperand(0)));
904 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000905 setValue(&I, L);
906
907 if (I.isVolatile())
908 DAG.setRoot(L.getValue(1));
909 else
910 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000911}
912
913
914void SelectionDAGLowering::visitStore(StoreInst &I) {
915 Value *SrcV = I.getOperand(0);
916 SDOperand Src = getValue(SrcV);
917 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000918 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000919 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000920}
921
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000922/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
923/// we want to emit this as a call to a named external function, return the name
924/// otherwise lower it and return null.
925const char *
926SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
927 switch (Intrinsic) {
928 case Intrinsic::vastart: visitVAStart(I); return 0;
929 case Intrinsic::vaend: visitVAEnd(I); return 0;
930 case Intrinsic::vacopy: visitVACopy(I); return 0;
931 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
932 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
933 case Intrinsic::setjmp:
934 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
935 break;
936 case Intrinsic::longjmp:
937 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
938 break;
939 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
940 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
941 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
942
943 case Intrinsic::readport:
944 case Intrinsic::readio: {
945 std::vector<MVT::ValueType> VTs;
946 VTs.push_back(TLI.getValueType(I.getType()));
947 VTs.push_back(MVT::Other);
948 std::vector<SDOperand> Ops;
949 Ops.push_back(getRoot());
950 Ops.push_back(getValue(I.getOperand(1)));
951 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
952 ISD::READPORT : ISD::READIO, VTs, Ops);
953
954 setValue(&I, Tmp);
955 DAG.setRoot(Tmp.getValue(1));
956 return 0;
957 }
958 case Intrinsic::writeport:
959 case Intrinsic::writeio:
960 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
961 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
962 getRoot(), getValue(I.getOperand(1)),
963 getValue(I.getOperand(2))));
964 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000965
Chris Lattner86cb6432005-12-13 17:40:33 +0000966 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000967 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
968 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000969
Jim Laskeyce72b172006-02-11 01:01:30 +0000970 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
971 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
972 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +0000973
Jim Laskeyce72b172006-02-11 01:01:30 +0000974 // Input Chain
975 Ops.push_back(getRoot());
976
977 // line number
978 Ops.push_back(getValue(I.getOperand(2)));
979
980 // column
981 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner36ce6912005-11-29 06:21:05 +0000982
Jim Laskeyd96185a2006-02-13 12:50:39 +0000983 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskeyce72b172006-02-11 01:01:30 +0000984 assert(DD && "Not a debug information descriptor");
985 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
986 assert(CompileUnit && "Not a compile unit");
987 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
988 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
989
990 if (Ops.size() == 5) // Found filename/workingdir.
991 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +0000992 }
993
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000994 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000995 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000996 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000997 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000998 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
999 return "llvm_dbg_region_start";
1000 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_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001004 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1005 return "llvm_dbg_region_end";
1006 if (I.getType() != Type::VoidTy)
1007 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1008 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001009 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001010 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1011 return "llvm_dbg_subprogram";
1012 if (I.getType() != Type::VoidTy)
1013 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1014 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001015 case Intrinsic::dbg_declare:
1016 if (I.getType() != Type::VoidTy)
1017 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1018 return 0;
1019
Reid Spencer0b118202006-01-16 21:12:35 +00001020 case Intrinsic::isunordered_f32:
1021 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001022 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1023 getValue(I.getOperand(2)), ISD::SETUO));
1024 return 0;
1025
Reid Spencer0b118202006-01-16 21:12:35 +00001026 case Intrinsic::sqrt_f32:
1027 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001028 setValue(&I, DAG.getNode(ISD::FSQRT,
1029 getValue(I.getOperand(1)).getValueType(),
1030 getValue(I.getOperand(1))));
1031 return 0;
1032 case Intrinsic::pcmarker: {
1033 SDOperand Tmp = getValue(I.getOperand(1));
1034 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1035 return 0;
1036 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001037 case Intrinsic::readcyclecounter: {
1038 std::vector<MVT::ValueType> VTs;
1039 VTs.push_back(MVT::i64);
1040 VTs.push_back(MVT::Other);
1041 std::vector<SDOperand> Ops;
1042 Ops.push_back(getRoot());
1043 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1044 setValue(&I, Tmp);
1045 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001046 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001047 }
Nate Begemand88fc032006-01-14 03:14:10 +00001048 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001049 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001050 case Intrinsic::bswap_i64:
1051 setValue(&I, DAG.getNode(ISD::BSWAP,
1052 getValue(I.getOperand(1)).getValueType(),
1053 getValue(I.getOperand(1))));
1054 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001055 case Intrinsic::cttz_i8:
1056 case Intrinsic::cttz_i16:
1057 case Intrinsic::cttz_i32:
1058 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001059 setValue(&I, DAG.getNode(ISD::CTTZ,
1060 getValue(I.getOperand(1)).getValueType(),
1061 getValue(I.getOperand(1))));
1062 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001063 case Intrinsic::ctlz_i8:
1064 case Intrinsic::ctlz_i16:
1065 case Intrinsic::ctlz_i32:
1066 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001067 setValue(&I, DAG.getNode(ISD::CTLZ,
1068 getValue(I.getOperand(1)).getValueType(),
1069 getValue(I.getOperand(1))));
1070 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001071 case Intrinsic::ctpop_i8:
1072 case Intrinsic::ctpop_i16:
1073 case Intrinsic::ctpop_i32:
1074 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001075 setValue(&I, DAG.getNode(ISD::CTPOP,
1076 getValue(I.getOperand(1)).getValueType(),
1077 getValue(I.getOperand(1))));
1078 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001079 case Intrinsic::stacksave: {
1080 std::vector<MVT::ValueType> VTs;
1081 VTs.push_back(TLI.getPointerTy());
1082 VTs.push_back(MVT::Other);
1083 std::vector<SDOperand> Ops;
1084 Ops.push_back(getRoot());
1085 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1086 setValue(&I, Tmp);
1087 DAG.setRoot(Tmp.getValue(1));
1088 return 0;
1089 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001090 case Intrinsic::stackrestore: {
1091 SDOperand Tmp = getValue(I.getOperand(1));
1092 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001093 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001094 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001095 case Intrinsic::prefetch:
1096 // FIXME: Currently discarding prefetches.
1097 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001098 default:
1099 std::cerr << I;
1100 assert(0 && "This intrinsic is not implemented yet!");
1101 return 0;
1102 }
1103}
1104
1105
Chris Lattner1c08c712005-01-07 07:47:53 +00001106void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001107 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001108 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001109 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001110 if (unsigned IID = F->getIntrinsicID()) {
1111 RenameFn = visitIntrinsicCall(I, IID);
1112 if (!RenameFn)
1113 return;
1114 } else { // Not an LLVM intrinsic.
1115 const std::string &Name = F->getName();
1116 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001117 if (I.getNumOperands() == 2 && // Basic sanity checks.
1118 I.getOperand(1)->getType()->isFloatingPoint() &&
1119 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001120 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001121 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1122 return;
1123 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001124 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001125 if (I.getNumOperands() == 2 && // Basic sanity checks.
1126 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001127 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001128 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001129 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1130 return;
1131 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001132 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001133 if (I.getNumOperands() == 2 && // Basic sanity checks.
1134 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001135 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001136 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001137 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1138 return;
1139 }
1140 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001141 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001142 } else if (isa<InlineAsm>(I.getOperand(0))) {
1143 visitInlineAsm(I);
1144 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001145 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001146
Chris Lattner64e14b12005-01-08 22:48:57 +00001147 SDOperand Callee;
1148 if (!RenameFn)
1149 Callee = getValue(I.getOperand(0));
1150 else
1151 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001152 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001153 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001154 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1155 Value *Arg = I.getOperand(i);
1156 SDOperand ArgNode = getValue(Arg);
1157 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1158 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001159
Nate Begeman8e21e712005-03-26 01:29:23 +00001160 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1161 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001162
Chris Lattnercf5734d2005-01-08 19:26:18 +00001163 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001164 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001165 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001166 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001167 setValue(&I, Result.first);
1168 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001169}
1170
Chris Lattner864635a2006-02-22 22:37:12 +00001171SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1172 SDOperand &Chain, SDOperand &Flag) {
1173 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1174 Chain = Val.getValue(1);
1175 Flag = Val.getValue(2);
1176
1177 // If the result was expanded, copy from the top part.
1178 if (Regs.size() > 1) {
1179 assert(Regs.size() == 2 &&
1180 "Cannot expand to more than 2 elts yet!");
1181 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1182 Chain = Val.getValue(1);
1183 Flag = Val.getValue(2);
1184 return DAG.getNode(ISD::MERGE_VALUES, ValueVT, Val, Hi);
1185 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001186
Chris Lattner864635a2006-02-22 22:37:12 +00001187 // Otherwise, if the return value was promoted, truncate it to the
1188 // appropriate type.
1189 if (RegVT == ValueVT)
1190 return Val;
1191
1192 if (MVT::isInteger(RegVT))
1193 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1194 else
1195 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1196}
1197
1198
1199
1200/// isAllocatableRegister - If the specified register is safe to allocate,
1201/// i.e. it isn't a stack pointer or some other special register, return the
1202/// register class for the register. Otherwise, return null.
1203static const TargetRegisterClass *
1204isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1205 const MRegisterInfo *MRI) {
1206 for (MRegisterInfo::regclass_iterator RC = MRI->regclass_begin(),
1207 E = MRI->regclass_end(); RC != E; ++RC) {
1208 // NOTE: This isn't ideal. In particular, this might allocate the
1209 // frame pointer in functions that need it (due to them not being taken
1210 // out of allocation, because a variable sized allocation hasn't been seen
1211 // yet). This is a slight code pessimization, but should still work.
1212 for (TargetRegisterClass::iterator I = (*RC)->allocation_order_begin(MF),
1213 E = (*RC)->allocation_order_end(MF); I != E; ++I)
1214 if (*I == Reg)
1215 return *RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001216 }
1217 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001218}
1219
1220RegsForValue SelectionDAGLowering::
1221GetRegistersForValue(const std::string &ConstrCode,
1222 MVT::ValueType VT, bool isOutReg, bool isInReg,
1223 std::set<unsigned> &OutputRegs,
1224 std::set<unsigned> &InputRegs) {
1225 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1226 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1227 std::vector<unsigned> Regs;
1228
1229 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1230 MVT::ValueType RegVT;
1231 MVT::ValueType ValueVT = VT;
1232
1233 if (PhysReg.first) {
1234 if (VT == MVT::Other)
1235 ValueVT = *PhysReg.second->vt_begin();
1236 RegVT = VT;
1237
1238 // This is a explicit reference to a physical register.
1239 Regs.push_back(PhysReg.first);
1240
1241 // If this is an expanded reference, add the rest of the regs to Regs.
1242 if (NumRegs != 1) {
1243 RegVT = *PhysReg.second->vt_begin();
1244 TargetRegisterClass::iterator I = PhysReg.second->begin();
1245 TargetRegisterClass::iterator E = PhysReg.second->end();
1246 for (; *I != PhysReg.first; ++I)
1247 assert(I != E && "Didn't find reg!");
1248
1249 // Already added the first reg.
1250 --NumRegs; ++I;
1251 for (; NumRegs; --NumRegs, ++I) {
1252 assert(I != E && "Ran out of registers to allocate!");
1253 Regs.push_back(*I);
1254 }
1255 }
1256 return RegsForValue(Regs, RegVT, ValueVT);
1257 }
1258
1259 // This is a reference to a register class. Allocate NumRegs consecutive,
1260 // available, registers from the class.
1261 std::vector<unsigned> RegClassRegs =
1262 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1263
1264 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1265 MachineFunction &MF = *CurMBB->getParent();
1266 unsigned NumAllocated = 0;
1267 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1268 unsigned Reg = RegClassRegs[i];
1269 // See if this register is available.
1270 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1271 (isInReg && InputRegs.count(Reg))) { // Already used.
1272 // Make sure we find consecutive registers.
1273 NumAllocated = 0;
1274 continue;
1275 }
1276
1277 // Check to see if this register is allocatable (i.e. don't give out the
1278 // stack pointer).
1279 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, MRI);
1280 if (!RC) {
1281 // Make sure we find consecutive registers.
1282 NumAllocated = 0;
1283 continue;
1284 }
1285
1286 // Okay, this register is good, we can use it.
1287 ++NumAllocated;
1288
1289 // If we allocated enough consecutive
1290 if (NumAllocated == NumRegs) {
1291 unsigned RegStart = (i-NumAllocated)+1;
1292 unsigned RegEnd = i+1;
1293 // Mark all of the allocated registers used.
1294 for (unsigned i = RegStart; i != RegEnd; ++i) {
1295 unsigned Reg = RegClassRegs[i];
1296 Regs.push_back(Reg);
1297 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1298 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1299 }
1300
1301 return RegsForValue(Regs, *RC->vt_begin(), VT);
1302 }
1303 }
1304
1305 // Otherwise, we couldn't allocate enough registers for this.
1306 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001307}
1308
Chris Lattner864635a2006-02-22 22:37:12 +00001309
Chris Lattnerce7518c2006-01-26 22:24:51 +00001310/// visitInlineAsm - Handle a call to an InlineAsm object.
1311///
1312void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1313 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1314
1315 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1316 MVT::Other);
1317
1318 // Note, we treat inline asms both with and without side-effects as the same.
1319 // If an inline asm doesn't have side effects and doesn't access memory, we
1320 // could not choose to not chain it.
1321 bool hasSideEffects = IA->hasSideEffects();
1322
Chris Lattner2cc2f662006-02-01 01:28:23 +00001323 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001324 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001325
1326 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1327 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1328 /// if it is a def of that register.
1329 std::vector<SDOperand> AsmNodeOperands;
1330 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1331 AsmNodeOperands.push_back(AsmStr);
1332
1333 SDOperand Chain = getRoot();
1334 SDOperand Flag;
1335
Chris Lattner4e4b5762006-02-01 18:59:47 +00001336 // We fully assign registers here at isel time. This is not optimal, but
1337 // should work. For register classes that correspond to LLVM classes, we
1338 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1339 // over the constraints, collecting fixed registers that we know we can't use.
1340 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001341 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001342 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1343 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1344 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001345
Chris Lattner1efa40f2006-02-22 00:56:39 +00001346 MVT::ValueType OpVT;
1347
1348 // Compute the value type for each operand and add it to ConstraintVTs.
1349 switch (Constraints[i].Type) {
1350 case InlineAsm::isOutput:
1351 if (!Constraints[i].isIndirectOutput) {
1352 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1353 OpVT = TLI.getValueType(I.getType());
1354 } else {
1355 Value *CallOperand = I.getOperand(OpNum);
1356 const Type *OpTy = CallOperand->getType();
1357 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1358 OpNum++; // Consumes a call operand.
1359 }
1360 break;
1361 case InlineAsm::isInput:
1362 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1363 OpNum++; // Consumes a call operand.
1364 break;
1365 case InlineAsm::isClobber:
1366 OpVT = MVT::Other;
1367 break;
1368 }
1369
1370 ConstraintVTs.push_back(OpVT);
1371
Chris Lattner864635a2006-02-22 22:37:12 +00001372 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1373 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001374
Chris Lattner864635a2006-02-22 22:37:12 +00001375 // Build a list of regs that this operand uses. This always has a single
1376 // element for promoted/expanded operands.
1377 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1378 false, false,
1379 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001380
1381 switch (Constraints[i].Type) {
1382 case InlineAsm::isOutput:
1383 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001384 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001385 // If this is an early-clobber output, it cannot be assigned to the same
1386 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001387 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001388 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001389 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001390 case InlineAsm::isInput:
1391 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001392 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001393 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001394 case InlineAsm::isClobber:
1395 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001396 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1397 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001398 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001399 }
1400 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001401
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001402 // Loop over all of the inputs, copying the operand values into the
1403 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001404 RegsForValue RetValRegs;
1405 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001406 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001407
Chris Lattner6656dd12006-01-31 02:03:41 +00001408 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001409 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1410 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001411
Chris Lattner2cc2f662006-02-01 01:28:23 +00001412 switch (Constraints[i].Type) {
1413 case InlineAsm::isOutput: {
Chris Lattner864635a2006-02-22 22:37:12 +00001414 // If this is an early-clobber output, or if there is an input
1415 // constraint that matches this, we need to reserve the input register
1416 // so no other inputs allocate to it.
1417 bool UsesInputRegister = false;
1418 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1419 UsesInputRegister = true;
1420
1421 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001422 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001423 RegsForValue Regs =
1424 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1425 true, UsesInputRegister,
1426 OutputRegs, InputRegs);
1427 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001428
Chris Lattner2cc2f662006-02-01 01:28:23 +00001429 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001430 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001431 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001432 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001433 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001434 } else {
Chris Lattner1efa40f2006-02-22 00:56:39 +00001435 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner864635a2006-02-22 22:37:12 +00001436 IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001437 OpNum++; // Consumes a call operand.
1438 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001439
1440 // Add information to the INLINEASM node to know that this register is
1441 // set.
Chris Lattner6656dd12006-01-31 02:03:41 +00001442
Chris Lattner864635a2006-02-22 22:37:12 +00001443 // FIXME:
1444 // FIXME: Handle multiple regs here.
1445 // FIXME:
1446 unsigned DestReg = Regs.Regs[0];
1447 AsmNodeOperands.push_back(DAG.getRegister(DestReg, Regs.RegVT));
1448 AsmNodeOperands.push_back(DAG.getConstant(2, MVT::i32)); // ISDEF
Chris Lattner6656dd12006-01-31 02:03:41 +00001449 break;
1450 }
1451 case InlineAsm::isInput: {
Chris Lattner1efa40f2006-02-22 00:56:39 +00001452 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001453 OpNum++; // Consumes a call operand.
Chris Lattner2223aea2006-02-02 00:25:23 +00001454
Chris Lattner3d81fee2006-02-04 02:16:44 +00001455 SDOperand ResOp;
1456 unsigned ResOpType;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001457 SDOperand InOperandVal = getValue(CallOperand);
Chris Lattner3d81fee2006-02-04 02:16:44 +00001458
Chris Lattner2223aea2006-02-02 00:25:23 +00001459 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1460 // If this is required to match an output register we have already set,
1461 // just use its register.
1462 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner864635a2006-02-22 22:37:12 +00001463 unsigned SrcReg;
Chris Lattner2223aea2006-02-02 00:25:23 +00001464 SrcReg = cast<RegisterSDNode>(AsmNodeOperands[OperandNo*2+2])->getReg();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001465 ResOp = DAG.getRegister(SrcReg, ConstraintVTs[i]);
Chris Lattner3d81fee2006-02-04 02:16:44 +00001466 ResOpType = 1;
1467
1468 Chain = DAG.getCopyToReg(Chain, SrcReg, InOperandVal, Flag);
1469 Flag = Chain.getValue(1);
Chris Lattner2223aea2006-02-02 00:25:23 +00001470 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00001471 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
Chris Lattner3d81fee2006-02-04 02:16:44 +00001472 if (ConstraintCode.size() == 1) // not a physreg name.
1473 CTy = TLI.getConstraintType(ConstraintCode[0]);
1474
1475 switch (CTy) {
1476 default: assert(0 && "Unknown constraint type! FAIL!");
1477 case TargetLowering::C_RegisterClass: {
Chris Lattner864635a2006-02-22 22:37:12 +00001478 // Copy the input into the appropriate registers.
1479 RegsForValue InRegs =
1480 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1481 false, true, OutputRegs, InputRegs);
Chris Lattner3d81fee2006-02-04 02:16:44 +00001482 // FIXME: should be match fail.
Chris Lattner864635a2006-02-22 22:37:12 +00001483 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1484
1485 if (InRegs.Regs.size() == 1) {
1486 // If there is a single register and the types differ, this must be
1487 // a promotion.
1488 if (InRegs.RegVT != InRegs.ValueVT) {
1489 if (MVT::isInteger(InRegs.RegVT))
1490 InOperandVal = DAG.getNode(ISD::ANY_EXTEND, InRegs.RegVT,
1491 InOperandVal);
1492 else
1493 InOperandVal = DAG.getNode(ISD::FP_EXTEND, InRegs.RegVT,
1494 InOperandVal);
1495 }
1496 Chain = DAG.getCopyToReg(Chain, InRegs.Regs[0], InOperandVal, Flag);
1497 Flag = Chain.getValue(1);
1498
1499 ResOp = DAG.getRegister(InRegs.Regs[0], InRegs.RegVT);
1500 } else {
1501 for (unsigned i = 0, e = InRegs.Regs.size(); i != e; ++i) {
1502 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, InRegs.RegVT,
1503 InOperandVal,
1504 DAG.getConstant(i, MVT::i32));
1505 Chain = DAG.getCopyToReg(Chain, InRegs.Regs[i], Part, Flag);
1506 Flag = Chain.getValue(1);
1507 }
1508 ResOp = DAG.getRegister(InRegs.Regs[0], InRegs.RegVT);
1509 }
Chris Lattner3d81fee2006-02-04 02:16:44 +00001510
Chris Lattner3d81fee2006-02-04 02:16:44 +00001511 ResOpType = 1;
1512 break;
1513 }
1514 case TargetLowering::C_Other:
1515 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1516 assert(0 && "MATCH FAIL!");
1517 ResOp = InOperandVal;
1518 ResOpType = 3;
1519 break;
1520 }
Chris Lattner2223aea2006-02-02 00:25:23 +00001521 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001522
Chris Lattner3d81fee2006-02-04 02:16:44 +00001523 // Add information to the INLINEASM node to know about this input.
1524 AsmNodeOperands.push_back(ResOp);
Chris Lattnerdc19b702006-02-04 02:26:14 +00001525 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
Chris Lattner6656dd12006-01-31 02:03:41 +00001526 break;
1527 }
1528 case InlineAsm::isClobber:
1529 // Nothing to do.
1530 break;
1531 }
1532 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001533
1534 // Finish up input operands.
1535 AsmNodeOperands[0] = Chain;
1536 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1537
1538 std::vector<MVT::ValueType> VTs;
1539 VTs.push_back(MVT::Other);
1540 VTs.push_back(MVT::Flag);
1541 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1542 Flag = Chain.getValue(1);
1543
Chris Lattner6656dd12006-01-31 02:03:41 +00001544 // If this asm returns a register value, copy the result from that register
1545 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001546 if (!RetValRegs.Regs.empty())
1547 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001548
Chris Lattner6656dd12006-01-31 02:03:41 +00001549 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1550
1551 // Process indirect outputs, first output all of the flagged copies out of
1552 // physregs.
1553 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001554 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001555 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001556 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1557 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001558 }
1559
1560 // Emit the non-flagged stores from the physregs.
1561 std::vector<SDOperand> OutChains;
1562 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1563 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1564 StoresToEmit[i].first,
1565 getValue(StoresToEmit[i].second),
1566 DAG.getSrcValue(StoresToEmit[i].second)));
1567 if (!OutChains.empty())
1568 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001569 DAG.setRoot(Chain);
1570}
1571
1572
Chris Lattner1c08c712005-01-07 07:47:53 +00001573void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1574 SDOperand Src = getValue(I.getOperand(0));
1575
1576 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001577
1578 if (IntPtr < Src.getValueType())
1579 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1580 else if (IntPtr > Src.getValueType())
1581 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001582
1583 // Scale the source by the type size.
1584 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1585 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1586 Src, getIntPtrConstant(ElementSize));
1587
1588 std::vector<std::pair<SDOperand, const Type*> > Args;
1589 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001590
1591 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001592 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001593 DAG.getExternalSymbol("malloc", IntPtr),
1594 Args, DAG);
1595 setValue(&I, Result.first); // Pointers always fit in registers
1596 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001597}
1598
1599void SelectionDAGLowering::visitFree(FreeInst &I) {
1600 std::vector<std::pair<SDOperand, const Type*> > Args;
1601 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1602 TLI.getTargetData().getIntPtrType()));
1603 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001604 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001605 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001606 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1607 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001608}
1609
Chris Lattner025c39b2005-08-26 20:54:47 +00001610// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1611// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1612// instructions are special in various ways, which require special support to
1613// insert. The specified MachineInstr is created but not inserted into any
1614// basic blocks, and the scheduler passes ownership of it to this method.
1615MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1616 MachineBasicBlock *MBB) {
1617 std::cerr << "If a target marks an instruction with "
1618 "'usesCustomDAGSchedInserter', it must implement "
1619 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1620 abort();
1621 return 0;
1622}
1623
Chris Lattner39ae3622005-01-09 00:00:49 +00001624void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001625 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1626 getValue(I.getOperand(1)),
1627 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001628}
1629
1630void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001631 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1632 getValue(I.getOperand(0)),
1633 DAG.getSrcValue(I.getOperand(0)));
1634 setValue(&I, V);
1635 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001636}
1637
1638void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001639 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1640 getValue(I.getOperand(1)),
1641 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001642}
1643
1644void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001645 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1646 getValue(I.getOperand(1)),
1647 getValue(I.getOperand(2)),
1648 DAG.getSrcValue(I.getOperand(1)),
1649 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001650}
1651
Chris Lattner39ae3622005-01-09 00:00:49 +00001652// It is always conservatively correct for llvm.returnaddress and
1653// llvm.frameaddress to return 0.
1654std::pair<SDOperand, SDOperand>
1655TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1656 unsigned Depth, SelectionDAG &DAG) {
1657 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001658}
1659
Chris Lattner50381b62005-05-14 05:50:48 +00001660SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001661 assert(0 && "LowerOperation not implemented for this target!");
1662 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001663 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001664}
1665
Nate Begeman0aed7842006-01-28 03:14:31 +00001666SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1667 SelectionDAG &DAG) {
1668 assert(0 && "CustomPromoteOperation not implemented for this target!");
1669 abort();
1670 return SDOperand();
1671}
1672
Chris Lattner39ae3622005-01-09 00:00:49 +00001673void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1674 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1675 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001676 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001677 setValue(&I, Result.first);
1678 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001679}
1680
Evan Cheng74d0aa92006-02-15 21:59:04 +00001681/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001682/// operand.
1683static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001684 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001685 MVT::ValueType CurVT = VT;
1686 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1687 uint64_t Val = C->getValue() & 255;
1688 unsigned Shift = 8;
1689 while (CurVT != MVT::i8) {
1690 Val = (Val << Shift) | Val;
1691 Shift <<= 1;
1692 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001693 }
1694 return DAG.getConstant(Val, VT);
1695 } else {
1696 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1697 unsigned Shift = 8;
1698 while (CurVT != MVT::i8) {
1699 Value =
1700 DAG.getNode(ISD::OR, VT,
1701 DAG.getNode(ISD::SHL, VT, Value,
1702 DAG.getConstant(Shift, MVT::i8)), Value);
1703 Shift <<= 1;
1704 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001705 }
1706
1707 return Value;
1708 }
1709}
1710
Evan Cheng74d0aa92006-02-15 21:59:04 +00001711/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1712/// used when a memcpy is turned into a memset when the source is a constant
1713/// string ptr.
1714static SDOperand getMemsetStringVal(MVT::ValueType VT,
1715 SelectionDAG &DAG, TargetLowering &TLI,
1716 std::string &Str, unsigned Offset) {
1717 MVT::ValueType CurVT = VT;
1718 uint64_t Val = 0;
1719 unsigned MSB = getSizeInBits(VT) / 8;
1720 if (TLI.isLittleEndian())
1721 Offset = Offset + MSB - 1;
1722 for (unsigned i = 0; i != MSB; ++i) {
1723 Val = (Val << 8) | Str[Offset];
1724 Offset += TLI.isLittleEndian() ? -1 : 1;
1725 }
1726 return DAG.getConstant(Val, VT);
1727}
1728
Evan Cheng1db92f92006-02-14 08:22:34 +00001729/// getMemBasePlusOffset - Returns base and offset node for the
1730static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1731 SelectionDAG &DAG, TargetLowering &TLI) {
1732 MVT::ValueType VT = Base.getValueType();
1733 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1734}
1735
Evan Chengc4f8eee2006-02-14 20:12:38 +00001736/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001737/// to replace the memset / memcpy is below the threshold. It also returns the
1738/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001739static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1740 unsigned Limit, uint64_t Size,
1741 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001742 MVT::ValueType VT;
1743
1744 if (TLI.allowsUnalignedMemoryAccesses()) {
1745 VT = MVT::i64;
1746 } else {
1747 switch (Align & 7) {
1748 case 0:
1749 VT = MVT::i64;
1750 break;
1751 case 4:
1752 VT = MVT::i32;
1753 break;
1754 case 2:
1755 VT = MVT::i16;
1756 break;
1757 default:
1758 VT = MVT::i8;
1759 break;
1760 }
1761 }
1762
Evan Cheng80e89d72006-02-14 09:11:59 +00001763 MVT::ValueType LVT = MVT::i64;
1764 while (!TLI.isTypeLegal(LVT))
1765 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1766 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001767
Evan Cheng80e89d72006-02-14 09:11:59 +00001768 if (VT > LVT)
1769 VT = LVT;
1770
Evan Chengdea72452006-02-14 23:05:54 +00001771 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001772 while (Size != 0) {
1773 unsigned VTSize = getSizeInBits(VT) / 8;
1774 while (VTSize > Size) {
1775 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001776 VTSize >>= 1;
1777 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001778 assert(MVT::isInteger(VT));
1779
1780 if (++NumMemOps > Limit)
1781 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001782 MemOps.push_back(VT);
1783 Size -= VTSize;
1784 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001785
1786 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001787}
1788
Chris Lattner7041ee32005-01-11 05:56:49 +00001789void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001790 SDOperand Op1 = getValue(I.getOperand(1));
1791 SDOperand Op2 = getValue(I.getOperand(2));
1792 SDOperand Op3 = getValue(I.getOperand(3));
1793 SDOperand Op4 = getValue(I.getOperand(4));
1794 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1795 if (Align == 0) Align = 1;
1796
1797 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1798 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001799
1800 // Expand memset / memcpy to a series of load / store ops
1801 // if the size operand falls below a certain threshold.
1802 std::vector<SDOperand> OutChains;
1803 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001804 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001805 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001806 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1807 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00001808 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00001809 unsigned Offset = 0;
1810 for (unsigned i = 0; i < NumMemOps; i++) {
1811 MVT::ValueType VT = MemOps[i];
1812 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00001813 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00001814 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1815 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00001816 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1817 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00001818 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00001819 Offset += VTSize;
1820 }
Evan Cheng1db92f92006-02-14 08:22:34 +00001821 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001822 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00001823 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001824 case ISD::MEMCPY: {
1825 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1826 Size->getValue(), Align, TLI)) {
1827 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00001828 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001829 GlobalAddressSDNode *G = NULL;
1830 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00001831 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001832
1833 if (Op2.getOpcode() == ISD::GlobalAddress)
1834 G = cast<GlobalAddressSDNode>(Op2);
1835 else if (Op2.getOpcode() == ISD::ADD &&
1836 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1837 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1838 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00001839 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00001840 }
1841 if (G) {
1842 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00001843 if (GV) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001844 Str = getStringValue(GV);
Evan Chengcffbb512006-02-16 23:11:42 +00001845 if (!Str.empty()) {
1846 CopyFromStr = true;
1847 SrcOff += SrcDelta;
1848 }
1849 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00001850 }
1851
Evan Chengc080d6f2006-02-15 01:54:51 +00001852 for (unsigned i = 0; i < NumMemOps; i++) {
1853 MVT::ValueType VT = MemOps[i];
1854 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001855 SDOperand Value, Chain, Store;
1856
Evan Chengcffbb512006-02-16 23:11:42 +00001857 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001858 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1859 Chain = getRoot();
1860 Store =
1861 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1862 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1863 DAG.getSrcValue(I.getOperand(1), DstOff));
1864 } else {
1865 Value = DAG.getLoad(VT, getRoot(),
1866 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1867 DAG.getSrcValue(I.getOperand(2), SrcOff));
1868 Chain = Value.getValue(1);
1869 Store =
1870 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1871 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1872 DAG.getSrcValue(I.getOperand(1), DstOff));
1873 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001874 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00001875 SrcOff += VTSize;
1876 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00001877 }
1878 }
1879 break;
1880 }
1881 }
1882
1883 if (!OutChains.empty()) {
1884 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1885 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00001886 }
1887 }
1888
Chris Lattner7041ee32005-01-11 05:56:49 +00001889 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001890 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00001891 Ops.push_back(Op1);
1892 Ops.push_back(Op2);
1893 Ops.push_back(Op3);
1894 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00001895 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001896}
1897
Chris Lattner7041ee32005-01-11 05:56:49 +00001898//===----------------------------------------------------------------------===//
1899// SelectionDAGISel code
1900//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001901
1902unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1903 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1904}
1905
Chris Lattner495a0b52005-08-17 06:37:43 +00001906void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001907 // FIXME: we only modify the CFG to split critical edges. This
1908 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001909}
Chris Lattner1c08c712005-01-07 07:47:53 +00001910
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001911
1912/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1913/// casting to the type of GEPI.
1914static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1915 Value *Ptr, Value *PtrOffset) {
1916 if (V) return V; // Already computed.
1917
1918 BasicBlock::iterator InsertPt;
1919 if (BB == GEPI->getParent()) {
1920 // If insert into the GEP's block, insert right after the GEP.
1921 InsertPt = GEPI;
1922 ++InsertPt;
1923 } else {
1924 // Otherwise, insert at the top of BB, after any PHI nodes
1925 InsertPt = BB->begin();
1926 while (isa<PHINode>(InsertPt)) ++InsertPt;
1927 }
1928
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001929 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1930 // BB so that there is only one value live across basic blocks (the cast
1931 // operand).
1932 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1933 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1934 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1935
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001936 // Add the offset, cast it to the right type.
1937 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1938 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1939 return V = Ptr;
1940}
1941
1942
1943/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1944/// selection, we want to be a bit careful about some things. In particular, if
1945/// we have a GEP instruction that is used in a different block than it is
1946/// defined, the addressing expression of the GEP cannot be folded into loads or
1947/// stores that use it. In this case, decompose the GEP and move constant
1948/// indices into blocks that use it.
1949static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1950 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001951 // If this GEP is only used inside the block it is defined in, there is no
1952 // need to rewrite it.
1953 bool isUsedOutsideDefBB = false;
1954 BasicBlock *DefBB = GEPI->getParent();
1955 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1956 UI != E; ++UI) {
1957 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1958 isUsedOutsideDefBB = true;
1959 break;
1960 }
1961 }
1962 if (!isUsedOutsideDefBB) return;
1963
1964 // If this GEP has no non-zero constant indices, there is nothing we can do,
1965 // ignore it.
1966 bool hasConstantIndex = false;
1967 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1968 E = GEPI->op_end(); OI != E; ++OI) {
1969 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1970 if (CI->getRawValue()) {
1971 hasConstantIndex = true;
1972 break;
1973 }
1974 }
Chris Lattner3802c252005-12-11 09:05:13 +00001975 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1976 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001977
1978 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1979 // constant offset (which we now know is non-zero) and deal with it later.
1980 uint64_t ConstantOffset = 0;
1981 const Type *UIntPtrTy = TD.getIntPtrType();
1982 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1983 const Type *Ty = GEPI->getOperand(0)->getType();
1984
1985 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1986 E = GEPI->op_end(); OI != E; ++OI) {
1987 Value *Idx = *OI;
1988 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1989 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1990 if (Field)
1991 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1992 Ty = StTy->getElementType(Field);
1993 } else {
1994 Ty = cast<SequentialType>(Ty)->getElementType();
1995
1996 // Handle constant subscripts.
1997 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1998 if (CI->getRawValue() == 0) continue;
1999
2000 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2001 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2002 else
2003 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2004 continue;
2005 }
2006
2007 // Ptr = Ptr + Idx * ElementSize;
2008
2009 // Cast Idx to UIntPtrTy if needed.
2010 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2011
2012 uint64_t ElementSize = TD.getTypeSize(Ty);
2013 // Mask off bits that should not be set.
2014 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2015 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2016
2017 // Multiply by the element size and add to the base.
2018 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2019 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2020 }
2021 }
2022
2023 // Make sure that the offset fits in uintptr_t.
2024 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2025 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2026
2027 // Okay, we have now emitted all of the variable index parts to the BB that
2028 // the GEP is defined in. Loop over all of the using instructions, inserting
2029 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002030 // instruction to use the newly computed value, making GEPI dead. When the
2031 // user is a load or store instruction address, we emit the add into the user
2032 // block, otherwise we use a canonical version right next to the gep (these
2033 // won't be foldable as addresses, so we might as well share the computation).
2034
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002035 std::map<BasicBlock*,Value*> InsertedExprs;
2036 while (!GEPI->use_empty()) {
2037 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002038
2039 // If this use is not foldable into the addressing mode, use a version
2040 // emitted in the GEP block.
2041 Value *NewVal;
2042 if (!isa<LoadInst>(User) &&
2043 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2044 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2045 Ptr, PtrOffset);
2046 } else {
2047 // Otherwise, insert the code in the User's block so it can be folded into
2048 // any users in that block.
2049 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002050 User->getParent(), GEPI,
2051 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002052 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002053 User->replaceUsesOfWith(GEPI, NewVal);
2054 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002055
2056 // Finally, the GEP is dead, remove it.
2057 GEPI->eraseFromParent();
2058}
2059
Chris Lattner1c08c712005-01-07 07:47:53 +00002060bool SelectionDAGISel::runOnFunction(Function &Fn) {
2061 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2062 RegMap = MF.getSSARegMap();
2063 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2064
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002065 // First, split all critical edges for PHI nodes with incoming values that are
2066 // constants, this way the load of the constant into a vreg will not be placed
2067 // into MBBs that are used some other way.
2068 //
2069 // In this pass we also look for GEP instructions that are used across basic
2070 // blocks and rewrites them to improve basic-block-at-a-time selection.
2071 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002072 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2073 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002074 BasicBlock::iterator BBI;
2075 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002076 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2077 if (isa<Constant>(PN->getIncomingValue(i)))
2078 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002079
2080 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2081 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2082 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002083 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002084
Chris Lattner1c08c712005-01-07 07:47:53 +00002085 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2086
2087 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2088 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002089
Chris Lattner1c08c712005-01-07 07:47:53 +00002090 return true;
2091}
2092
2093
Chris Lattnerddb870b2005-01-13 17:59:43 +00002094SDOperand SelectionDAGISel::
2095CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002096 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002097 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002098 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002099 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002100
2101 // If this type is not legal, we must make sure to not create an invalid
2102 // register use.
2103 MVT::ValueType SrcVT = Op.getValueType();
2104 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2105 SelectionDAG &DAG = SDL.DAG;
2106 if (SrcVT == DestVT) {
2107 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2108 } else if (SrcVT < DestVT) {
2109 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002110 if (MVT::isFloatingPoint(SrcVT))
2111 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2112 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002113 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002114 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2115 } else {
2116 // The src value is expanded into multiple registers.
2117 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2118 Op, DAG.getConstant(0, MVT::i32));
2119 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2120 Op, DAG.getConstant(1, MVT::i32));
2121 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2122 return DAG.getCopyToReg(Op, Reg+1, Hi);
2123 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002124}
2125
Chris Lattner068a81e2005-01-17 17:15:02 +00002126void SelectionDAGISel::
2127LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2128 std::vector<SDOperand> &UnorderedChains) {
2129 // If this is the entry block, emit arguments.
2130 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002131 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002132 SDOperand OldRoot = SDL.DAG.getRoot();
2133 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002134
Chris Lattnerbf209482005-10-30 19:42:35 +00002135 unsigned a = 0;
2136 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2137 AI != E; ++AI, ++a)
2138 if (!AI->use_empty()) {
2139 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002140
Chris Lattnerbf209482005-10-30 19:42:35 +00002141 // If this argument is live outside of the entry block, insert a copy from
2142 // whereever we got it to the vreg that other BB's will reference it as.
2143 if (FuncInfo.ValueMap.count(AI)) {
2144 SDOperand Copy =
2145 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2146 UnorderedChains.push_back(Copy);
2147 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002148 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002149
2150 // Next, if the function has live ins that need to be copied into vregs,
2151 // emit the copies now, into the top of the block.
2152 MachineFunction &MF = SDL.DAG.getMachineFunction();
2153 if (MF.livein_begin() != MF.livein_end()) {
2154 SSARegMap *RegMap = MF.getSSARegMap();
2155 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2156 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2157 E = MF.livein_end(); LI != E; ++LI)
2158 if (LI->second)
2159 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2160 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002161 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002162
2163 // Finally, if the target has anything special to do, allow it to do so.
2164 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002165}
2166
2167
Chris Lattner1c08c712005-01-07 07:47:53 +00002168void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2169 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2170 FunctionLoweringInfo &FuncInfo) {
2171 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002172
2173 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002174
Chris Lattnerbf209482005-10-30 19:42:35 +00002175 // Lower any arguments needed in this block if this is the entry block.
2176 if (LLVMBB == &LLVMBB->getParent()->front())
2177 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002178
2179 BB = FuncInfo.MBBMap[LLVMBB];
2180 SDL.setCurrentBasicBlock(BB);
2181
2182 // Lower all of the non-terminator instructions.
2183 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2184 I != E; ++I)
2185 SDL.visit(*I);
2186
2187 // Ensure that all instructions which are used outside of their defining
2188 // blocks are available as virtual registers.
2189 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002190 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002191 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002192 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002193 UnorderedChains.push_back(
2194 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002195 }
2196
2197 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2198 // ensure constants are generated when needed. Remember the virtual registers
2199 // that need to be added to the Machine PHI nodes as input. We cannot just
2200 // directly add them, because expansion might result in multiple MBB's for one
2201 // BB. As such, the start of the BB might correspond to a different MBB than
2202 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002203 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002204
2205 // Emit constants only once even if used by multiple PHI nodes.
2206 std::map<Constant*, unsigned> ConstantsOut;
2207
2208 // Check successor nodes PHI nodes that expect a constant to be available from
2209 // this block.
2210 TerminatorInst *TI = LLVMBB->getTerminator();
2211 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2212 BasicBlock *SuccBB = TI->getSuccessor(succ);
2213 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2214 PHINode *PN;
2215
2216 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2217 // nodes and Machine PHI nodes, but the incoming operands have not been
2218 // emitted yet.
2219 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002220 (PN = dyn_cast<PHINode>(I)); ++I)
2221 if (!PN->use_empty()) {
2222 unsigned Reg;
2223 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2224 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2225 unsigned &RegOut = ConstantsOut[C];
2226 if (RegOut == 0) {
2227 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002228 UnorderedChains.push_back(
2229 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002230 }
2231 Reg = RegOut;
2232 } else {
2233 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002234 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002235 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002236 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2237 "Didn't codegen value into a register!??");
2238 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002239 UnorderedChains.push_back(
2240 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002241 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002242 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002243
Chris Lattnerf44fd882005-01-07 21:34:19 +00002244 // Remember that this register needs to added to the machine PHI node as
2245 // the input for this MBB.
2246 unsigned NumElements =
2247 TLI.getNumElements(TLI.getValueType(PN->getType()));
2248 for (unsigned i = 0, e = NumElements; i != e; ++i)
2249 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002250 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002251 }
2252 ConstantsOut.clear();
2253
Chris Lattnerddb870b2005-01-13 17:59:43 +00002254 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002255 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002256 SDOperand Root = SDL.getRoot();
2257 if (Root.getOpcode() != ISD::EntryToken) {
2258 unsigned i = 0, e = UnorderedChains.size();
2259 for (; i != e; ++i) {
2260 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2261 if (UnorderedChains[i].Val->getOperand(0) == Root)
2262 break; // Don't add the root if we already indirectly depend on it.
2263 }
2264
2265 if (i == e)
2266 UnorderedChains.push_back(Root);
2267 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002268 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2269 }
2270
Chris Lattner1c08c712005-01-07 07:47:53 +00002271 // Lower the terminator after the copies are emitted.
2272 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002273
2274 // Make sure the root of the DAG is up-to-date.
2275 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002276}
2277
2278void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2279 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002280 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002281 CurDAG = &DAG;
2282 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2283
2284 // First step, lower LLVM code to some DAG. This DAG may use operations and
2285 // types that are not supported by the target.
2286 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2287
Chris Lattneraf21d552005-10-10 16:47:10 +00002288 // Run the DAG combiner in pre-legalize mode.
2289 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002290
Chris Lattner1c08c712005-01-07 07:47:53 +00002291 DEBUG(std::cerr << "Lowered selection DAG:\n");
2292 DEBUG(DAG.dump());
2293
2294 // Second step, hack on the DAG until it only uses operations and types that
2295 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002296 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002297
2298 DEBUG(std::cerr << "Legalized selection DAG:\n");
2299 DEBUG(DAG.dump());
2300
Chris Lattneraf21d552005-10-10 16:47:10 +00002301 // Run the DAG combiner in post-legalize mode.
2302 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002303
Evan Chenga9c20912006-01-21 02:32:06 +00002304 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002305
Chris Lattnera33ef482005-03-30 01:10:47 +00002306 // Third, instruction select all of the operations to machine code, adding the
2307 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002308 InstructionSelectBasicBlock(DAG);
2309
Chris Lattner1c08c712005-01-07 07:47:53 +00002310 DEBUG(std::cerr << "Selected machine code:\n");
2311 DEBUG(BB->dump());
2312
Chris Lattnera33ef482005-03-30 01:10:47 +00002313 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002314 // PHI nodes in successors.
2315 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2316 MachineInstr *PHI = PHINodesToUpdate[i].first;
2317 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2318 "This is not a machine PHI node that we are updating!");
2319 PHI->addRegOperand(PHINodesToUpdate[i].second);
2320 PHI->addMachineBasicBlockOperand(BB);
2321 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002322
2323 // Finally, add the CFG edges from the last selected MBB to the successor
2324 // MBBs.
2325 TerminatorInst *TI = LLVMBB->getTerminator();
2326 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2327 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2328 BB->addSuccessor(Succ0MBB);
2329 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002330}
Evan Chenga9c20912006-01-21 02:32:06 +00002331
2332//===----------------------------------------------------------------------===//
2333/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2334/// target node in the graph.
2335void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2336 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002337 ScheduleDAG *SL = NULL;
2338
2339 switch (ISHeuristic) {
2340 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002341 case defaultScheduling:
2342 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2343 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2344 else /* TargetLowering::SchedulingForRegPressure */
2345 SL = createBURRListDAGScheduler(DAG, BB);
2346 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002347 case noScheduling:
2348 case simpleScheduling:
2349 case simpleNoItinScheduling:
2350 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2351 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002352 case listSchedulingBURR:
2353 SL = createBURRListDAGScheduler(DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002354 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002355 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002356 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002357}