blob: 4468b56ac71de6b580f4e5fb02ead534323c298b [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
45using namespace llvm;
46
Chris Lattner975f5c92005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000048static cl::opt<bool>
Evan Cheng739a6a42006-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 Lattnere05a4612005-01-12 03:41:21 +000054#else
Evan Cheng739a6a42006-01-21 02:32:06 +000055static const bool ViewISelDAGs = 0;
56static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000057#endif
58
Evan Chengc1e1d972006-01-23 07:01:07 +000059namespace {
60 cl::opt<SchedHeuristics>
61 ISHeuristic(
62 "sched",
63 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000064 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000065 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000066 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000068 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000069 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-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 Chenga6eff8a2006-01-25 09:12:57 +000076 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000077 "Bottom up register reduction list scheduling"),
Evan Chengc1e1d972006-01-23 07:01:07 +000078 clEnumValEnd));
79} // namespace
80
Chris Lattner6f87d182006-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);
Chris Lattner571d9642006-02-23 19:21:04 +0000116
117 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
118 /// specified value into the registers specified by this object. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag);
122
123 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
124 /// operand list. This adds the code marker and includes the number of
125 /// values added into it.
126 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
127 std::vector<SDOperand> &Ops);
Chris Lattner6f87d182006-02-22 22:37:12 +0000128 };
129}
Evan Chengc1e1d972006-01-23 07:01:07 +0000130
Chris Lattner7a60d912005-01-07 07:47:53 +0000131namespace llvm {
132 //===--------------------------------------------------------------------===//
133 /// FunctionLoweringInfo - This contains information that is global to a
134 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000135 class FunctionLoweringInfo {
136 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000137 TargetLowering &TLI;
138 Function &Fn;
139 MachineFunction &MF;
140 SSARegMap *RegMap;
141
142 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
143
144 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
145 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
146
147 /// ValueMap - Since we emit code for the function a basic block at a time,
148 /// we must remember which virtual registers hold the values for
149 /// cross-basic-block values.
150 std::map<const Value*, unsigned> ValueMap;
151
152 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
153 /// the entry block. This allows the allocas to be efficiently referenced
154 /// anywhere in the function.
155 std::map<const AllocaInst*, int> StaticAllocaMap;
156
157 unsigned MakeReg(MVT::ValueType VT) {
158 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
159 }
Misha Brukman835702a2005-04-21 22:36:52 +0000160
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 unsigned CreateRegForValue(const Value *V) {
162 MVT::ValueType VT = TLI.getValueType(V->getType());
163 // The common case is that we will only create one register for this
164 // value. If we have that case, create and return the virtual register.
165 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000166 if (NV == 1) {
167 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000168 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000169 }
Misha Brukman835702a2005-04-21 22:36:52 +0000170
Chris Lattner7a60d912005-01-07 07:47:53 +0000171 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000172 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000173 unsigned NT = VT-1; // Find the type to use.
174 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
175 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000176
Chris Lattner7a60d912005-01-07 07:47:53 +0000177 unsigned R = MakeReg((MVT::ValueType)NT);
178 for (unsigned i = 1; i != NV; ++i)
179 MakeReg((MVT::ValueType)NT);
180 return R;
181 }
Misha Brukman835702a2005-04-21 22:36:52 +0000182
Chris Lattner7a60d912005-01-07 07:47:53 +0000183 unsigned InitializeRegForValue(const Value *V) {
184 unsigned &R = ValueMap[V];
185 assert(R == 0 && "Already initialized this value register!");
186 return R = CreateRegForValue(V);
187 }
188 };
189}
190
191/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
192/// PHI nodes or outside of the basic block that defines it.
193static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194 if (isa<PHINode>(I)) return true;
195 BasicBlock *BB = I->getParent();
196 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
198 return true;
199 return false;
200}
201
Chris Lattner6871b232005-10-30 19:42:35 +0000202/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
203/// entry block, return true.
204static bool isOnlyUsedInEntryBlock(Argument *A) {
205 BasicBlock *Entry = A->getParent()->begin();
206 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
207 if (cast<Instruction>(*UI)->getParent() != Entry)
208 return false; // Use not in entry block.
209 return true;
210}
211
Chris Lattner7a60d912005-01-07 07:47:53 +0000212FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000213 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000214 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
215
Chris Lattner6871b232005-10-30 19:42:35 +0000216 // Create a vreg for each argument register that is not dead and is used
217 // outside of the entry block for the function.
218 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
219 AI != E; ++AI)
220 if (!isOnlyUsedInEntryBlock(AI))
221 InitializeRegForValue(AI);
222
Chris Lattner7a60d912005-01-07 07:47:53 +0000223 // Initialize the mapping of values to registers. This is only set up for
224 // instruction values that are used outside of the block that defines
225 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000226 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
228 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
229 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
230 const Type *Ty = AI->getAllocatedType();
231 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000232 unsigned Align =
233 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
234 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000235
236 // If the alignment of the value is smaller than the size of the value,
237 // and if the size of the value is particularly small (<= 8 bytes),
238 // round up to the size of the value for potentially better performance.
239 //
240 // FIXME: This could be made better with a preferred alignment hook in
241 // TargetData. It serves primarily to 8-byte align doubles for X86.
242 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000243 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000244 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000245 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000246 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000247 }
248
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000249 for (; BB != EB; ++BB)
250 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000251 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
252 if (!isa<AllocaInst>(I) ||
253 !StaticAllocaMap.count(cast<AllocaInst>(I)))
254 InitializeRegForValue(I);
255
256 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
257 // also creates the initial PHI MachineInstrs, though none of the input
258 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000259 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000260 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
261 MBBMap[BB] = MBB;
262 MF.getBasicBlockList().push_back(MBB);
263
264 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
265 // appropriate.
266 PHINode *PN;
267 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000268 (PN = dyn_cast<PHINode>(I)); ++I)
269 if (!PN->use_empty()) {
270 unsigned NumElements =
271 TLI.getNumElements(TLI.getValueType(PN->getType()));
272 unsigned PHIReg = ValueMap[PN];
273 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
274 for (unsigned i = 0; i != NumElements; ++i)
275 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
276 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000277 }
278}
279
280
281
282//===----------------------------------------------------------------------===//
283/// SelectionDAGLowering - This is the common target-independent lowering
284/// implementation that is parameterized by a TargetLowering object.
285/// Also, targets can overload any lowering method.
286///
287namespace llvm {
288class SelectionDAGLowering {
289 MachineBasicBlock *CurMBB;
290
291 std::map<const Value*, SDOperand> NodeMap;
292
Chris Lattner4d9651c2005-01-17 22:19:26 +0000293 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
294 /// them up and then emit token factor nodes when possible. This allows us to
295 /// get simple disambiguation between loads without worrying about alias
296 /// analysis.
297 std::vector<SDOperand> PendingLoads;
298
Chris Lattner7a60d912005-01-07 07:47:53 +0000299public:
300 // TLI - This is information that describes the available target features we
301 // need for lowering. This indicates when operations are unavailable,
302 // implemented with a libcall, etc.
303 TargetLowering &TLI;
304 SelectionDAG &DAG;
305 const TargetData &TD;
306
307 /// FuncInfo - Information about the function as a whole.
308 ///
309 FunctionLoweringInfo &FuncInfo;
310
311 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000312 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000313 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
314 FuncInfo(funcinfo) {
315 }
316
Chris Lattner4108bb02005-01-17 19:43:36 +0000317 /// getRoot - Return the current virtual root of the Selection DAG.
318 ///
319 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000320 if (PendingLoads.empty())
321 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000322
Chris Lattner4d9651c2005-01-17 22:19:26 +0000323 if (PendingLoads.size() == 1) {
324 SDOperand Root = PendingLoads[0];
325 DAG.setRoot(Root);
326 PendingLoads.clear();
327 return Root;
328 }
329
330 // Otherwise, we have to make a token factor node.
331 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
332 PendingLoads.clear();
333 DAG.setRoot(Root);
334 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000335 }
336
Chris Lattner7a60d912005-01-07 07:47:53 +0000337 void visit(Instruction &I) { visit(I.getOpcode(), I); }
338
339 void visit(unsigned Opcode, User &I) {
340 switch (Opcode) {
341 default: assert(0 && "Unknown instruction type encountered!");
342 abort();
343 // Build the switch statement using the Instruction.def file.
344#define HANDLE_INST(NUM, OPCODE, CLASS) \
345 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
346#include "llvm/Instruction.def"
347 }
348 }
349
350 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
351
352
353 SDOperand getIntPtrConstant(uint64_t Val) {
354 return DAG.getConstant(Val, TLI.getPointerTy());
355 }
356
357 SDOperand getValue(const Value *V) {
358 SDOperand &N = NodeMap[V];
359 if (N.Val) return N;
360
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000361 const Type *VTy = V->getType();
362 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000363 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
365 visit(CE->getOpcode(), *CE);
366 assert(N.Val && "visit didn't populate the ValueMap!");
367 return N;
368 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
369 return N = DAG.getGlobalAddress(GV, VT);
370 } else if (isa<ConstantPointerNull>(C)) {
371 return N = DAG.getConstant(0, TLI.getPointerTy());
372 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000373 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000374 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
375 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000376 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
377 unsigned NumElements = PTy->getNumElements();
378 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
379 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
380
381 // Now that we know the number and type of the elements, push a
382 // Constant or ConstantFP node onto the ops list for each element of
383 // the packed constant.
384 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000385 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
386 if (MVT::isFloatingPoint(PVT)) {
387 for (unsigned i = 0; i != NumElements; ++i) {
388 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
389 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
390 }
391 } else {
392 for (unsigned i = 0; i != NumElements; ++i) {
393 const ConstantIntegral *El =
394 cast<ConstantIntegral>(CP->getOperand(i));
395 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
396 }
397 }
398 } else {
399 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
400 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000401 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000402 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000403 else
Chris Lattner803a5752005-12-21 02:43:26 +0000404 Op = DAG.getConstant(0, PVT);
405 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000406 }
Chris Lattner803a5752005-12-21 02:43:26 +0000407
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000408 // Handle the case where we have a 1-element vector, in which
409 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000410 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000411 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000412 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
413 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
414 } else {
415 // If the packed type isn't legal, then create a ConstantVec node with
416 // generic Vector type instead.
417 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
418 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000419 } else {
420 // Canonicalize all constant ints to be unsigned.
421 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
422 }
423
424 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
425 std::map<const AllocaInst*, int>::iterator SI =
426 FuncInfo.StaticAllocaMap.find(AI);
427 if (SI != FuncInfo.StaticAllocaMap.end())
428 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
429 }
430
431 std::map<const Value*, unsigned>::const_iterator VMI =
432 FuncInfo.ValueMap.find(V);
433 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000434
Chris Lattner33182322005-08-16 21:55:35 +0000435 unsigned InReg = VMI->second;
436
437 // If this type is not legal, make it so now.
438 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
439
440 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
441 if (DestVT < VT) {
442 // Source must be expanded. This input value is actually coming from the
443 // register pair VMI->second and VMI->second+1.
444 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
445 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
446 } else {
447 if (DestVT > VT) { // Promotion case
448 if (MVT::isFloatingPoint(VT))
449 N = DAG.getNode(ISD::FP_ROUND, VT, N);
450 else
451 N = DAG.getNode(ISD::TRUNCATE, VT, N);
452 }
453 }
454
455 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 }
457
458 const SDOperand &setValue(const Value *V, SDOperand NewN) {
459 SDOperand &N = NodeMap[V];
460 assert(N.Val == 0 && "Already set a value for this node!");
461 return N = NewN;
462 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000463
Chris Lattner6f87d182006-02-22 22:37:12 +0000464 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
465 MVT::ValueType VT,
466 bool OutReg, bool InReg,
467 std::set<unsigned> &OutputRegs,
468 std::set<unsigned> &InputRegs);
469
Chris Lattner7a60d912005-01-07 07:47:53 +0000470 // Terminator instructions.
471 void visitRet(ReturnInst &I);
472 void visitBr(BranchInst &I);
473 void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
475 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000476 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000477 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000478 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
482 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000483 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000484 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000485 void visitAdd(User &I) {
486 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000487 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000488 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000489 void visitMul(User &I) {
490 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000491 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000493 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000494 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 }
496 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000497 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000498 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000500 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
501 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
502 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000503 void visitShl(User &I) { visitShift(I, ISD::SHL); }
504 void visitShr(User &I) {
505 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000506 }
507
508 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
509 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
510 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
511 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
512 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
513 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
514 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
515
516 void visitGetElementPtr(User &I);
517 void visitCast(User &I);
518 void visitSelect(User &I);
519 //
520
521 void visitMalloc(MallocInst &I);
522 void visitFree(FreeInst &I);
523 void visitAlloca(AllocaInst &I);
524 void visitLoad(LoadInst &I);
525 void visitStore(StoreInst &I);
526 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
527 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000528 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000529 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000530
Chris Lattner7a60d912005-01-07 07:47:53 +0000531 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000532 void visitVAArg(VAArgInst &I);
533 void visitVAEnd(CallInst &I);
534 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000535 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000536
Chris Lattner875def92005-01-11 05:56:49 +0000537 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000538
539 void visitUserOp1(Instruction &I) {
540 assert(0 && "UserOp1 should not exist at instruction selection time!");
541 abort();
542 }
543 void visitUserOp2(Instruction &I) {
544 assert(0 && "UserOp2 should not exist at instruction selection time!");
545 abort();
546 }
547};
548} // end namespace llvm
549
550void SelectionDAGLowering::visitRet(ReturnInst &I) {
551 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000552 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000553 return;
554 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000555 std::vector<SDOperand> NewValues;
556 NewValues.push_back(getRoot());
557 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
558 SDOperand RetOp = getValue(I.getOperand(i));
559
560 // If this is an integer return value, we need to promote it ourselves to
561 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
562 // than sign/zero.
563 if (MVT::isInteger(RetOp.getValueType()) &&
564 RetOp.getValueType() < MVT::i64) {
565 MVT::ValueType TmpVT;
566 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
567 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
568 else
569 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000570
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000571 if (I.getOperand(i)->getType()->isSigned())
572 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
573 else
574 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
575 }
576 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000577 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000578 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000579}
580
581void SelectionDAGLowering::visitBr(BranchInst &I) {
582 // Update machine-CFG edges.
583 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000584
585 // Figure out which block is immediately after the current one.
586 MachineBasicBlock *NextBlock = 0;
587 MachineFunction::iterator BBI = CurMBB;
588 if (++BBI != CurMBB->getParent()->end())
589 NextBlock = BBI;
590
591 if (I.isUnconditional()) {
592 // If this is not a fall-through branch, emit the branch.
593 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000594 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000595 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000596 } else {
597 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000598
599 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000600 if (Succ1MBB == NextBlock) {
601 // If the condition is false, fall through. This means we should branch
602 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000603 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000604 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000605 } else if (Succ0MBB == NextBlock) {
606 // If the condition is true, fall through. This means we should branch if
607 // the condition is false to Succ #1. Invert the condition first.
608 SDOperand True = DAG.getConstant(1, Cond.getValueType());
609 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000610 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000611 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000612 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000613 std::vector<SDOperand> Ops;
614 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000615 // If the false case is the current basic block, then this is a self
616 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
617 // adds an extra instruction in the loop. Instead, invert the
618 // condition and emit "Loop: ... br!cond Loop; br Out.
619 if (CurMBB == Succ1MBB) {
620 std::swap(Succ0MBB, Succ1MBB);
621 SDOperand True = DAG.getConstant(1, Cond.getValueType());
622 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
623 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000624 Ops.push_back(Cond);
625 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
626 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
627 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000628 }
629 }
630}
631
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000632void SelectionDAGLowering::visitSub(User &I) {
633 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000634 if (I.getType()->isFloatingPoint()) {
635 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
636 if (CFP->isExactlyValue(-0.0)) {
637 SDOperand Op2 = getValue(I.getOperand(1));
638 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
639 return;
640 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000641 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000642 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000643}
644
Nate Begemanb2e089c2005-11-19 00:36:38 +0000645void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
646 unsigned VecOp) {
647 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000648 SDOperand Op1 = getValue(I.getOperand(0));
649 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000650
Chris Lattner19baba62005-11-19 18:40:42 +0000651 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000652 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
653 } else if (Ty->isFloatingPoint()) {
654 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
655 } else {
656 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000657 unsigned NumElements = PTy->getNumElements();
658 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000659 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000660
661 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000662 // the Legalize pass does not have to deal with them. Similarly, if the
663 // abstract vector is going to turn into one that the target natively
664 // supports, generate that type now so that Legalize doesn't have to deal
665 // with that either. These steps ensure that Legalize only has to handle
666 // vector types in its Expand case.
667 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000668 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000669 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000670 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
671 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000672 } else {
673 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
674 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000675 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000676 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000677 }
Nate Begeman127321b2005-11-18 07:42:56 +0000678}
Chris Lattner96c26752005-01-19 22:31:21 +0000679
Nate Begeman127321b2005-11-18 07:42:56 +0000680void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
681 SDOperand Op1 = getValue(I.getOperand(0));
682 SDOperand Op2 = getValue(I.getOperand(1));
683
684 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
685
Chris Lattner7a60d912005-01-07 07:47:53 +0000686 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
687}
688
689void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
690 ISD::CondCode UnsignedOpcode) {
691 SDOperand Op1 = getValue(I.getOperand(0));
692 SDOperand Op2 = getValue(I.getOperand(1));
693 ISD::CondCode Opcode = SignedOpcode;
694 if (I.getOperand(0)->getType()->isUnsigned())
695 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000696 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000697}
698
699void SelectionDAGLowering::visitSelect(User &I) {
700 SDOperand Cond = getValue(I.getOperand(0));
701 SDOperand TrueVal = getValue(I.getOperand(1));
702 SDOperand FalseVal = getValue(I.getOperand(2));
703 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
704 TrueVal, FalseVal));
705}
706
707void SelectionDAGLowering::visitCast(User &I) {
708 SDOperand N = getValue(I.getOperand(0));
709 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
710 MVT::ValueType DestTy = TLI.getValueType(I.getType());
711
712 if (N.getValueType() == DestTy) {
713 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000714 } else if (DestTy == MVT::i1) {
715 // Cast to bool is a comparison against zero, not truncation to zero.
716 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
717 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000718 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000719 } else if (isInteger(SrcTy)) {
720 if (isInteger(DestTy)) { // Int -> Int cast
721 if (DestTy < SrcTy) // Truncating cast?
722 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
723 else if (I.getOperand(0)->getType()->isSigned())
724 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
725 else
726 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
727 } else { // Int -> FP cast
728 if (I.getOperand(0)->getType()->isSigned())
729 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
730 else
731 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
732 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000733 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000734 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
735 if (isFloatingPoint(DestTy)) { // FP -> FP cast
736 if (DestTy < SrcTy) // Rounding cast?
737 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
738 else
739 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
740 } else { // FP -> Int cast.
741 if (I.getType()->isSigned())
742 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
743 else
744 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
745 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000746 }
747}
748
749void SelectionDAGLowering::visitGetElementPtr(User &I) {
750 SDOperand N = getValue(I.getOperand(0));
751 const Type *Ty = I.getOperand(0)->getType();
752 const Type *UIntPtrTy = TD.getIntPtrType();
753
754 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
755 OI != E; ++OI) {
756 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000757 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000758 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
759 if (Field) {
760 // N = N + Offset
761 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
762 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000763 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000764 }
765 Ty = StTy->getElementType(Field);
766 } else {
767 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000768
Chris Lattner43535a12005-11-09 04:45:33 +0000769 // If this is a constant subscript, handle it quickly.
770 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
771 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000772
Chris Lattner43535a12005-11-09 04:45:33 +0000773 uint64_t Offs;
774 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
775 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
776 else
777 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
778 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
779 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000780 }
Chris Lattner43535a12005-11-09 04:45:33 +0000781
782 // N = N + Idx * ElementSize;
783 uint64_t ElementSize = TD.getTypeSize(Ty);
784 SDOperand IdxN = getValue(Idx);
785
786 // If the index is smaller or larger than intptr_t, truncate or extend
787 // it.
788 if (IdxN.getValueType() < N.getValueType()) {
789 if (Idx->getType()->isSigned())
790 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
791 else
792 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
793 } else if (IdxN.getValueType() > N.getValueType())
794 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
795
796 // If this is a multiply by a power of two, turn it into a shl
797 // immediately. This is a very common case.
798 if (isPowerOf2_64(ElementSize)) {
799 unsigned Amt = Log2_64(ElementSize);
800 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000801 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000802 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
803 continue;
804 }
805
806 SDOperand Scale = getIntPtrConstant(ElementSize);
807 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
808 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000809 }
810 }
811 setValue(&I, N);
812}
813
814void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
815 // If this is a fixed sized alloca in the entry block of the function,
816 // allocate it statically on the stack.
817 if (FuncInfo.StaticAllocaMap.count(&I))
818 return; // getValue will auto-populate this.
819
820 const Type *Ty = I.getAllocatedType();
821 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000822 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
823 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000824
825 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000826 MVT::ValueType IntPtr = TLI.getPointerTy();
827 if (IntPtr < AllocSize.getValueType())
828 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
829 else if (IntPtr > AllocSize.getValueType())
830 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000831
Chris Lattnereccb73d2005-01-22 23:04:37 +0000832 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000833 getIntPtrConstant(TySize));
834
835 // Handle alignment. If the requested alignment is less than or equal to the
836 // stack alignment, ignore it and round the size of the allocation up to the
837 // stack alignment size. If the size is greater than the stack alignment, we
838 // note this in the DYNAMIC_STACKALLOC node.
839 unsigned StackAlign =
840 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
841 if (Align <= StackAlign) {
842 Align = 0;
843 // Add SA-1 to the size.
844 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
845 getIntPtrConstant(StackAlign-1));
846 // Mask out the low bits for alignment purposes.
847 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
848 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
849 }
850
Chris Lattner96c262e2005-05-14 07:29:57 +0000851 std::vector<MVT::ValueType> VTs;
852 VTs.push_back(AllocSize.getValueType());
853 VTs.push_back(MVT::Other);
854 std::vector<SDOperand> Ops;
855 Ops.push_back(getRoot());
856 Ops.push_back(AllocSize);
857 Ops.push_back(getIntPtrConstant(Align));
858 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000859 DAG.setRoot(setValue(&I, DSA).getValue(1));
860
861 // Inform the Frame Information that we have just allocated a variable-sized
862 // object.
863 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
864}
865
Chris Lattner435b4022005-11-29 06:21:05 +0000866/// getStringValue - Turn an LLVM constant pointer that eventually points to a
867/// global into a string value. Return an empty string if we can't do it.
868///
Evan Cheng6781b6e2006-02-15 21:59:04 +0000869static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
870 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
871 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
872 if (Init->isString()) {
873 std::string Result = Init->getAsString();
874 if (Offset < Result.size()) {
875 // If we are pointing INTO The string, erase the beginning...
876 Result.erase(Result.begin(), Result.begin()+Offset);
877 return Result;
Chris Lattner435b4022005-11-29 06:21:05 +0000878 }
879 }
880 }
881 return "";
882}
Chris Lattner7a60d912005-01-07 07:47:53 +0000883
884void SelectionDAGLowering::visitLoad(LoadInst &I) {
885 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000886
Chris Lattner4d9651c2005-01-17 22:19:26 +0000887 SDOperand Root;
888 if (I.isVolatile())
889 Root = getRoot();
890 else {
891 // Do not serialize non-volatile loads against each other.
892 Root = DAG.getRoot();
893 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000894
895 const Type *Ty = I.getType();
896 SDOperand L;
897
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000898 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000899 unsigned NumElements = PTy->getNumElements();
900 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000901 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000902
903 // Immediately scalarize packed types containing only one element, so that
904 // the Legalize pass does not have to deal with them.
905 if (NumElements == 1) {
906 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000907 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
908 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000909 } else {
910 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
911 DAG.getSrcValue(I.getOperand(0)));
912 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000913 } else {
914 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
915 DAG.getSrcValue(I.getOperand(0)));
916 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000917 setValue(&I, L);
918
919 if (I.isVolatile())
920 DAG.setRoot(L.getValue(1));
921 else
922 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000923}
924
925
926void SelectionDAGLowering::visitStore(StoreInst &I) {
927 Value *SrcV = I.getOperand(0);
928 SDOperand Src = getValue(SrcV);
929 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000930 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000931 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000932}
933
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000934/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
935/// we want to emit this as a call to a named external function, return the name
936/// otherwise lower it and return null.
937const char *
938SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
939 switch (Intrinsic) {
940 case Intrinsic::vastart: visitVAStart(I); return 0;
941 case Intrinsic::vaend: visitVAEnd(I); return 0;
942 case Intrinsic::vacopy: visitVACopy(I); return 0;
943 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
944 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
945 case Intrinsic::setjmp:
946 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
947 break;
948 case Intrinsic::longjmp:
949 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
950 break;
951 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
952 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
953 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
954
955 case Intrinsic::readport:
956 case Intrinsic::readio: {
957 std::vector<MVT::ValueType> VTs;
958 VTs.push_back(TLI.getValueType(I.getType()));
959 VTs.push_back(MVT::Other);
960 std::vector<SDOperand> Ops;
961 Ops.push_back(getRoot());
962 Ops.push_back(getValue(I.getOperand(1)));
963 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
964 ISD::READPORT : ISD::READIO, VTs, Ops);
965
966 setValue(&I, Tmp);
967 DAG.setRoot(Tmp.getValue(1));
968 return 0;
969 }
970 case Intrinsic::writeport:
971 case Intrinsic::writeio:
972 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
973 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
974 getRoot(), getValue(I.getOperand(1)),
975 getValue(I.getOperand(2))));
976 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000977
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000978 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000979 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
980 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000981
Jim Laskey5995d012006-02-11 01:01:30 +0000982 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
983 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
984 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +0000985
Jim Laskey5995d012006-02-11 01:01:30 +0000986 // Input Chain
987 Ops.push_back(getRoot());
988
989 // line number
990 Ops.push_back(getValue(I.getOperand(2)));
991
992 // column
993 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +0000994
Jim Laskey390c63e2006-02-13 12:50:39 +0000995 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +0000996 assert(DD && "Not a debug information descriptor");
997 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
998 assert(CompileUnit && "Not a compile unit");
999 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1000 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1001
1002 if (Ops.size() == 5) // Found filename/workingdir.
1003 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001004 }
1005
Chris Lattner8782b782005-12-03 18:50:48 +00001006 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001007 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001008 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001009 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001010 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1011 return "llvm_dbg_region_start";
1012 if (I.getType() != Type::VoidTy)
1013 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1014 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001015 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001016 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1017 return "llvm_dbg_region_end";
1018 if (I.getType() != Type::VoidTy)
1019 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1020 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001021 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001022 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1023 return "llvm_dbg_subprogram";
1024 if (I.getType() != Type::VoidTy)
1025 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1026 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001027 case Intrinsic::dbg_declare:
1028 if (I.getType() != Type::VoidTy)
1029 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1030 return 0;
1031
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001032 case Intrinsic::isunordered_f32:
1033 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001034 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1035 getValue(I.getOperand(2)), ISD::SETUO));
1036 return 0;
1037
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001038 case Intrinsic::sqrt_f32:
1039 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001040 setValue(&I, DAG.getNode(ISD::FSQRT,
1041 getValue(I.getOperand(1)).getValueType(),
1042 getValue(I.getOperand(1))));
1043 return 0;
1044 case Intrinsic::pcmarker: {
1045 SDOperand Tmp = getValue(I.getOperand(1));
1046 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1047 return 0;
1048 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001049 case Intrinsic::readcyclecounter: {
1050 std::vector<MVT::ValueType> VTs;
1051 VTs.push_back(MVT::i64);
1052 VTs.push_back(MVT::Other);
1053 std::vector<SDOperand> Ops;
1054 Ops.push_back(getRoot());
1055 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1056 setValue(&I, Tmp);
1057 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001058 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001059 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001060 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001061 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001062 case Intrinsic::bswap_i64:
1063 setValue(&I, DAG.getNode(ISD::BSWAP,
1064 getValue(I.getOperand(1)).getValueType(),
1065 getValue(I.getOperand(1))));
1066 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001067 case Intrinsic::cttz_i8:
1068 case Intrinsic::cttz_i16:
1069 case Intrinsic::cttz_i32:
1070 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001071 setValue(&I, DAG.getNode(ISD::CTTZ,
1072 getValue(I.getOperand(1)).getValueType(),
1073 getValue(I.getOperand(1))));
1074 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001075 case Intrinsic::ctlz_i8:
1076 case Intrinsic::ctlz_i16:
1077 case Intrinsic::ctlz_i32:
1078 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001079 setValue(&I, DAG.getNode(ISD::CTLZ,
1080 getValue(I.getOperand(1)).getValueType(),
1081 getValue(I.getOperand(1))));
1082 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001083 case Intrinsic::ctpop_i8:
1084 case Intrinsic::ctpop_i16:
1085 case Intrinsic::ctpop_i32:
1086 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001087 setValue(&I, DAG.getNode(ISD::CTPOP,
1088 getValue(I.getOperand(1)).getValueType(),
1089 getValue(I.getOperand(1))));
1090 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001091 case Intrinsic::stacksave: {
1092 std::vector<MVT::ValueType> VTs;
1093 VTs.push_back(TLI.getPointerTy());
1094 VTs.push_back(MVT::Other);
1095 std::vector<SDOperand> Ops;
1096 Ops.push_back(getRoot());
1097 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1098 setValue(&I, Tmp);
1099 DAG.setRoot(Tmp.getValue(1));
1100 return 0;
1101 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001102 case Intrinsic::stackrestore: {
1103 SDOperand Tmp = getValue(I.getOperand(1));
1104 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001105 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001106 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001107 case Intrinsic::prefetch:
1108 // FIXME: Currently discarding prefetches.
1109 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001110 default:
1111 std::cerr << I;
1112 assert(0 && "This intrinsic is not implemented yet!");
1113 return 0;
1114 }
1115}
1116
1117
Chris Lattner7a60d912005-01-07 07:47:53 +00001118void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001119 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001120 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001121 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001122 if (unsigned IID = F->getIntrinsicID()) {
1123 RenameFn = visitIntrinsicCall(I, IID);
1124 if (!RenameFn)
1125 return;
1126 } else { // Not an LLVM intrinsic.
1127 const std::string &Name = F->getName();
1128 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001129 if (I.getNumOperands() == 2 && // Basic sanity checks.
1130 I.getOperand(1)->getType()->isFloatingPoint() &&
1131 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001132 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001133 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1134 return;
1135 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001136 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001137 if (I.getNumOperands() == 2 && // Basic sanity checks.
1138 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001139 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001140 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001141 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1142 return;
1143 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001144 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001145 if (I.getNumOperands() == 2 && // Basic sanity checks.
1146 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1150 return;
1151 }
1152 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001153 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001154 } else if (isa<InlineAsm>(I.getOperand(0))) {
1155 visitInlineAsm(I);
1156 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001157 }
Misha Brukman835702a2005-04-21 22:36:52 +00001158
Chris Lattner18d2b342005-01-08 22:48:57 +00001159 SDOperand Callee;
1160 if (!RenameFn)
1161 Callee = getValue(I.getOperand(0));
1162 else
1163 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001164 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001165 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001166 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1167 Value *Arg = I.getOperand(i);
1168 SDOperand ArgNode = getValue(Arg);
1169 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1170 }
Misha Brukman835702a2005-04-21 22:36:52 +00001171
Nate Begemanf6565252005-03-26 01:29:23 +00001172 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1173 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001174
Chris Lattner1f45cd72005-01-08 19:26:18 +00001175 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001176 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001177 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001178 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001179 setValue(&I, Result.first);
1180 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001181}
1182
Chris Lattner6f87d182006-02-22 22:37:12 +00001183SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1184 SDOperand &Chain, SDOperand &Flag) {
1185 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1186 Chain = Val.getValue(1);
1187 Flag = Val.getValue(2);
1188
1189 // If the result was expanded, copy from the top part.
1190 if (Regs.size() > 1) {
1191 assert(Regs.size() == 2 &&
1192 "Cannot expand to more than 2 elts yet!");
1193 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1194 Chain = Val.getValue(1);
1195 Flag = Val.getValue(2);
Chris Lattnerb1124f32006-02-22 23:09:03 +00001196 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
Chris Lattner6f87d182006-02-22 22:37:12 +00001197 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001198
Chris Lattner6f87d182006-02-22 22:37:12 +00001199 // Otherwise, if the return value was promoted, truncate it to the
1200 // appropriate type.
1201 if (RegVT == ValueVT)
1202 return Val;
1203
1204 if (MVT::isInteger(RegVT))
1205 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1206 else
1207 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1208}
1209
Chris Lattner571d9642006-02-23 19:21:04 +00001210/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1211/// specified value into the registers specified by this object. This uses
1212/// Chain/Flag as the input and updates them for the output Chain/Flag.
1213void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1214 SDOperand &Chain, SDOperand &Flag) {
1215 if (Regs.size() == 1) {
1216 // If there is a single register and the types differ, this must be
1217 // a promotion.
1218 if (RegVT != ValueVT) {
1219 if (MVT::isInteger(RegVT))
1220 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1221 else
1222 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1223 }
1224 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1225 Flag = Chain.getValue(1);
1226 } else {
1227 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1228 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1229 DAG.getConstant(i, MVT::i32));
1230 Chain = DAG.getCopyToReg(Chain, Regs[i], Part, Flag);
1231 Flag = Chain.getValue(1);
1232 }
1233 }
1234}
Chris Lattner6f87d182006-02-22 22:37:12 +00001235
Chris Lattner571d9642006-02-23 19:21:04 +00001236/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1237/// operand list. This adds the code marker and includes the number of
1238/// values added into it.
1239void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1240 std::vector<SDOperand> &Ops) {
1241 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1242 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1243 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1244}
Chris Lattner6f87d182006-02-22 22:37:12 +00001245
1246/// isAllocatableRegister - If the specified register is safe to allocate,
1247/// i.e. it isn't a stack pointer or some other special register, return the
1248/// register class for the register. Otherwise, return null.
1249static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001250isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1251 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1252 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1253 E = MRI->regclass_end(); RCI != E; ++RCI) {
1254 const TargetRegisterClass *RC = *RCI;
1255 // If none of the the value types for this register class are valid, we
1256 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1257 bool isLegal = false;
1258 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1259 I != E; ++I) {
1260 if (TLI.isTypeLegal(*I)) {
1261 isLegal = true;
1262 break;
1263 }
1264 }
1265
1266 if (!isLegal) continue;
1267
Chris Lattner6f87d182006-02-22 22:37:12 +00001268 // NOTE: This isn't ideal. In particular, this might allocate the
1269 // frame pointer in functions that need it (due to them not being taken
1270 // out of allocation, because a variable sized allocation hasn't been seen
1271 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001272 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1273 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001274 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001275 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001276 }
1277 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001278}
1279
1280RegsForValue SelectionDAGLowering::
1281GetRegistersForValue(const std::string &ConstrCode,
1282 MVT::ValueType VT, bool isOutReg, bool isInReg,
1283 std::set<unsigned> &OutputRegs,
1284 std::set<unsigned> &InputRegs) {
1285 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1286 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1287 std::vector<unsigned> Regs;
1288
1289 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1290 MVT::ValueType RegVT;
1291 MVT::ValueType ValueVT = VT;
1292
1293 if (PhysReg.first) {
1294 if (VT == MVT::Other)
1295 ValueVT = *PhysReg.second->vt_begin();
1296 RegVT = VT;
1297
1298 // This is a explicit reference to a physical register.
1299 Regs.push_back(PhysReg.first);
1300
1301 // If this is an expanded reference, add the rest of the regs to Regs.
1302 if (NumRegs != 1) {
1303 RegVT = *PhysReg.second->vt_begin();
1304 TargetRegisterClass::iterator I = PhysReg.second->begin();
1305 TargetRegisterClass::iterator E = PhysReg.second->end();
1306 for (; *I != PhysReg.first; ++I)
1307 assert(I != E && "Didn't find reg!");
1308
1309 // Already added the first reg.
1310 --NumRegs; ++I;
1311 for (; NumRegs; --NumRegs, ++I) {
1312 assert(I != E && "Ran out of registers to allocate!");
1313 Regs.push_back(*I);
1314 }
1315 }
1316 return RegsForValue(Regs, RegVT, ValueVT);
1317 }
1318
1319 // This is a reference to a register class. Allocate NumRegs consecutive,
1320 // available, registers from the class.
1321 std::vector<unsigned> RegClassRegs =
1322 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1323
1324 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1325 MachineFunction &MF = *CurMBB->getParent();
1326 unsigned NumAllocated = 0;
1327 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1328 unsigned Reg = RegClassRegs[i];
1329 // See if this register is available.
1330 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1331 (isInReg && InputRegs.count(Reg))) { // Already used.
1332 // Make sure we find consecutive registers.
1333 NumAllocated = 0;
1334 continue;
1335 }
1336
1337 // Check to see if this register is allocatable (i.e. don't give out the
1338 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001339 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001340 if (!RC) {
1341 // Make sure we find consecutive registers.
1342 NumAllocated = 0;
1343 continue;
1344 }
1345
1346 // Okay, this register is good, we can use it.
1347 ++NumAllocated;
1348
1349 // If we allocated enough consecutive
1350 if (NumAllocated == NumRegs) {
1351 unsigned RegStart = (i-NumAllocated)+1;
1352 unsigned RegEnd = i+1;
1353 // Mark all of the allocated registers used.
1354 for (unsigned i = RegStart; i != RegEnd; ++i) {
1355 unsigned Reg = RegClassRegs[i];
1356 Regs.push_back(Reg);
1357 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1358 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1359 }
1360
1361 return RegsForValue(Regs, *RC->vt_begin(), VT);
1362 }
1363 }
1364
1365 // Otherwise, we couldn't allocate enough registers for this.
1366 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001367}
1368
Chris Lattner6f87d182006-02-22 22:37:12 +00001369
Chris Lattner476e67b2006-01-26 22:24:51 +00001370/// visitInlineAsm - Handle a call to an InlineAsm object.
1371///
1372void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1373 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1374
1375 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1376 MVT::Other);
1377
1378 // Note, we treat inline asms both with and without side-effects as the same.
1379 // If an inline asm doesn't have side effects and doesn't access memory, we
1380 // could not choose to not chain it.
1381 bool hasSideEffects = IA->hasSideEffects();
1382
Chris Lattner3a5ed552006-02-01 01:28:23 +00001383 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001384 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001385
1386 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1387 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1388 /// if it is a def of that register.
1389 std::vector<SDOperand> AsmNodeOperands;
1390 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1391 AsmNodeOperands.push_back(AsmStr);
1392
1393 SDOperand Chain = getRoot();
1394 SDOperand Flag;
1395
Chris Lattner1558fc62006-02-01 18:59:47 +00001396 // We fully assign registers here at isel time. This is not optimal, but
1397 // should work. For register classes that correspond to LLVM classes, we
1398 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1399 // over the constraints, collecting fixed registers that we know we can't use.
1400 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001401 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001402 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1403 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1404 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001405
Chris Lattner7ad77df2006-02-22 00:56:39 +00001406 MVT::ValueType OpVT;
1407
1408 // Compute the value type for each operand and add it to ConstraintVTs.
1409 switch (Constraints[i].Type) {
1410 case InlineAsm::isOutput:
1411 if (!Constraints[i].isIndirectOutput) {
1412 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1413 OpVT = TLI.getValueType(I.getType());
1414 } else {
1415 Value *CallOperand = I.getOperand(OpNum);
1416 const Type *OpTy = CallOperand->getType();
1417 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1418 OpNum++; // Consumes a call operand.
1419 }
1420 break;
1421 case InlineAsm::isInput:
1422 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1423 OpNum++; // Consumes a call operand.
1424 break;
1425 case InlineAsm::isClobber:
1426 OpVT = MVT::Other;
1427 break;
1428 }
1429
1430 ConstraintVTs.push_back(OpVT);
1431
Chris Lattner6f87d182006-02-22 22:37:12 +00001432 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1433 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001434
Chris Lattner6f87d182006-02-22 22:37:12 +00001435 // Build a list of regs that this operand uses. This always has a single
1436 // element for promoted/expanded operands.
1437 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1438 false, false,
1439 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001440
1441 switch (Constraints[i].Type) {
1442 case InlineAsm::isOutput:
1443 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001444 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001445 // If this is an early-clobber output, it cannot be assigned to the same
1446 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001447 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001448 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001449 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001450 case InlineAsm::isInput:
1451 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001452 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001453 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001454 case InlineAsm::isClobber:
1455 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001456 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1457 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001458 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001459 }
1460 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001461
Chris Lattner5c79f982006-02-21 23:12:12 +00001462 // Loop over all of the inputs, copying the operand values into the
1463 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001464 RegsForValue RetValRegs;
1465 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001466 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001467
Chris Lattner2e56e892006-01-31 02:03:41 +00001468 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001469 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1470 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001471
Chris Lattner3a5ed552006-02-01 01:28:23 +00001472 switch (Constraints[i].Type) {
1473 case InlineAsm::isOutput: {
Chris Lattner6f87d182006-02-22 22:37:12 +00001474 // If this is an early-clobber output, or if there is an input
1475 // constraint that matches this, we need to reserve the input register
1476 // so no other inputs allocate to it.
1477 bool UsesInputRegister = false;
1478 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1479 UsesInputRegister = true;
1480
1481 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001482 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001483 RegsForValue Regs =
1484 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1485 true, UsesInputRegister,
1486 OutputRegs, InputRegs);
1487 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001488
Chris Lattner3a5ed552006-02-01 01:28:23 +00001489 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001490 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001491 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001492 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001493 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001494 } else {
Chris Lattner7ad77df2006-02-22 00:56:39 +00001495 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner6f87d182006-02-22 22:37:12 +00001496 IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001497 OpNum++; // Consumes a call operand.
1498 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001499
1500 // Add information to the INLINEASM node to know that this register is
1501 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001502 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001503 break;
1504 }
1505 case InlineAsm::isInput: {
Chris Lattner7ad77df2006-02-22 00:56:39 +00001506 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner1558fc62006-02-01 18:59:47 +00001507 OpNum++; // Consumes a call operand.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001508
Chris Lattner5c79f982006-02-21 23:12:12 +00001509 SDOperand InOperandVal = getValue(CallOperand);
Chris Lattner65ad53f2006-02-04 02:16:44 +00001510
Chris Lattner7f5880b2006-02-02 00:25:23 +00001511 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1512 // If this is required to match an output register we have already set,
1513 // just use its register.
1514 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001515
Chris Lattner571d9642006-02-23 19:21:04 +00001516 // Scan until we find the definition we already emitted of this operand.
1517 // When we find it, create a RegsForValue operand.
1518 unsigned CurOp = 2; // The first operand.
1519 for (; OperandNo; --OperandNo) {
1520 // Advance to the next operand.
1521 unsigned NumOps =
1522 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1523 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1524 "Skipped past definitions?");
1525 CurOp += (NumOps>>3)+1;
1526 }
1527
1528 unsigned NumOps =
1529 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1530 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1531 "Skipped past definitions?");
1532
1533 // Add NumOps>>3 registers to MatchedRegs.
1534 RegsForValue MatchedRegs;
1535 MatchedRegs.ValueVT = InOperandVal.getValueType();
1536 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1537 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1538 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1539 MatchedRegs.Regs.push_back(Reg);
1540 }
1541
1542 // Use the produced MatchedRegs object to
1543 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1544 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner7f5880b2006-02-02 00:25:23 +00001545 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001546 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
Chris Lattner65ad53f2006-02-04 02:16:44 +00001547 if (ConstraintCode.size() == 1) // not a physreg name.
1548 CTy = TLI.getConstraintType(ConstraintCode[0]);
1549
Chris Lattner571d9642006-02-23 19:21:04 +00001550 if (CTy == TargetLowering::C_Other) {
Chris Lattner65ad53f2006-02-04 02:16:44 +00001551 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1552 assert(0 && "MATCH FAIL!");
Chris Lattner571d9642006-02-23 19:21:04 +00001553
1554 // Add information to the INLINEASM node to know about this input.
1555 unsigned ResOpType = 3 /*imm*/ | (1 << 3);
1556 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1557 AsmNodeOperands.push_back(InOperandVal);
Chris Lattner65ad53f2006-02-04 02:16:44 +00001558 break;
1559 }
Chris Lattner571d9642006-02-23 19:21:04 +00001560
1561 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1562
1563 // Copy the input into the appropriate registers.
1564 RegsForValue InRegs =
1565 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1566 false, true, OutputRegs, InputRegs);
1567 // FIXME: should be match fail.
1568 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1569
1570 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1571
1572 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
1573 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001574 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001575 break;
1576 }
Chris Lattner571d9642006-02-23 19:21:04 +00001577 case InlineAsm::isClobber: {
1578 RegsForValue ClobberedRegs =
1579 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1580 OutputRegs, InputRegs);
1581 // Add the clobbered value to the operand list, so that the register
1582 // allocator is aware that the physreg got clobbered.
1583 if (!ClobberedRegs.Regs.empty())
1584 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001585 break;
1586 }
Chris Lattner571d9642006-02-23 19:21:04 +00001587 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001588 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001589
1590 // Finish up input operands.
1591 AsmNodeOperands[0] = Chain;
1592 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1593
1594 std::vector<MVT::ValueType> VTs;
1595 VTs.push_back(MVT::Other);
1596 VTs.push_back(MVT::Flag);
1597 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1598 Flag = Chain.getValue(1);
1599
Chris Lattner2e56e892006-01-31 02:03:41 +00001600 // If this asm returns a register value, copy the result from that register
1601 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001602 if (!RetValRegs.Regs.empty())
1603 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001604
Chris Lattner2e56e892006-01-31 02:03:41 +00001605 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1606
1607 // Process indirect outputs, first output all of the flagged copies out of
1608 // physregs.
1609 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001610 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001611 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001612 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1613 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001614 }
1615
1616 // Emit the non-flagged stores from the physregs.
1617 std::vector<SDOperand> OutChains;
1618 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1619 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1620 StoresToEmit[i].first,
1621 getValue(StoresToEmit[i].second),
1622 DAG.getSrcValue(StoresToEmit[i].second)));
1623 if (!OutChains.empty())
1624 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001625 DAG.setRoot(Chain);
1626}
1627
1628
Chris Lattner7a60d912005-01-07 07:47:53 +00001629void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1630 SDOperand Src = getValue(I.getOperand(0));
1631
1632 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001633
1634 if (IntPtr < Src.getValueType())
1635 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1636 else if (IntPtr > Src.getValueType())
1637 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001638
1639 // Scale the source by the type size.
1640 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1641 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1642 Src, getIntPtrConstant(ElementSize));
1643
1644 std::vector<std::pair<SDOperand, const Type*> > Args;
1645 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001646
1647 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001648 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001649 DAG.getExternalSymbol("malloc", IntPtr),
1650 Args, DAG);
1651 setValue(&I, Result.first); // Pointers always fit in registers
1652 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001653}
1654
1655void SelectionDAGLowering::visitFree(FreeInst &I) {
1656 std::vector<std::pair<SDOperand, const Type*> > Args;
1657 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1658 TLI.getTargetData().getIntPtrType()));
1659 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001660 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001661 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001662 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1663 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001664}
1665
Chris Lattner13d7c252005-08-26 20:54:47 +00001666// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1667// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1668// instructions are special in various ways, which require special support to
1669// insert. The specified MachineInstr is created but not inserted into any
1670// basic blocks, and the scheduler passes ownership of it to this method.
1671MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1672 MachineBasicBlock *MBB) {
1673 std::cerr << "If a target marks an instruction with "
1674 "'usesCustomDAGSchedInserter', it must implement "
1675 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1676 abort();
1677 return 0;
1678}
1679
Chris Lattner58cfd792005-01-09 00:00:49 +00001680void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001681 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1682 getValue(I.getOperand(1)),
1683 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001684}
1685
1686void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001687 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1688 getValue(I.getOperand(0)),
1689 DAG.getSrcValue(I.getOperand(0)));
1690 setValue(&I, V);
1691 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001692}
1693
1694void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001695 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1696 getValue(I.getOperand(1)),
1697 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001698}
1699
1700void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001701 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1702 getValue(I.getOperand(1)),
1703 getValue(I.getOperand(2)),
1704 DAG.getSrcValue(I.getOperand(1)),
1705 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001706}
1707
Chris Lattner58cfd792005-01-09 00:00:49 +00001708// It is always conservatively correct for llvm.returnaddress and
1709// llvm.frameaddress to return 0.
1710std::pair<SDOperand, SDOperand>
1711TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1712 unsigned Depth, SelectionDAG &DAG) {
1713 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001714}
1715
Chris Lattner29dcc712005-05-14 05:50:48 +00001716SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001717 assert(0 && "LowerOperation not implemented for this target!");
1718 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001719 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001720}
1721
Nate Begeman595ec732006-01-28 03:14:31 +00001722SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1723 SelectionDAG &DAG) {
1724 assert(0 && "CustomPromoteOperation not implemented for this target!");
1725 abort();
1726 return SDOperand();
1727}
1728
Chris Lattner58cfd792005-01-09 00:00:49 +00001729void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1730 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1731 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001732 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001733 setValue(&I, Result.first);
1734 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001735}
1736
Evan Cheng6781b6e2006-02-15 21:59:04 +00001737/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001738/// operand.
1739static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001740 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001741 MVT::ValueType CurVT = VT;
1742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1743 uint64_t Val = C->getValue() & 255;
1744 unsigned Shift = 8;
1745 while (CurVT != MVT::i8) {
1746 Val = (Val << Shift) | Val;
1747 Shift <<= 1;
1748 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001749 }
1750 return DAG.getConstant(Val, VT);
1751 } else {
1752 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1753 unsigned Shift = 8;
1754 while (CurVT != MVT::i8) {
1755 Value =
1756 DAG.getNode(ISD::OR, VT,
1757 DAG.getNode(ISD::SHL, VT, Value,
1758 DAG.getConstant(Shift, MVT::i8)), Value);
1759 Shift <<= 1;
1760 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001761 }
1762
1763 return Value;
1764 }
1765}
1766
Evan Cheng6781b6e2006-02-15 21:59:04 +00001767/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1768/// used when a memcpy is turned into a memset when the source is a constant
1769/// string ptr.
1770static SDOperand getMemsetStringVal(MVT::ValueType VT,
1771 SelectionDAG &DAG, TargetLowering &TLI,
1772 std::string &Str, unsigned Offset) {
1773 MVT::ValueType CurVT = VT;
1774 uint64_t Val = 0;
1775 unsigned MSB = getSizeInBits(VT) / 8;
1776 if (TLI.isLittleEndian())
1777 Offset = Offset + MSB - 1;
1778 for (unsigned i = 0; i != MSB; ++i) {
1779 Val = (Val << 8) | Str[Offset];
1780 Offset += TLI.isLittleEndian() ? -1 : 1;
1781 }
1782 return DAG.getConstant(Val, VT);
1783}
1784
Evan Cheng81fcea82006-02-14 08:22:34 +00001785/// getMemBasePlusOffset - Returns base and offset node for the
1786static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1787 SelectionDAG &DAG, TargetLowering &TLI) {
1788 MVT::ValueType VT = Base.getValueType();
1789 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1790}
1791
Evan Chengdb2a7a72006-02-14 20:12:38 +00001792/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001793/// to replace the memset / memcpy is below the threshold. It also returns the
1794/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001795static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1796 unsigned Limit, uint64_t Size,
1797 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001798 MVT::ValueType VT;
1799
1800 if (TLI.allowsUnalignedMemoryAccesses()) {
1801 VT = MVT::i64;
1802 } else {
1803 switch (Align & 7) {
1804 case 0:
1805 VT = MVT::i64;
1806 break;
1807 case 4:
1808 VT = MVT::i32;
1809 break;
1810 case 2:
1811 VT = MVT::i16;
1812 break;
1813 default:
1814 VT = MVT::i8;
1815 break;
1816 }
1817 }
1818
Evan Chengd5026102006-02-14 09:11:59 +00001819 MVT::ValueType LVT = MVT::i64;
1820 while (!TLI.isTypeLegal(LVT))
1821 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1822 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001823
Evan Chengd5026102006-02-14 09:11:59 +00001824 if (VT > LVT)
1825 VT = LVT;
1826
Evan Cheng04514992006-02-14 23:05:54 +00001827 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001828 while (Size != 0) {
1829 unsigned VTSize = getSizeInBits(VT) / 8;
1830 while (VTSize > Size) {
1831 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001832 VTSize >>= 1;
1833 }
Evan Chengd5026102006-02-14 09:11:59 +00001834 assert(MVT::isInteger(VT));
1835
1836 if (++NumMemOps > Limit)
1837 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001838 MemOps.push_back(VT);
1839 Size -= VTSize;
1840 }
Evan Chengd5026102006-02-14 09:11:59 +00001841
1842 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001843}
1844
Chris Lattner875def92005-01-11 05:56:49 +00001845void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001846 SDOperand Op1 = getValue(I.getOperand(1));
1847 SDOperand Op2 = getValue(I.getOperand(2));
1848 SDOperand Op3 = getValue(I.getOperand(3));
1849 SDOperand Op4 = getValue(I.getOperand(4));
1850 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1851 if (Align == 0) Align = 1;
1852
1853 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1854 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001855
1856 // Expand memset / memcpy to a series of load / store ops
1857 // if the size operand falls below a certain threshold.
1858 std::vector<SDOperand> OutChains;
1859 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001860 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001861 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001862 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1863 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001864 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001865 unsigned Offset = 0;
1866 for (unsigned i = 0; i < NumMemOps; i++) {
1867 MVT::ValueType VT = MemOps[i];
1868 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001869 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001870 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1871 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001872 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1873 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001874 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001875 Offset += VTSize;
1876 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001877 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001878 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001879 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001880 case ISD::MEMCPY: {
1881 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1882 Size->getValue(), Align, TLI)) {
1883 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001884 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001885 GlobalAddressSDNode *G = NULL;
1886 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001887 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001888
1889 if (Op2.getOpcode() == ISD::GlobalAddress)
1890 G = cast<GlobalAddressSDNode>(Op2);
1891 else if (Op2.getOpcode() == ISD::ADD &&
1892 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1893 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1894 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001895 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001896 }
1897 if (G) {
1898 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001899 if (GV) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001900 Str = getStringValue(GV);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001901 if (!Str.empty()) {
1902 CopyFromStr = true;
1903 SrcOff += SrcDelta;
1904 }
1905 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001906 }
1907
Evan Chenge2038bd2006-02-15 01:54:51 +00001908 for (unsigned i = 0; i < NumMemOps; i++) {
1909 MVT::ValueType VT = MemOps[i];
1910 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001911 SDOperand Value, Chain, Store;
1912
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001913 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001914 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1915 Chain = getRoot();
1916 Store =
1917 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1918 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1919 DAG.getSrcValue(I.getOperand(1), DstOff));
1920 } else {
1921 Value = DAG.getLoad(VT, getRoot(),
1922 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1923 DAG.getSrcValue(I.getOperand(2), SrcOff));
1924 Chain = Value.getValue(1);
1925 Store =
1926 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1927 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1928 DAG.getSrcValue(I.getOperand(1), DstOff));
1929 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001930 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00001931 SrcOff += VTSize;
1932 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00001933 }
1934 }
1935 break;
1936 }
1937 }
1938
1939 if (!OutChains.empty()) {
1940 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1941 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00001942 }
1943 }
1944
Chris Lattner875def92005-01-11 05:56:49 +00001945 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001946 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00001947 Ops.push_back(Op1);
1948 Ops.push_back(Op2);
1949 Ops.push_back(Op3);
1950 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00001951 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001952}
1953
Chris Lattner875def92005-01-11 05:56:49 +00001954//===----------------------------------------------------------------------===//
1955// SelectionDAGISel code
1956//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001957
1958unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1959 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1960}
1961
Chris Lattnerc9950c12005-08-17 06:37:43 +00001962void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001963 // FIXME: we only modify the CFG to split critical edges. This
1964 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001965}
Chris Lattner7a60d912005-01-07 07:47:53 +00001966
Chris Lattner35397782005-12-05 07:10:48 +00001967
1968/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1969/// casting to the type of GEPI.
1970static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1971 Value *Ptr, Value *PtrOffset) {
1972 if (V) return V; // Already computed.
1973
1974 BasicBlock::iterator InsertPt;
1975 if (BB == GEPI->getParent()) {
1976 // If insert into the GEP's block, insert right after the GEP.
1977 InsertPt = GEPI;
1978 ++InsertPt;
1979 } else {
1980 // Otherwise, insert at the top of BB, after any PHI nodes
1981 InsertPt = BB->begin();
1982 while (isa<PHINode>(InsertPt)) ++InsertPt;
1983 }
1984
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001985 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1986 // BB so that there is only one value live across basic blocks (the cast
1987 // operand).
1988 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1989 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1990 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1991
Chris Lattner35397782005-12-05 07:10:48 +00001992 // Add the offset, cast it to the right type.
1993 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1994 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1995 return V = Ptr;
1996}
1997
1998
1999/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2000/// selection, we want to be a bit careful about some things. In particular, if
2001/// we have a GEP instruction that is used in a different block than it is
2002/// defined, the addressing expression of the GEP cannot be folded into loads or
2003/// stores that use it. In this case, decompose the GEP and move constant
2004/// indices into blocks that use it.
2005static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2006 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002007 // If this GEP is only used inside the block it is defined in, there is no
2008 // need to rewrite it.
2009 bool isUsedOutsideDefBB = false;
2010 BasicBlock *DefBB = GEPI->getParent();
2011 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2012 UI != E; ++UI) {
2013 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2014 isUsedOutsideDefBB = true;
2015 break;
2016 }
2017 }
2018 if (!isUsedOutsideDefBB) return;
2019
2020 // If this GEP has no non-zero constant indices, there is nothing we can do,
2021 // ignore it.
2022 bool hasConstantIndex = false;
2023 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2024 E = GEPI->op_end(); OI != E; ++OI) {
2025 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2026 if (CI->getRawValue()) {
2027 hasConstantIndex = true;
2028 break;
2029 }
2030 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002031 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2032 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002033
2034 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2035 // constant offset (which we now know is non-zero) and deal with it later.
2036 uint64_t ConstantOffset = 0;
2037 const Type *UIntPtrTy = TD.getIntPtrType();
2038 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2039 const Type *Ty = GEPI->getOperand(0)->getType();
2040
2041 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2042 E = GEPI->op_end(); OI != E; ++OI) {
2043 Value *Idx = *OI;
2044 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2045 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2046 if (Field)
2047 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2048 Ty = StTy->getElementType(Field);
2049 } else {
2050 Ty = cast<SequentialType>(Ty)->getElementType();
2051
2052 // Handle constant subscripts.
2053 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2054 if (CI->getRawValue() == 0) continue;
2055
2056 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2057 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2058 else
2059 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2060 continue;
2061 }
2062
2063 // Ptr = Ptr + Idx * ElementSize;
2064
2065 // Cast Idx to UIntPtrTy if needed.
2066 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2067
2068 uint64_t ElementSize = TD.getTypeSize(Ty);
2069 // Mask off bits that should not be set.
2070 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2071 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2072
2073 // Multiply by the element size and add to the base.
2074 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2075 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2076 }
2077 }
2078
2079 // Make sure that the offset fits in uintptr_t.
2080 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2081 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2082
2083 // Okay, we have now emitted all of the variable index parts to the BB that
2084 // the GEP is defined in. Loop over all of the using instructions, inserting
2085 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002086 // instruction to use the newly computed value, making GEPI dead. When the
2087 // user is a load or store instruction address, we emit the add into the user
2088 // block, otherwise we use a canonical version right next to the gep (these
2089 // won't be foldable as addresses, so we might as well share the computation).
2090
Chris Lattner35397782005-12-05 07:10:48 +00002091 std::map<BasicBlock*,Value*> InsertedExprs;
2092 while (!GEPI->use_empty()) {
2093 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002094
2095 // If this use is not foldable into the addressing mode, use a version
2096 // emitted in the GEP block.
2097 Value *NewVal;
2098 if (!isa<LoadInst>(User) &&
2099 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2100 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2101 Ptr, PtrOffset);
2102 } else {
2103 // Otherwise, insert the code in the User's block so it can be folded into
2104 // any users in that block.
2105 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002106 User->getParent(), GEPI,
2107 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002108 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002109 User->replaceUsesOfWith(GEPI, NewVal);
2110 }
Chris Lattner35397782005-12-05 07:10:48 +00002111
2112 // Finally, the GEP is dead, remove it.
2113 GEPI->eraseFromParent();
2114}
2115
Chris Lattner7a60d912005-01-07 07:47:53 +00002116bool SelectionDAGISel::runOnFunction(Function &Fn) {
2117 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2118 RegMap = MF.getSSARegMap();
2119 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2120
Chris Lattner35397782005-12-05 07:10:48 +00002121 // First, split all critical edges for PHI nodes with incoming values that are
2122 // constants, this way the load of the constant into a vreg will not be placed
2123 // into MBBs that are used some other way.
2124 //
2125 // In this pass we also look for GEP instructions that are used across basic
2126 // blocks and rewrites them to improve basic-block-at-a-time selection.
2127 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002128 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2129 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002130 BasicBlock::iterator BBI;
2131 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2133 if (isa<Constant>(PN->getIncomingValue(i)))
2134 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002135
2136 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2137 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2138 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002139 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002140
Chris Lattner7a60d912005-01-07 07:47:53 +00002141 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2142
2143 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2144 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002145
Chris Lattner7a60d912005-01-07 07:47:53 +00002146 return true;
2147}
2148
2149
Chris Lattner718b5c22005-01-13 17:59:43 +00002150SDOperand SelectionDAGISel::
2151CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002152 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002153 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002154 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002155 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002156
2157 // If this type is not legal, we must make sure to not create an invalid
2158 // register use.
2159 MVT::ValueType SrcVT = Op.getValueType();
2160 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2161 SelectionDAG &DAG = SDL.DAG;
2162 if (SrcVT == DestVT) {
2163 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2164 } else if (SrcVT < DestVT) {
2165 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002166 if (MVT::isFloatingPoint(SrcVT))
2167 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2168 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002169 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002170 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2171 } else {
2172 // The src value is expanded into multiple registers.
2173 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2174 Op, DAG.getConstant(0, MVT::i32));
2175 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2176 Op, DAG.getConstant(1, MVT::i32));
2177 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2178 return DAG.getCopyToReg(Op, Reg+1, Hi);
2179 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002180}
2181
Chris Lattner16f64df2005-01-17 17:15:02 +00002182void SelectionDAGISel::
2183LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2184 std::vector<SDOperand> &UnorderedChains) {
2185 // If this is the entry block, emit arguments.
2186 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002187 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002188 SDOperand OldRoot = SDL.DAG.getRoot();
2189 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002190
Chris Lattner6871b232005-10-30 19:42:35 +00002191 unsigned a = 0;
2192 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2193 AI != E; ++AI, ++a)
2194 if (!AI->use_empty()) {
2195 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002196
Chris Lattner6871b232005-10-30 19:42:35 +00002197 // If this argument is live outside of the entry block, insert a copy from
2198 // whereever we got it to the vreg that other BB's will reference it as.
2199 if (FuncInfo.ValueMap.count(AI)) {
2200 SDOperand Copy =
2201 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2202 UnorderedChains.push_back(Copy);
2203 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002204 }
Chris Lattner6871b232005-10-30 19:42:35 +00002205
2206 // Next, if the function has live ins that need to be copied into vregs,
2207 // emit the copies now, into the top of the block.
2208 MachineFunction &MF = SDL.DAG.getMachineFunction();
2209 if (MF.livein_begin() != MF.livein_end()) {
2210 SSARegMap *RegMap = MF.getSSARegMap();
2211 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2212 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2213 E = MF.livein_end(); LI != E; ++LI)
2214 if (LI->second)
2215 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2216 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002217 }
Chris Lattner6871b232005-10-30 19:42:35 +00002218
2219 // Finally, if the target has anything special to do, allow it to do so.
2220 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002221}
2222
2223
Chris Lattner7a60d912005-01-07 07:47:53 +00002224void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2225 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2226 FunctionLoweringInfo &FuncInfo) {
2227 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002228
2229 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002230
Chris Lattner6871b232005-10-30 19:42:35 +00002231 // Lower any arguments needed in this block if this is the entry block.
2232 if (LLVMBB == &LLVMBB->getParent()->front())
2233 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002234
2235 BB = FuncInfo.MBBMap[LLVMBB];
2236 SDL.setCurrentBasicBlock(BB);
2237
2238 // Lower all of the non-terminator instructions.
2239 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2240 I != E; ++I)
2241 SDL.visit(*I);
2242
2243 // Ensure that all instructions which are used outside of their defining
2244 // blocks are available as virtual registers.
2245 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002246 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002247 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002248 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002249 UnorderedChains.push_back(
2250 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002251 }
2252
2253 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2254 // ensure constants are generated when needed. Remember the virtual registers
2255 // that need to be added to the Machine PHI nodes as input. We cannot just
2256 // directly add them, because expansion might result in multiple MBB's for one
2257 // BB. As such, the start of the BB might correspond to a different MBB than
2258 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002259 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002260
2261 // Emit constants only once even if used by multiple PHI nodes.
2262 std::map<Constant*, unsigned> ConstantsOut;
2263
2264 // Check successor nodes PHI nodes that expect a constant to be available from
2265 // this block.
2266 TerminatorInst *TI = LLVMBB->getTerminator();
2267 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2268 BasicBlock *SuccBB = TI->getSuccessor(succ);
2269 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2270 PHINode *PN;
2271
2272 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2273 // nodes and Machine PHI nodes, but the incoming operands have not been
2274 // emitted yet.
2275 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002276 (PN = dyn_cast<PHINode>(I)); ++I)
2277 if (!PN->use_empty()) {
2278 unsigned Reg;
2279 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2280 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2281 unsigned &RegOut = ConstantsOut[C];
2282 if (RegOut == 0) {
2283 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002284 UnorderedChains.push_back(
2285 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002286 }
2287 Reg = RegOut;
2288 } else {
2289 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002290 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002291 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002292 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2293 "Didn't codegen value into a register!??");
2294 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002295 UnorderedChains.push_back(
2296 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002297 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002298 }
Misha Brukman835702a2005-04-21 22:36:52 +00002299
Chris Lattner8ea875f2005-01-07 21:34:19 +00002300 // Remember that this register needs to added to the machine PHI node as
2301 // the input for this MBB.
2302 unsigned NumElements =
2303 TLI.getNumElements(TLI.getValueType(PN->getType()));
2304 for (unsigned i = 0, e = NumElements; i != e; ++i)
2305 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002306 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002307 }
2308 ConstantsOut.clear();
2309
Chris Lattner718b5c22005-01-13 17:59:43 +00002310 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002311 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002312 SDOperand Root = SDL.getRoot();
2313 if (Root.getOpcode() != ISD::EntryToken) {
2314 unsigned i = 0, e = UnorderedChains.size();
2315 for (; i != e; ++i) {
2316 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2317 if (UnorderedChains[i].Val->getOperand(0) == Root)
2318 break; // Don't add the root if we already indirectly depend on it.
2319 }
2320
2321 if (i == e)
2322 UnorderedChains.push_back(Root);
2323 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002324 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2325 }
2326
Chris Lattner7a60d912005-01-07 07:47:53 +00002327 // Lower the terminator after the copies are emitted.
2328 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002329
2330 // Make sure the root of the DAG is up-to-date.
2331 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002332}
2333
2334void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2335 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002336 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002337 CurDAG = &DAG;
2338 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2339
2340 // First step, lower LLVM code to some DAG. This DAG may use operations and
2341 // types that are not supported by the target.
2342 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2343
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002344 // Run the DAG combiner in pre-legalize mode.
2345 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002346
Chris Lattner7a60d912005-01-07 07:47:53 +00002347 DEBUG(std::cerr << "Lowered selection DAG:\n");
2348 DEBUG(DAG.dump());
2349
2350 // Second step, hack on the DAG until it only uses operations and types that
2351 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002352 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002353
2354 DEBUG(std::cerr << "Legalized selection DAG:\n");
2355 DEBUG(DAG.dump());
2356
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002357 // Run the DAG combiner in post-legalize mode.
2358 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002359
Evan Cheng739a6a42006-01-21 02:32:06 +00002360 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002361
Chris Lattner5ca31d92005-03-30 01:10:47 +00002362 // Third, instruction select all of the operations to machine code, adding the
2363 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002364 InstructionSelectBasicBlock(DAG);
2365
Chris Lattner7a60d912005-01-07 07:47:53 +00002366 DEBUG(std::cerr << "Selected machine code:\n");
2367 DEBUG(BB->dump());
2368
Chris Lattner5ca31d92005-03-30 01:10:47 +00002369 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002370 // PHI nodes in successors.
2371 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2372 MachineInstr *PHI = PHINodesToUpdate[i].first;
2373 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2374 "This is not a machine PHI node that we are updating!");
2375 PHI->addRegOperand(PHINodesToUpdate[i].second);
2376 PHI->addMachineBasicBlockOperand(BB);
2377 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002378
2379 // Finally, add the CFG edges from the last selected MBB to the successor
2380 // MBBs.
2381 TerminatorInst *TI = LLVMBB->getTerminator();
2382 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2383 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2384 BB->addSuccessor(Succ0MBB);
2385 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002386}
Evan Cheng739a6a42006-01-21 02:32:06 +00002387
2388//===----------------------------------------------------------------------===//
2389/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2390/// target node in the graph.
2391void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2392 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002393 ScheduleDAG *SL = NULL;
2394
2395 switch (ISHeuristic) {
2396 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002397 case defaultScheduling:
2398 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2399 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2400 else /* TargetLowering::SchedulingForRegPressure */
2401 SL = createBURRListDAGScheduler(DAG, BB);
2402 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002403 case noScheduling:
2404 case simpleScheduling:
2405 case simpleNoItinScheduling:
2406 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2407 break;
Evan Cheng31272342006-01-23 08:26:10 +00002408 case listSchedulingBURR:
2409 SL = createBURRListDAGScheduler(DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002410 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002411 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002412 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002413}