blob: 10ee2d50915e3f49f34c9e32f64d346fc0080c61 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Evan Chengc1e1d972006-01-23 07:01:07 +000060namespace {
61 cl::opt<SchedHeuristics>
62 ISHeuristic(
63 "sched",
64 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000065 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000066 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000067 clEnumValN(defaultScheduling, "default",
68 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000069 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000070 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000071 clEnumValN(simpleScheduling, "simple",
72 "Simple two pass scheduling: minimize critical path "
73 "and maximize processor utilization"),
74 clEnumValN(simpleNoItinScheduling, "simple-noitin",
75 "Simple two pass scheduling: Same as simple "
76 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000078 "Bottom up register reduction list scheduling"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValEnd));
80} // namespace
81
Chris Lattner6f87d182006-02-22 22:37:12 +000082namespace {
83 /// RegsForValue - This struct represents the physical registers that a
84 /// particular value is assigned and the type information about the value.
85 /// This is needed because values can be promoted into larger registers and
86 /// expanded into multiple smaller registers than the value.
87 struct RegsForValue {
88 /// Regs - This list hold the register (for legal and promoted values)
89 /// or register set (for expanded values) that the value should be assigned
90 /// to.
91 std::vector<unsigned> Regs;
92
93 /// RegVT - The value type of each register.
94 ///
95 MVT::ValueType RegVT;
96
97 /// ValueVT - The value type of the LLVM value, which may be promoted from
98 /// RegVT or made from merging the two expanded parts.
99 MVT::ValueType ValueVT;
100
101 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102
103 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
104 : RegVT(regvt), ValueVT(valuevt) {
105 Regs.push_back(Reg);
106 }
107 RegsForValue(const std::vector<unsigned> &regs,
108 MVT::ValueType regvt, MVT::ValueType valuevt)
109 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
110 }
111
112 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
113 /// this value and returns the result as a ValueVT value. This uses
114 /// Chain/Flag as the input and updates them for the output Chain/Flag.
115 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000116 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000117
118 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
119 /// specified value into the registers specified by this object. This uses
120 /// Chain/Flag as the input and updates them for the output Chain/Flag.
121 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000122 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000123
124 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
125 /// operand list. This adds the code marker and includes the number of
126 /// values added into it.
127 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000129 };
130}
Evan Chengc1e1d972006-01-23 07:01:07 +0000131
Chris Lattner7a60d912005-01-07 07:47:53 +0000132namespace llvm {
133 //===--------------------------------------------------------------------===//
134 /// FunctionLoweringInfo - This contains information that is global to a
135 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000136 class FunctionLoweringInfo {
137 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000138 TargetLowering &TLI;
139 Function &Fn;
140 MachineFunction &MF;
141 SSARegMap *RegMap;
142
143 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
144
145 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
146 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
147
148 /// ValueMap - Since we emit code for the function a basic block at a time,
149 /// we must remember which virtual registers hold the values for
150 /// cross-basic-block values.
151 std::map<const Value*, unsigned> ValueMap;
152
153 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
154 /// the entry block. This allows the allocas to be efficiently referenced
155 /// anywhere in the function.
156 std::map<const AllocaInst*, int> StaticAllocaMap;
157
158 unsigned MakeReg(MVT::ValueType VT) {
159 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
160 }
Misha Brukman835702a2005-04-21 22:36:52 +0000161
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 unsigned CreateRegForValue(const Value *V) {
163 MVT::ValueType VT = TLI.getValueType(V->getType());
164 // The common case is that we will only create one register for this
165 // value. If we have that case, create and return the virtual register.
166 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000167 if (NV == 1) {
168 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000169 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000170 }
Misha Brukman835702a2005-04-21 22:36:52 +0000171
Chris Lattner7a60d912005-01-07 07:47:53 +0000172 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000173 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 unsigned NT = VT-1; // Find the type to use.
175 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
176 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000177
Chris Lattner7a60d912005-01-07 07:47:53 +0000178 unsigned R = MakeReg((MVT::ValueType)NT);
179 for (unsigned i = 1; i != NV; ++i)
180 MakeReg((MVT::ValueType)NT);
181 return R;
182 }
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 unsigned InitializeRegForValue(const Value *V) {
185 unsigned &R = ValueMap[V];
186 assert(R == 0 && "Already initialized this value register!");
187 return R = CreateRegForValue(V);
188 }
189 };
190}
191
192/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
193/// PHI nodes or outside of the basic block that defines it.
194static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
195 if (isa<PHINode>(I)) return true;
196 BasicBlock *BB = I->getParent();
197 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
198 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
199 return true;
200 return false;
201}
202
Chris Lattner6871b232005-10-30 19:42:35 +0000203/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204/// entry block, return true.
205static bool isOnlyUsedInEntryBlock(Argument *A) {
206 BasicBlock *Entry = A->getParent()->begin();
207 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != Entry)
209 return false; // Use not in entry block.
210 return true;
211}
212
Chris Lattner7a60d912005-01-07 07:47:53 +0000213FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000214 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000215 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
216
Chris Lattner6871b232005-10-30 19:42:35 +0000217 // Create a vreg for each argument register that is not dead and is used
218 // outside of the entry block for the function.
219 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
220 AI != E; ++AI)
221 if (!isOnlyUsedInEntryBlock(AI))
222 InitializeRegForValue(AI);
223
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 // Initialize the mapping of values to registers. This is only set up for
225 // instruction values that are used outside of the block that defines
226 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000227 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
230 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
231 const Type *Ty = AI->getAllocatedType();
232 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000233 unsigned Align =
234 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
235 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000236
237 // If the alignment of the value is smaller than the size of the value,
238 // and if the size of the value is particularly small (<= 8 bytes),
239 // round up to the size of the value for potentially better performance.
240 //
241 // FIXME: This could be made better with a preferred alignment hook in
242 // TargetData. It serves primarily to 8-byte align doubles for X86.
243 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000244 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000245 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000246 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000247 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 }
249
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000250 for (; BB != EB; ++BB)
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
253 if (!isa<AllocaInst>(I) ||
254 !StaticAllocaMap.count(cast<AllocaInst>(I)))
255 InitializeRegForValue(I);
256
257 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
258 // also creates the initial PHI MachineInstrs, though none of the input
259 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
262 MBBMap[BB] = MBB;
263 MF.getBasicBlockList().push_back(MBB);
264
265 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
266 // appropriate.
267 PHINode *PN;
268 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000269 (PN = dyn_cast<PHINode>(I)); ++I)
270 if (!PN->use_empty()) {
271 unsigned NumElements =
272 TLI.getNumElements(TLI.getValueType(PN->getType()));
273 unsigned PHIReg = ValueMap[PN];
274 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
275 for (unsigned i = 0; i != NumElements; ++i)
276 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
277 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000278 }
279}
280
281
282
283//===----------------------------------------------------------------------===//
284/// SelectionDAGLowering - This is the common target-independent lowering
285/// implementation that is parameterized by a TargetLowering object.
286/// Also, targets can overload any lowering method.
287///
288namespace llvm {
289class SelectionDAGLowering {
290 MachineBasicBlock *CurMBB;
291
292 std::map<const Value*, SDOperand> NodeMap;
293
Chris Lattner4d9651c2005-01-17 22:19:26 +0000294 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
295 /// them up and then emit token factor nodes when possible. This allows us to
296 /// get simple disambiguation between loads without worrying about alias
297 /// analysis.
298 std::vector<SDOperand> PendingLoads;
299
Chris Lattner7a60d912005-01-07 07:47:53 +0000300public:
301 // TLI - This is information that describes the available target features we
302 // need for lowering. This indicates when operations are unavailable,
303 // implemented with a libcall, etc.
304 TargetLowering &TLI;
305 SelectionDAG &DAG;
306 const TargetData &TD;
307
308 /// FuncInfo - Information about the function as a whole.
309 ///
310 FunctionLoweringInfo &FuncInfo;
311
312 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000313 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000314 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
315 FuncInfo(funcinfo) {
316 }
317
Chris Lattner4108bb02005-01-17 19:43:36 +0000318 /// getRoot - Return the current virtual root of the Selection DAG.
319 ///
320 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000321 if (PendingLoads.empty())
322 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000323
Chris Lattner4d9651c2005-01-17 22:19:26 +0000324 if (PendingLoads.size() == 1) {
325 SDOperand Root = PendingLoads[0];
326 DAG.setRoot(Root);
327 PendingLoads.clear();
328 return Root;
329 }
330
331 // Otherwise, we have to make a token factor node.
332 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
333 PendingLoads.clear();
334 DAG.setRoot(Root);
335 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000336 }
337
Chris Lattner7a60d912005-01-07 07:47:53 +0000338 void visit(Instruction &I) { visit(I.getOpcode(), I); }
339
340 void visit(unsigned Opcode, User &I) {
341 switch (Opcode) {
342 default: assert(0 && "Unknown instruction type encountered!");
343 abort();
344 // Build the switch statement using the Instruction.def file.
345#define HANDLE_INST(NUM, OPCODE, CLASS) \
346 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
347#include "llvm/Instruction.def"
348 }
349 }
350
351 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
352
353
354 SDOperand getIntPtrConstant(uint64_t Val) {
355 return DAG.getConstant(Val, TLI.getPointerTy());
356 }
357
358 SDOperand getValue(const Value *V) {
359 SDOperand &N = NodeMap[V];
360 if (N.Val) return N;
361
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000362 const Type *VTy = V->getType();
363 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000364 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
365 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
366 visit(CE->getOpcode(), *CE);
367 assert(N.Val && "visit didn't populate the ValueMap!");
368 return N;
369 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
370 return N = DAG.getGlobalAddress(GV, VT);
371 } else if (isa<ConstantPointerNull>(C)) {
372 return N = DAG.getConstant(0, TLI.getPointerTy());
373 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000374 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000375 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
376 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000377 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
378 unsigned NumElements = PTy->getNumElements();
379 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
380 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
381
382 // Now that we know the number and type of the elements, push a
383 // Constant or ConstantFP node onto the ops list for each element of
384 // the packed constant.
385 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000386 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
387 if (MVT::isFloatingPoint(PVT)) {
388 for (unsigned i = 0; i != NumElements; ++i) {
389 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
390 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
391 }
392 } else {
393 for (unsigned i = 0; i != NumElements; ++i) {
394 const ConstantIntegral *El =
395 cast<ConstantIntegral>(CP->getOperand(i));
396 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
397 }
398 }
399 } else {
400 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
401 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000402 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000403 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000404 else
Chris Lattner803a5752005-12-21 02:43:26 +0000405 Op = DAG.getConstant(0, PVT);
406 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000407 }
Chris Lattner803a5752005-12-21 02:43:26 +0000408
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000409 // Handle the case where we have a 1-element vector, in which
410 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000411 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000412 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000413 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
414 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
415 } else {
416 // If the packed type isn't legal, then create a ConstantVec node with
417 // generic Vector type instead.
Evan Chengb97aab42006-03-01 01:09:54 +0000418 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
419 SDOperand Typ = DAG.getValueType(PVT);
420 Ops.insert(Ops.begin(), Typ);
421 Ops.insert(Ops.begin(), Num);
422 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemanae89d862005-12-07 19:48:11 +0000423 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000424 } else {
425 // Canonicalize all constant ints to be unsigned.
426 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
427 }
428
429 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
430 std::map<const AllocaInst*, int>::iterator SI =
431 FuncInfo.StaticAllocaMap.find(AI);
432 if (SI != FuncInfo.StaticAllocaMap.end())
433 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
434 }
435
436 std::map<const Value*, unsigned>::const_iterator VMI =
437 FuncInfo.ValueMap.find(V);
438 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000439
Chris Lattner33182322005-08-16 21:55:35 +0000440 unsigned InReg = VMI->second;
441
442 // If this type is not legal, make it so now.
443 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
444
445 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
446 if (DestVT < VT) {
447 // Source must be expanded. This input value is actually coming from the
448 // register pair VMI->second and VMI->second+1.
449 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
450 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
451 } else {
452 if (DestVT > VT) { // Promotion case
453 if (MVT::isFloatingPoint(VT))
454 N = DAG.getNode(ISD::FP_ROUND, VT, N);
455 else
456 N = DAG.getNode(ISD::TRUNCATE, VT, N);
457 }
458 }
459
460 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 }
462
463 const SDOperand &setValue(const Value *V, SDOperand NewN) {
464 SDOperand &N = NodeMap[V];
465 assert(N.Val == 0 && "Already set a value for this node!");
466 return N = NewN;
467 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000468
Chris Lattner6f87d182006-02-22 22:37:12 +0000469 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
470 MVT::ValueType VT,
471 bool OutReg, bool InReg,
472 std::set<unsigned> &OutputRegs,
473 std::set<unsigned> &InputRegs);
474
Chris Lattner7a60d912005-01-07 07:47:53 +0000475 // Terminator instructions.
476 void visitRet(ReturnInst &I);
477 void visitBr(BranchInst &I);
478 void visitUnreachable(UnreachableInst &I) { /* noop */ }
479
480 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000481 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000482 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000483 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
484 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
485 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
486
487 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000488 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000489 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000490 void visitAdd(User &I) {
491 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000492 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000493 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000494 void visitMul(User &I) {
495 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000496 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000497 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
501 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000502 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000503 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000504 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000505 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
506 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
507 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000508 void visitShl(User &I) { visitShift(I, ISD::SHL); }
509 void visitShr(User &I) {
510 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 }
512
513 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
514 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
515 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
516 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
517 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
518 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
519 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
520
521 void visitGetElementPtr(User &I);
522 void visitCast(User &I);
523 void visitSelect(User &I);
524 //
525
526 void visitMalloc(MallocInst &I);
527 void visitFree(FreeInst &I);
528 void visitAlloca(AllocaInst &I);
529 void visitLoad(LoadInst &I);
530 void visitStore(StoreInst &I);
531 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
532 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000533 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000534 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000535
Chris Lattner7a60d912005-01-07 07:47:53 +0000536 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000537 void visitVAArg(VAArgInst &I);
538 void visitVAEnd(CallInst &I);
539 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000540 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000541
Chris Lattner875def92005-01-11 05:56:49 +0000542 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
544 void visitUserOp1(Instruction &I) {
545 assert(0 && "UserOp1 should not exist at instruction selection time!");
546 abort();
547 }
548 void visitUserOp2(Instruction &I) {
549 assert(0 && "UserOp2 should not exist at instruction selection time!");
550 abort();
551 }
552};
553} // end namespace llvm
554
555void SelectionDAGLowering::visitRet(ReturnInst &I) {
556 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000557 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000558 return;
559 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000560 std::vector<SDOperand> NewValues;
561 NewValues.push_back(getRoot());
562 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
563 SDOperand RetOp = getValue(I.getOperand(i));
564
565 // If this is an integer return value, we need to promote it ourselves to
566 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
567 // than sign/zero.
568 if (MVT::isInteger(RetOp.getValueType()) &&
569 RetOp.getValueType() < MVT::i64) {
570 MVT::ValueType TmpVT;
571 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
572 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
573 else
574 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000575
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000576 if (I.getOperand(i)->getType()->isSigned())
577 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
578 else
579 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
580 }
581 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000582 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000583 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000584}
585
586void SelectionDAGLowering::visitBr(BranchInst &I) {
587 // Update machine-CFG edges.
588 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000589
590 // Figure out which block is immediately after the current one.
591 MachineBasicBlock *NextBlock = 0;
592 MachineFunction::iterator BBI = CurMBB;
593 if (++BBI != CurMBB->getParent()->end())
594 NextBlock = BBI;
595
596 if (I.isUnconditional()) {
597 // If this is not a fall-through branch, emit the branch.
598 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000599 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000600 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 } else {
602 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000603
604 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000605 if (Succ1MBB == NextBlock) {
606 // If the condition is false, fall through. This means we should branch
607 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000608 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000609 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000610 } else if (Succ0MBB == NextBlock) {
611 // If the condition is true, fall through. This means we should branch if
612 // the condition is false to Succ #1. Invert the condition first.
613 SDOperand True = DAG.getConstant(1, Cond.getValueType());
614 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000615 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000616 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000617 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000618 std::vector<SDOperand> Ops;
619 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000620 // If the false case is the current basic block, then this is a self
621 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
622 // adds an extra instruction in the loop. Instead, invert the
623 // condition and emit "Loop: ... br!cond Loop; br Out.
624 if (CurMBB == Succ1MBB) {
625 std::swap(Succ0MBB, Succ1MBB);
626 SDOperand True = DAG.getConstant(1, Cond.getValueType());
627 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
628 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000629 Ops.push_back(Cond);
630 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
631 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
632 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000633 }
634 }
635}
636
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000637void SelectionDAGLowering::visitSub(User &I) {
638 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000639 if (I.getType()->isFloatingPoint()) {
640 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
641 if (CFP->isExactlyValue(-0.0)) {
642 SDOperand Op2 = getValue(I.getOperand(1));
643 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
644 return;
645 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000646 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000647 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000648}
649
Nate Begemanb2e089c2005-11-19 00:36:38 +0000650void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
651 unsigned VecOp) {
652 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000653 SDOperand Op1 = getValue(I.getOperand(0));
654 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000655
Chris Lattner19baba62005-11-19 18:40:42 +0000656 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000657 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
658 } else if (Ty->isFloatingPoint()) {
659 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
660 } else {
661 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000662 unsigned NumElements = PTy->getNumElements();
663 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000664 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000665
666 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000667 // the Legalize pass does not have to deal with them. Similarly, if the
668 // abstract vector is going to turn into one that the target natively
669 // supports, generate that type now so that Legalize doesn't have to deal
670 // with that either. These steps ensure that Legalize only has to handle
671 // vector types in its Expand case.
672 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000673 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000674 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Chengb97aab42006-03-01 01:09:54 +0000675 } else if (TVT != MVT::Other &&
676 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000677 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000678 } else {
679 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
680 SDOperand Typ = DAG.getValueType(PVT);
Evan Chengb97aab42006-03-01 01:09:54 +0000681 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000682 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000683 }
Nate Begeman127321b2005-11-18 07:42:56 +0000684}
Chris Lattner96c26752005-01-19 22:31:21 +0000685
Nate Begeman127321b2005-11-18 07:42:56 +0000686void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
687 SDOperand Op1 = getValue(I.getOperand(0));
688 SDOperand Op2 = getValue(I.getOperand(1));
689
690 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
691
Chris Lattner7a60d912005-01-07 07:47:53 +0000692 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
693}
694
695void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
696 ISD::CondCode UnsignedOpcode) {
697 SDOperand Op1 = getValue(I.getOperand(0));
698 SDOperand Op2 = getValue(I.getOperand(1));
699 ISD::CondCode Opcode = SignedOpcode;
700 if (I.getOperand(0)->getType()->isUnsigned())
701 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000702 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000703}
704
705void SelectionDAGLowering::visitSelect(User &I) {
706 SDOperand Cond = getValue(I.getOperand(0));
707 SDOperand TrueVal = getValue(I.getOperand(1));
708 SDOperand FalseVal = getValue(I.getOperand(2));
709 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
710 TrueVal, FalseVal));
711}
712
713void SelectionDAGLowering::visitCast(User &I) {
714 SDOperand N = getValue(I.getOperand(0));
715 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
716 MVT::ValueType DestTy = TLI.getValueType(I.getType());
717
718 if (N.getValueType() == DestTy) {
719 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000720 } else if (DestTy == MVT::i1) {
721 // Cast to bool is a comparison against zero, not truncation to zero.
722 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
723 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000724 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000725 } else if (isInteger(SrcTy)) {
726 if (isInteger(DestTy)) { // Int -> Int cast
727 if (DestTy < SrcTy) // Truncating cast?
728 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
729 else if (I.getOperand(0)->getType()->isSigned())
730 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
731 else
732 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
733 } else { // Int -> FP cast
734 if (I.getOperand(0)->getType()->isSigned())
735 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
736 else
737 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
738 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000739 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000740 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
741 if (isFloatingPoint(DestTy)) { // FP -> FP cast
742 if (DestTy < SrcTy) // Rounding cast?
743 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
744 else
745 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
746 } else { // FP -> Int cast.
747 if (I.getType()->isSigned())
748 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
749 else
750 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
751 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000752 }
753}
754
755void SelectionDAGLowering::visitGetElementPtr(User &I) {
756 SDOperand N = getValue(I.getOperand(0));
757 const Type *Ty = I.getOperand(0)->getType();
758 const Type *UIntPtrTy = TD.getIntPtrType();
759
760 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
761 OI != E; ++OI) {
762 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000763 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000764 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
765 if (Field) {
766 // N = N + Offset
767 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
768 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000769 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000770 }
771 Ty = StTy->getElementType(Field);
772 } else {
773 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000774
Chris Lattner43535a12005-11-09 04:45:33 +0000775 // If this is a constant subscript, handle it quickly.
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
777 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000778
Chris Lattner43535a12005-11-09 04:45:33 +0000779 uint64_t Offs;
780 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
781 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
782 else
783 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
784 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
785 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000786 }
Chris Lattner43535a12005-11-09 04:45:33 +0000787
788 // N = N + Idx * ElementSize;
789 uint64_t ElementSize = TD.getTypeSize(Ty);
790 SDOperand IdxN = getValue(Idx);
791
792 // If the index is smaller or larger than intptr_t, truncate or extend
793 // it.
794 if (IdxN.getValueType() < N.getValueType()) {
795 if (Idx->getType()->isSigned())
796 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
797 else
798 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
799 } else if (IdxN.getValueType() > N.getValueType())
800 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
801
802 // If this is a multiply by a power of two, turn it into a shl
803 // immediately. This is a very common case.
804 if (isPowerOf2_64(ElementSize)) {
805 unsigned Amt = Log2_64(ElementSize);
806 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000807 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000808 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
809 continue;
810 }
811
812 SDOperand Scale = getIntPtrConstant(ElementSize);
813 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
814 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000815 }
816 }
817 setValue(&I, N);
818}
819
820void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
821 // If this is a fixed sized alloca in the entry block of the function,
822 // allocate it statically on the stack.
823 if (FuncInfo.StaticAllocaMap.count(&I))
824 return; // getValue will auto-populate this.
825
826 const Type *Ty = I.getAllocatedType();
827 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000828 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
829 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000830
831 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000832 MVT::ValueType IntPtr = TLI.getPointerTy();
833 if (IntPtr < AllocSize.getValueType())
834 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
835 else if (IntPtr > AllocSize.getValueType())
836 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000837
Chris Lattnereccb73d2005-01-22 23:04:37 +0000838 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000839 getIntPtrConstant(TySize));
840
841 // Handle alignment. If the requested alignment is less than or equal to the
842 // stack alignment, ignore it and round the size of the allocation up to the
843 // stack alignment size. If the size is greater than the stack alignment, we
844 // note this in the DYNAMIC_STACKALLOC node.
845 unsigned StackAlign =
846 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
847 if (Align <= StackAlign) {
848 Align = 0;
849 // Add SA-1 to the size.
850 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
851 getIntPtrConstant(StackAlign-1));
852 // Mask out the low bits for alignment purposes.
853 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
854 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
855 }
856
Chris Lattner96c262e2005-05-14 07:29:57 +0000857 std::vector<MVT::ValueType> VTs;
858 VTs.push_back(AllocSize.getValueType());
859 VTs.push_back(MVT::Other);
860 std::vector<SDOperand> Ops;
861 Ops.push_back(getRoot());
862 Ops.push_back(AllocSize);
863 Ops.push_back(getIntPtrConstant(Align));
864 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000865 DAG.setRoot(setValue(&I, DSA).getValue(1));
866
867 // Inform the Frame Information that we have just allocated a variable-sized
868 // object.
869 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
870}
871
Chris Lattner435b4022005-11-29 06:21:05 +0000872/// getStringValue - Turn an LLVM constant pointer that eventually points to a
873/// global into a string value. Return an empty string if we can't do it.
874///
Evan Cheng6781b6e2006-02-15 21:59:04 +0000875static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
876 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
877 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
878 if (Init->isString()) {
879 std::string Result = Init->getAsString();
880 if (Offset < Result.size()) {
881 // If we are pointing INTO The string, erase the beginning...
882 Result.erase(Result.begin(), Result.begin()+Offset);
883 return Result;
Chris Lattner435b4022005-11-29 06:21:05 +0000884 }
885 }
886 }
887 return "";
888}
Chris Lattner7a60d912005-01-07 07:47:53 +0000889
890void SelectionDAGLowering::visitLoad(LoadInst &I) {
891 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000892
Chris Lattner4d9651c2005-01-17 22:19:26 +0000893 SDOperand Root;
894 if (I.isVolatile())
895 Root = getRoot();
896 else {
897 // Do not serialize non-volatile loads against each other.
898 Root = DAG.getRoot();
899 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000900
901 const Type *Ty = I.getType();
902 SDOperand L;
903
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000904 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000905 unsigned NumElements = PTy->getNumElements();
906 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000907 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000908
909 // Immediately scalarize packed types containing only one element, so that
910 // the Legalize pass does not have to deal with them.
911 if (NumElements == 1) {
912 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Evan Chengb97aab42006-03-01 01:09:54 +0000913 } else if (TVT != MVT::Other &&
914 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000915 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000916 } else {
917 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
918 DAG.getSrcValue(I.getOperand(0)));
919 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000920 } else {
921 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
922 DAG.getSrcValue(I.getOperand(0)));
923 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000924 setValue(&I, L);
925
926 if (I.isVolatile())
927 DAG.setRoot(L.getValue(1));
928 else
929 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000930}
931
932
933void SelectionDAGLowering::visitStore(StoreInst &I) {
934 Value *SrcV = I.getOperand(0);
935 SDOperand Src = getValue(SrcV);
936 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000937 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000938 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000939}
940
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000941/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
942/// we want to emit this as a call to a named external function, return the name
943/// otherwise lower it and return null.
944const char *
945SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
946 switch (Intrinsic) {
947 case Intrinsic::vastart: visitVAStart(I); return 0;
948 case Intrinsic::vaend: visitVAEnd(I); return 0;
949 case Intrinsic::vacopy: visitVACopy(I); return 0;
950 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
951 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
952 case Intrinsic::setjmp:
953 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
954 break;
955 case Intrinsic::longjmp:
956 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
957 break;
Chris Lattner093c1592006-03-03 00:00:25 +0000958 case Intrinsic::memcpy_i32:
959 case Intrinsic::memcpy_i64:
960 visitMemIntrinsic(I, ISD::MEMCPY);
961 return 0;
962 case Intrinsic::memset_i32:
963 case Intrinsic::memset_i64:
964 visitMemIntrinsic(I, ISD::MEMSET);
965 return 0;
966 case Intrinsic::memmove_i32:
967 case Intrinsic::memmove_i64:
968 visitMemIntrinsic(I, ISD::MEMMOVE);
969 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000970
971 case Intrinsic::readport:
972 case Intrinsic::readio: {
973 std::vector<MVT::ValueType> VTs;
974 VTs.push_back(TLI.getValueType(I.getType()));
975 VTs.push_back(MVT::Other);
976 std::vector<SDOperand> Ops;
977 Ops.push_back(getRoot());
978 Ops.push_back(getValue(I.getOperand(1)));
979 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
980 ISD::READPORT : ISD::READIO, VTs, Ops);
981
982 setValue(&I, Tmp);
983 DAG.setRoot(Tmp.getValue(1));
984 return 0;
985 }
986 case Intrinsic::writeport:
987 case Intrinsic::writeio:
988 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
989 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
990 getRoot(), getValue(I.getOperand(1)),
991 getValue(I.getOperand(2))));
992 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000993
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000994 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000995 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
996 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000997
Jim Laskey5995d012006-02-11 01:01:30 +0000998 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
999 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
1000 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001001
Jim Laskey5995d012006-02-11 01:01:30 +00001002 // Input Chain
1003 Ops.push_back(getRoot());
1004
1005 // line number
1006 Ops.push_back(getValue(I.getOperand(2)));
1007
1008 // column
1009 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +00001010
Jim Laskey390c63e2006-02-13 12:50:39 +00001011 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +00001012 assert(DD && "Not a debug information descriptor");
1013 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1014 assert(CompileUnit && "Not a compile unit");
1015 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1016 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1017
1018 if (Ops.size() == 5) // Found filename/workingdir.
1019 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001020 }
1021
Chris Lattner8782b782005-12-03 18:50:48 +00001022 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001023 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001024 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001025 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001026 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1027 return "llvm_dbg_region_start";
1028 if (I.getType() != Type::VoidTy)
1029 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1030 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001031 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001032 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1033 return "llvm_dbg_region_end";
1034 if (I.getType() != Type::VoidTy)
1035 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1036 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001037 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001038 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1039 return "llvm_dbg_subprogram";
1040 if (I.getType() != Type::VoidTy)
1041 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1042 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001043 case Intrinsic::dbg_declare:
1044 if (I.getType() != Type::VoidTy)
1045 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1046 return 0;
1047
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001048 case Intrinsic::isunordered_f32:
1049 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001050 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1051 getValue(I.getOperand(2)), ISD::SETUO));
1052 return 0;
1053
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001054 case Intrinsic::sqrt_f32:
1055 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001056 setValue(&I, DAG.getNode(ISD::FSQRT,
1057 getValue(I.getOperand(1)).getValueType(),
1058 getValue(I.getOperand(1))));
1059 return 0;
1060 case Intrinsic::pcmarker: {
1061 SDOperand Tmp = getValue(I.getOperand(1));
1062 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1063 return 0;
1064 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001065 case Intrinsic::readcyclecounter: {
1066 std::vector<MVT::ValueType> VTs;
1067 VTs.push_back(MVT::i64);
1068 VTs.push_back(MVT::Other);
1069 std::vector<SDOperand> Ops;
1070 Ops.push_back(getRoot());
1071 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1072 setValue(&I, Tmp);
1073 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001074 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001075 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001076 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001077 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001078 case Intrinsic::bswap_i64:
1079 setValue(&I, DAG.getNode(ISD::BSWAP,
1080 getValue(I.getOperand(1)).getValueType(),
1081 getValue(I.getOperand(1))));
1082 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001083 case Intrinsic::cttz_i8:
1084 case Intrinsic::cttz_i16:
1085 case Intrinsic::cttz_i32:
1086 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001087 setValue(&I, DAG.getNode(ISD::CTTZ,
1088 getValue(I.getOperand(1)).getValueType(),
1089 getValue(I.getOperand(1))));
1090 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001091 case Intrinsic::ctlz_i8:
1092 case Intrinsic::ctlz_i16:
1093 case Intrinsic::ctlz_i32:
1094 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001095 setValue(&I, DAG.getNode(ISD::CTLZ,
1096 getValue(I.getOperand(1)).getValueType(),
1097 getValue(I.getOperand(1))));
1098 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001099 case Intrinsic::ctpop_i8:
1100 case Intrinsic::ctpop_i16:
1101 case Intrinsic::ctpop_i32:
1102 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001103 setValue(&I, DAG.getNode(ISD::CTPOP,
1104 getValue(I.getOperand(1)).getValueType(),
1105 getValue(I.getOperand(1))));
1106 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001107 case Intrinsic::stacksave: {
1108 std::vector<MVT::ValueType> VTs;
1109 VTs.push_back(TLI.getPointerTy());
1110 VTs.push_back(MVT::Other);
1111 std::vector<SDOperand> Ops;
1112 Ops.push_back(getRoot());
1113 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1114 setValue(&I, Tmp);
1115 DAG.setRoot(Tmp.getValue(1));
1116 return 0;
1117 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001118 case Intrinsic::stackrestore: {
1119 SDOperand Tmp = getValue(I.getOperand(1));
1120 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001121 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001122 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001123 case Intrinsic::prefetch:
1124 // FIXME: Currently discarding prefetches.
1125 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001126 default:
1127 std::cerr << I;
1128 assert(0 && "This intrinsic is not implemented yet!");
1129 return 0;
1130 }
1131}
1132
1133
Chris Lattner7a60d912005-01-07 07:47:53 +00001134void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001135 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001136 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001137 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001138 if (unsigned IID = F->getIntrinsicID()) {
1139 RenameFn = visitIntrinsicCall(I, IID);
1140 if (!RenameFn)
1141 return;
1142 } else { // Not an LLVM intrinsic.
1143 const std::string &Name = F->getName();
1144 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001145 if (I.getNumOperands() == 2 && // Basic sanity checks.
1146 I.getOperand(1)->getType()->isFloatingPoint() &&
1147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001149 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1150 return;
1151 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001152 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001153 if (I.getNumOperands() == 2 && // Basic sanity checks.
1154 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001155 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001156 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001157 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1158 return;
1159 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001160 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001161 if (I.getNumOperands() == 2 && // Basic sanity checks.
1162 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001163 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001164 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001165 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1166 return;
1167 }
1168 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001169 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001170 } else if (isa<InlineAsm>(I.getOperand(0))) {
1171 visitInlineAsm(I);
1172 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001173 }
Misha Brukman835702a2005-04-21 22:36:52 +00001174
Chris Lattner18d2b342005-01-08 22:48:57 +00001175 SDOperand Callee;
1176 if (!RenameFn)
1177 Callee = getValue(I.getOperand(0));
1178 else
1179 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001180 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001181 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001182 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1183 Value *Arg = I.getOperand(i);
1184 SDOperand ArgNode = getValue(Arg);
1185 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1186 }
Misha Brukman835702a2005-04-21 22:36:52 +00001187
Nate Begemanf6565252005-03-26 01:29:23 +00001188 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1189 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001190
Chris Lattner1f45cd72005-01-08 19:26:18 +00001191 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001192 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001193 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001194 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001195 setValue(&I, Result.first);
1196 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001197}
1198
Chris Lattner6f87d182006-02-22 22:37:12 +00001199SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001200 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001201 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1202 Chain = Val.getValue(1);
1203 Flag = Val.getValue(2);
1204
1205 // If the result was expanded, copy from the top part.
1206 if (Regs.size() > 1) {
1207 assert(Regs.size() == 2 &&
1208 "Cannot expand to more than 2 elts yet!");
1209 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1210 Chain = Val.getValue(1);
1211 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001212 if (DAG.getTargetLoweringInfo().isLittleEndian())
1213 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1214 else
1215 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001216 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001217
Chris Lattner6f87d182006-02-22 22:37:12 +00001218 // Otherwise, if the return value was promoted, truncate it to the
1219 // appropriate type.
1220 if (RegVT == ValueVT)
1221 return Val;
1222
1223 if (MVT::isInteger(RegVT))
1224 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1225 else
1226 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1227}
1228
Chris Lattner571d9642006-02-23 19:21:04 +00001229/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1230/// specified value into the registers specified by this object. This uses
1231/// Chain/Flag as the input and updates them for the output Chain/Flag.
1232void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001233 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001234 if (Regs.size() == 1) {
1235 // If there is a single register and the types differ, this must be
1236 // a promotion.
1237 if (RegVT != ValueVT) {
1238 if (MVT::isInteger(RegVT))
1239 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1240 else
1241 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1242 }
1243 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1244 Flag = Chain.getValue(1);
1245 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001246 std::vector<unsigned> R(Regs);
1247 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1248 std::reverse(R.begin(), R.end());
1249
1250 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001251 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1252 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001253 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001254 Flag = Chain.getValue(1);
1255 }
1256 }
1257}
Chris Lattner6f87d182006-02-22 22:37:12 +00001258
Chris Lattner571d9642006-02-23 19:21:04 +00001259/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1260/// operand list. This adds the code marker and includes the number of
1261/// values added into it.
1262void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001263 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001264 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1265 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1266 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1267}
Chris Lattner6f87d182006-02-22 22:37:12 +00001268
1269/// isAllocatableRegister - If the specified register is safe to allocate,
1270/// i.e. it isn't a stack pointer or some other special register, return the
1271/// register class for the register. Otherwise, return null.
1272static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001273isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1274 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1275 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1276 E = MRI->regclass_end(); RCI != E; ++RCI) {
1277 const TargetRegisterClass *RC = *RCI;
1278 // If none of the the value types for this register class are valid, we
1279 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1280 bool isLegal = false;
1281 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1282 I != E; ++I) {
1283 if (TLI.isTypeLegal(*I)) {
1284 isLegal = true;
1285 break;
1286 }
1287 }
1288
1289 if (!isLegal) continue;
1290
Chris Lattner6f87d182006-02-22 22:37:12 +00001291 // NOTE: This isn't ideal. In particular, this might allocate the
1292 // frame pointer in functions that need it (due to them not being taken
1293 // out of allocation, because a variable sized allocation hasn't been seen
1294 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001295 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1296 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001297 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001298 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001299 }
1300 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001301}
1302
1303RegsForValue SelectionDAGLowering::
1304GetRegistersForValue(const std::string &ConstrCode,
1305 MVT::ValueType VT, bool isOutReg, bool isInReg,
1306 std::set<unsigned> &OutputRegs,
1307 std::set<unsigned> &InputRegs) {
1308 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1309 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1310 std::vector<unsigned> Regs;
1311
1312 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1313 MVT::ValueType RegVT;
1314 MVT::ValueType ValueVT = VT;
1315
1316 if (PhysReg.first) {
1317 if (VT == MVT::Other)
1318 ValueVT = *PhysReg.second->vt_begin();
1319 RegVT = VT;
1320
1321 // This is a explicit reference to a physical register.
1322 Regs.push_back(PhysReg.first);
1323
1324 // If this is an expanded reference, add the rest of the regs to Regs.
1325 if (NumRegs != 1) {
1326 RegVT = *PhysReg.second->vt_begin();
1327 TargetRegisterClass::iterator I = PhysReg.second->begin();
1328 TargetRegisterClass::iterator E = PhysReg.second->end();
1329 for (; *I != PhysReg.first; ++I)
1330 assert(I != E && "Didn't find reg!");
1331
1332 // Already added the first reg.
1333 --NumRegs; ++I;
1334 for (; NumRegs; --NumRegs, ++I) {
1335 assert(I != E && "Ran out of registers to allocate!");
1336 Regs.push_back(*I);
1337 }
1338 }
1339 return RegsForValue(Regs, RegVT, ValueVT);
1340 }
1341
1342 // This is a reference to a register class. Allocate NumRegs consecutive,
1343 // available, registers from the class.
1344 std::vector<unsigned> RegClassRegs =
1345 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1346
1347 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1348 MachineFunction &MF = *CurMBB->getParent();
1349 unsigned NumAllocated = 0;
1350 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1351 unsigned Reg = RegClassRegs[i];
1352 // See if this register is available.
1353 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1354 (isInReg && InputRegs.count(Reg))) { // Already used.
1355 // Make sure we find consecutive registers.
1356 NumAllocated = 0;
1357 continue;
1358 }
1359
1360 // Check to see if this register is allocatable (i.e. don't give out the
1361 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001362 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001363 if (!RC) {
1364 // Make sure we find consecutive registers.
1365 NumAllocated = 0;
1366 continue;
1367 }
1368
1369 // Okay, this register is good, we can use it.
1370 ++NumAllocated;
1371
1372 // If we allocated enough consecutive
1373 if (NumAllocated == NumRegs) {
1374 unsigned RegStart = (i-NumAllocated)+1;
1375 unsigned RegEnd = i+1;
1376 // Mark all of the allocated registers used.
1377 for (unsigned i = RegStart; i != RegEnd; ++i) {
1378 unsigned Reg = RegClassRegs[i];
1379 Regs.push_back(Reg);
1380 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1381 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1382 }
1383
1384 return RegsForValue(Regs, *RC->vt_begin(), VT);
1385 }
1386 }
1387
1388 // Otherwise, we couldn't allocate enough registers for this.
1389 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001390}
1391
Chris Lattner6f87d182006-02-22 22:37:12 +00001392
Chris Lattner476e67b2006-01-26 22:24:51 +00001393/// visitInlineAsm - Handle a call to an InlineAsm object.
1394///
1395void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1396 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1397
1398 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1399 MVT::Other);
1400
1401 // Note, we treat inline asms both with and without side-effects as the same.
1402 // If an inline asm doesn't have side effects and doesn't access memory, we
1403 // could not choose to not chain it.
1404 bool hasSideEffects = IA->hasSideEffects();
1405
Chris Lattner3a5ed552006-02-01 01:28:23 +00001406 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001407 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001408
1409 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1410 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1411 /// if it is a def of that register.
1412 std::vector<SDOperand> AsmNodeOperands;
1413 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1414 AsmNodeOperands.push_back(AsmStr);
1415
1416 SDOperand Chain = getRoot();
1417 SDOperand Flag;
1418
Chris Lattner1558fc62006-02-01 18:59:47 +00001419 // We fully assign registers here at isel time. This is not optimal, but
1420 // should work. For register classes that correspond to LLVM classes, we
1421 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1422 // over the constraints, collecting fixed registers that we know we can't use.
1423 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001424 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001425 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1426 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1427 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001428
Chris Lattner7ad77df2006-02-22 00:56:39 +00001429 MVT::ValueType OpVT;
1430
1431 // Compute the value type for each operand and add it to ConstraintVTs.
1432 switch (Constraints[i].Type) {
1433 case InlineAsm::isOutput:
1434 if (!Constraints[i].isIndirectOutput) {
1435 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1436 OpVT = TLI.getValueType(I.getType());
1437 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001438 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001439 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1440 OpNum++; // Consumes a call operand.
1441 }
1442 break;
1443 case InlineAsm::isInput:
1444 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1445 OpNum++; // Consumes a call operand.
1446 break;
1447 case InlineAsm::isClobber:
1448 OpVT = MVT::Other;
1449 break;
1450 }
1451
1452 ConstraintVTs.push_back(OpVT);
1453
Chris Lattner6f87d182006-02-22 22:37:12 +00001454 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1455 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001456
Chris Lattner6f87d182006-02-22 22:37:12 +00001457 // Build a list of regs that this operand uses. This always has a single
1458 // element for promoted/expanded operands.
1459 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1460 false, false,
1461 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001462
1463 switch (Constraints[i].Type) {
1464 case InlineAsm::isOutput:
1465 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001466 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001467 // If this is an early-clobber output, it cannot be assigned to the same
1468 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001469 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001470 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001471 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001472 case InlineAsm::isInput:
1473 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001474 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001475 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001476 case InlineAsm::isClobber:
1477 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001478 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1479 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001480 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001481 }
1482 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001483
Chris Lattner5c79f982006-02-21 23:12:12 +00001484 // Loop over all of the inputs, copying the operand values into the
1485 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001486 RegsForValue RetValRegs;
1487 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001488 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001489
Chris Lattner2e56e892006-01-31 02:03:41 +00001490 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001491 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1492 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001493
Chris Lattner3a5ed552006-02-01 01:28:23 +00001494 switch (Constraints[i].Type) {
1495 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001496 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1497 if (ConstraintCode.size() == 1) // not a physreg name.
1498 CTy = TLI.getConstraintType(ConstraintCode[0]);
1499
1500 if (CTy == TargetLowering::C_Memory) {
1501 // Memory output.
1502 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1503
1504 // Check that the operand (the address to store to) isn't a float.
1505 if (!MVT::isInteger(InOperandVal.getValueType()))
1506 assert(0 && "MATCH FAIL!");
1507
1508 if (!Constraints[i].isIndirectOutput)
1509 assert(0 && "MATCH FAIL!");
1510
1511 OpNum++; // Consumes a call operand.
1512
1513 // Extend/truncate to the right pointer type if needed.
1514 MVT::ValueType PtrType = TLI.getPointerTy();
1515 if (InOperandVal.getValueType() < PtrType)
1516 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1517 else if (InOperandVal.getValueType() > PtrType)
1518 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1519
1520 // Add information to the INLINEASM node to know about this output.
1521 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1522 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1523 AsmNodeOperands.push_back(InOperandVal);
1524 break;
1525 }
1526
1527 // Otherwise, this is a register output.
1528 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1529
Chris Lattner6f87d182006-02-22 22:37:12 +00001530 // If this is an early-clobber output, or if there is an input
1531 // constraint that matches this, we need to reserve the input register
1532 // so no other inputs allocate to it.
1533 bool UsesInputRegister = false;
1534 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1535 UsesInputRegister = true;
1536
1537 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001538 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001539 RegsForValue Regs =
1540 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1541 true, UsesInputRegister,
1542 OutputRegs, InputRegs);
1543 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001544
Chris Lattner3a5ed552006-02-01 01:28:23 +00001545 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001546 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001547 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001548 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001549 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001550 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001551 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1552 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001553 OpNum++; // Consumes a call operand.
1554 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001555
1556 // Add information to the INLINEASM node to know that this register is
1557 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001558 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001559 break;
1560 }
1561 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001562 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001563 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001564
Chris Lattner7f5880b2006-02-02 00:25:23 +00001565 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1566 // If this is required to match an output register we have already set,
1567 // just use its register.
1568 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001569
Chris Lattner571d9642006-02-23 19:21:04 +00001570 // Scan until we find the definition we already emitted of this operand.
1571 // When we find it, create a RegsForValue operand.
1572 unsigned CurOp = 2; // The first operand.
1573 for (; OperandNo; --OperandNo) {
1574 // Advance to the next operand.
1575 unsigned NumOps =
1576 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1577 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1578 "Skipped past definitions?");
1579 CurOp += (NumOps>>3)+1;
1580 }
1581
1582 unsigned NumOps =
1583 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1584 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1585 "Skipped past definitions?");
1586
1587 // Add NumOps>>3 registers to MatchedRegs.
1588 RegsForValue MatchedRegs;
1589 MatchedRegs.ValueVT = InOperandVal.getValueType();
1590 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1591 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1592 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1593 MatchedRegs.Regs.push_back(Reg);
1594 }
1595
1596 // Use the produced MatchedRegs object to
1597 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1598 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001599 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001600 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001601
1602 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1603 if (ConstraintCode.size() == 1) // not a physreg name.
1604 CTy = TLI.getConstraintType(ConstraintCode[0]);
1605
1606 if (CTy == TargetLowering::C_Other) {
1607 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1608 assert(0 && "MATCH FAIL!");
1609
1610 // Add information to the INLINEASM node to know about this input.
1611 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1612 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1613 AsmNodeOperands.push_back(InOperandVal);
1614 break;
1615 } else if (CTy == TargetLowering::C_Memory) {
1616 // Memory input.
1617
1618 // Check that the operand isn't a float.
1619 if (!MVT::isInteger(InOperandVal.getValueType()))
1620 assert(0 && "MATCH FAIL!");
1621
1622 // Extend/truncate to the right pointer type if needed.
1623 MVT::ValueType PtrType = TLI.getPointerTy();
1624 if (InOperandVal.getValueType() < PtrType)
1625 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1626 else if (InOperandVal.getValueType() > PtrType)
1627 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1628
1629 // Add information to the INLINEASM node to know about this input.
1630 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1631 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1632 AsmNodeOperands.push_back(InOperandVal);
1633 break;
1634 }
1635
1636 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1637
1638 // Copy the input into the appropriate registers.
1639 RegsForValue InRegs =
1640 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1641 false, true, OutputRegs, InputRegs);
1642 // FIXME: should be match fail.
1643 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1644
1645 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1646
1647 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001648 break;
1649 }
Chris Lattner571d9642006-02-23 19:21:04 +00001650 case InlineAsm::isClobber: {
1651 RegsForValue ClobberedRegs =
1652 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1653 OutputRegs, InputRegs);
1654 // Add the clobbered value to the operand list, so that the register
1655 // allocator is aware that the physreg got clobbered.
1656 if (!ClobberedRegs.Regs.empty())
1657 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001658 break;
1659 }
Chris Lattner571d9642006-02-23 19:21:04 +00001660 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001661 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001662
1663 // Finish up input operands.
1664 AsmNodeOperands[0] = Chain;
1665 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1666
1667 std::vector<MVT::ValueType> VTs;
1668 VTs.push_back(MVT::Other);
1669 VTs.push_back(MVT::Flag);
1670 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1671 Flag = Chain.getValue(1);
1672
Chris Lattner2e56e892006-01-31 02:03:41 +00001673 // If this asm returns a register value, copy the result from that register
1674 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001675 if (!RetValRegs.Regs.empty())
1676 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001677
Chris Lattner2e56e892006-01-31 02:03:41 +00001678 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1679
1680 // Process indirect outputs, first output all of the flagged copies out of
1681 // physregs.
1682 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001683 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001684 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001685 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1686 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001687 }
1688
1689 // Emit the non-flagged stores from the physregs.
1690 std::vector<SDOperand> OutChains;
1691 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1692 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1693 StoresToEmit[i].first,
1694 getValue(StoresToEmit[i].second),
1695 DAG.getSrcValue(StoresToEmit[i].second)));
1696 if (!OutChains.empty())
1697 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001698 DAG.setRoot(Chain);
1699}
1700
1701
Chris Lattner7a60d912005-01-07 07:47:53 +00001702void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1703 SDOperand Src = getValue(I.getOperand(0));
1704
1705 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001706
1707 if (IntPtr < Src.getValueType())
1708 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1709 else if (IntPtr > Src.getValueType())
1710 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001711
1712 // Scale the source by the type size.
1713 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1714 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1715 Src, getIntPtrConstant(ElementSize));
1716
1717 std::vector<std::pair<SDOperand, const Type*> > Args;
1718 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001719
1720 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001721 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001722 DAG.getExternalSymbol("malloc", IntPtr),
1723 Args, DAG);
1724 setValue(&I, Result.first); // Pointers always fit in registers
1725 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001726}
1727
1728void SelectionDAGLowering::visitFree(FreeInst &I) {
1729 std::vector<std::pair<SDOperand, const Type*> > Args;
1730 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1731 TLI.getTargetData().getIntPtrType()));
1732 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001733 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001734 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001735 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1736 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001737}
1738
Chris Lattner13d7c252005-08-26 20:54:47 +00001739// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1740// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1741// instructions are special in various ways, which require special support to
1742// insert. The specified MachineInstr is created but not inserted into any
1743// basic blocks, and the scheduler passes ownership of it to this method.
1744MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1745 MachineBasicBlock *MBB) {
1746 std::cerr << "If a target marks an instruction with "
1747 "'usesCustomDAGSchedInserter', it must implement "
1748 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1749 abort();
1750 return 0;
1751}
1752
Chris Lattner58cfd792005-01-09 00:00:49 +00001753void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001754 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1755 getValue(I.getOperand(1)),
1756 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001757}
1758
1759void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001760 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1761 getValue(I.getOperand(0)),
1762 DAG.getSrcValue(I.getOperand(0)));
1763 setValue(&I, V);
1764 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001765}
1766
1767void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001768 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1769 getValue(I.getOperand(1)),
1770 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001771}
1772
1773void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001774 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1775 getValue(I.getOperand(1)),
1776 getValue(I.getOperand(2)),
1777 DAG.getSrcValue(I.getOperand(1)),
1778 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001779}
1780
Chris Lattner58cfd792005-01-09 00:00:49 +00001781// It is always conservatively correct for llvm.returnaddress and
1782// llvm.frameaddress to return 0.
1783std::pair<SDOperand, SDOperand>
1784TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1785 unsigned Depth, SelectionDAG &DAG) {
1786 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001787}
1788
Chris Lattner29dcc712005-05-14 05:50:48 +00001789SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001790 assert(0 && "LowerOperation not implemented for this target!");
1791 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001792 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001793}
1794
Nate Begeman595ec732006-01-28 03:14:31 +00001795SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1796 SelectionDAG &DAG) {
1797 assert(0 && "CustomPromoteOperation not implemented for this target!");
1798 abort();
1799 return SDOperand();
1800}
1801
Chris Lattner58cfd792005-01-09 00:00:49 +00001802void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1803 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1804 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001805 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001806 setValue(&I, Result.first);
1807 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001808}
1809
Evan Cheng6781b6e2006-02-15 21:59:04 +00001810/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001811/// operand.
1812static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001813 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001814 MVT::ValueType CurVT = VT;
1815 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1816 uint64_t Val = C->getValue() & 255;
1817 unsigned Shift = 8;
1818 while (CurVT != MVT::i8) {
1819 Val = (Val << Shift) | Val;
1820 Shift <<= 1;
1821 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001822 }
1823 return DAG.getConstant(Val, VT);
1824 } else {
1825 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1826 unsigned Shift = 8;
1827 while (CurVT != MVT::i8) {
1828 Value =
1829 DAG.getNode(ISD::OR, VT,
1830 DAG.getNode(ISD::SHL, VT, Value,
1831 DAG.getConstant(Shift, MVT::i8)), Value);
1832 Shift <<= 1;
1833 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001834 }
1835
1836 return Value;
1837 }
1838}
1839
Evan Cheng6781b6e2006-02-15 21:59:04 +00001840/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1841/// used when a memcpy is turned into a memset when the source is a constant
1842/// string ptr.
1843static SDOperand getMemsetStringVal(MVT::ValueType VT,
1844 SelectionDAG &DAG, TargetLowering &TLI,
1845 std::string &Str, unsigned Offset) {
1846 MVT::ValueType CurVT = VT;
1847 uint64_t Val = 0;
1848 unsigned MSB = getSizeInBits(VT) / 8;
1849 if (TLI.isLittleEndian())
1850 Offset = Offset + MSB - 1;
1851 for (unsigned i = 0; i != MSB; ++i) {
1852 Val = (Val << 8) | Str[Offset];
1853 Offset += TLI.isLittleEndian() ? -1 : 1;
1854 }
1855 return DAG.getConstant(Val, VT);
1856}
1857
Evan Cheng81fcea82006-02-14 08:22:34 +00001858/// getMemBasePlusOffset - Returns base and offset node for the
1859static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1860 SelectionDAG &DAG, TargetLowering &TLI) {
1861 MVT::ValueType VT = Base.getValueType();
1862 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1863}
1864
Evan Chengdb2a7a72006-02-14 20:12:38 +00001865/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001866/// to replace the memset / memcpy is below the threshold. It also returns the
1867/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001868static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1869 unsigned Limit, uint64_t Size,
1870 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001871 MVT::ValueType VT;
1872
1873 if (TLI.allowsUnalignedMemoryAccesses()) {
1874 VT = MVT::i64;
1875 } else {
1876 switch (Align & 7) {
1877 case 0:
1878 VT = MVT::i64;
1879 break;
1880 case 4:
1881 VT = MVT::i32;
1882 break;
1883 case 2:
1884 VT = MVT::i16;
1885 break;
1886 default:
1887 VT = MVT::i8;
1888 break;
1889 }
1890 }
1891
Evan Chengd5026102006-02-14 09:11:59 +00001892 MVT::ValueType LVT = MVT::i64;
1893 while (!TLI.isTypeLegal(LVT))
1894 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1895 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001896
Evan Chengd5026102006-02-14 09:11:59 +00001897 if (VT > LVT)
1898 VT = LVT;
1899
Evan Cheng04514992006-02-14 23:05:54 +00001900 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001901 while (Size != 0) {
1902 unsigned VTSize = getSizeInBits(VT) / 8;
1903 while (VTSize > Size) {
1904 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001905 VTSize >>= 1;
1906 }
Evan Chengd5026102006-02-14 09:11:59 +00001907 assert(MVT::isInteger(VT));
1908
1909 if (++NumMemOps > Limit)
1910 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001911 MemOps.push_back(VT);
1912 Size -= VTSize;
1913 }
Evan Chengd5026102006-02-14 09:11:59 +00001914
1915 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001916}
1917
Chris Lattner875def92005-01-11 05:56:49 +00001918void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001919 SDOperand Op1 = getValue(I.getOperand(1));
1920 SDOperand Op2 = getValue(I.getOperand(2));
1921 SDOperand Op3 = getValue(I.getOperand(3));
1922 SDOperand Op4 = getValue(I.getOperand(4));
1923 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1924 if (Align == 0) Align = 1;
1925
1926 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1927 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001928
1929 // Expand memset / memcpy to a series of load / store ops
1930 // if the size operand falls below a certain threshold.
1931 std::vector<SDOperand> OutChains;
1932 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001933 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001934 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001935 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1936 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001937 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001938 unsigned Offset = 0;
1939 for (unsigned i = 0; i < NumMemOps; i++) {
1940 MVT::ValueType VT = MemOps[i];
1941 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001942 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001943 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1944 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001945 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1946 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001947 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001948 Offset += VTSize;
1949 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001950 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001951 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001952 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001953 case ISD::MEMCPY: {
1954 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1955 Size->getValue(), Align, TLI)) {
1956 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001957 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001958 GlobalAddressSDNode *G = NULL;
1959 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001960 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001961
1962 if (Op2.getOpcode() == ISD::GlobalAddress)
1963 G = cast<GlobalAddressSDNode>(Op2);
1964 else if (Op2.getOpcode() == ISD::ADD &&
1965 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1966 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1967 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001968 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001969 }
1970 if (G) {
1971 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001972 if (GV) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001973 Str = getStringValue(GV);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001974 if (!Str.empty()) {
1975 CopyFromStr = true;
1976 SrcOff += SrcDelta;
1977 }
1978 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001979 }
1980
Evan Chenge2038bd2006-02-15 01:54:51 +00001981 for (unsigned i = 0; i < NumMemOps; i++) {
1982 MVT::ValueType VT = MemOps[i];
1983 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001984 SDOperand Value, Chain, Store;
1985
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001986 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001987 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1988 Chain = getRoot();
1989 Store =
1990 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1991 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1992 DAG.getSrcValue(I.getOperand(1), DstOff));
1993 } else {
1994 Value = DAG.getLoad(VT, getRoot(),
1995 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1996 DAG.getSrcValue(I.getOperand(2), SrcOff));
1997 Chain = Value.getValue(1);
1998 Store =
1999 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2000 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2001 DAG.getSrcValue(I.getOperand(1), DstOff));
2002 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002003 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002004 SrcOff += VTSize;
2005 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002006 }
2007 }
2008 break;
2009 }
2010 }
2011
2012 if (!OutChains.empty()) {
2013 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2014 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002015 }
2016 }
2017
Chris Lattner875def92005-01-11 05:56:49 +00002018 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002019 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002020 Ops.push_back(Op1);
2021 Ops.push_back(Op2);
2022 Ops.push_back(Op3);
2023 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002024 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002025}
2026
Chris Lattner875def92005-01-11 05:56:49 +00002027//===----------------------------------------------------------------------===//
2028// SelectionDAGISel code
2029//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002030
2031unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2032 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2033}
2034
Chris Lattnerc9950c12005-08-17 06:37:43 +00002035void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002036 // FIXME: we only modify the CFG to split critical edges. This
2037 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002038}
Chris Lattner7a60d912005-01-07 07:47:53 +00002039
Chris Lattner35397782005-12-05 07:10:48 +00002040
2041/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2042/// casting to the type of GEPI.
2043static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2044 Value *Ptr, Value *PtrOffset) {
2045 if (V) return V; // Already computed.
2046
2047 BasicBlock::iterator InsertPt;
2048 if (BB == GEPI->getParent()) {
2049 // If insert into the GEP's block, insert right after the GEP.
2050 InsertPt = GEPI;
2051 ++InsertPt;
2052 } else {
2053 // Otherwise, insert at the top of BB, after any PHI nodes
2054 InsertPt = BB->begin();
2055 while (isa<PHINode>(InsertPt)) ++InsertPt;
2056 }
2057
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002058 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2059 // BB so that there is only one value live across basic blocks (the cast
2060 // operand).
2061 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2062 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2063 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2064
Chris Lattner35397782005-12-05 07:10:48 +00002065 // Add the offset, cast it to the right type.
2066 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2067 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2068 return V = Ptr;
2069}
2070
2071
2072/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2073/// selection, we want to be a bit careful about some things. In particular, if
2074/// we have a GEP instruction that is used in a different block than it is
2075/// defined, the addressing expression of the GEP cannot be folded into loads or
2076/// stores that use it. In this case, decompose the GEP and move constant
2077/// indices into blocks that use it.
2078static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2079 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002080 // If this GEP is only used inside the block it is defined in, there is no
2081 // need to rewrite it.
2082 bool isUsedOutsideDefBB = false;
2083 BasicBlock *DefBB = GEPI->getParent();
2084 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2085 UI != E; ++UI) {
2086 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2087 isUsedOutsideDefBB = true;
2088 break;
2089 }
2090 }
2091 if (!isUsedOutsideDefBB) return;
2092
2093 // If this GEP has no non-zero constant indices, there is nothing we can do,
2094 // ignore it.
2095 bool hasConstantIndex = false;
2096 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2097 E = GEPI->op_end(); OI != E; ++OI) {
2098 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2099 if (CI->getRawValue()) {
2100 hasConstantIndex = true;
2101 break;
2102 }
2103 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002104 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2105 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002106
2107 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2108 // constant offset (which we now know is non-zero) and deal with it later.
2109 uint64_t ConstantOffset = 0;
2110 const Type *UIntPtrTy = TD.getIntPtrType();
2111 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2112 const Type *Ty = GEPI->getOperand(0)->getType();
2113
2114 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2115 E = GEPI->op_end(); OI != E; ++OI) {
2116 Value *Idx = *OI;
2117 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2118 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2119 if (Field)
2120 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2121 Ty = StTy->getElementType(Field);
2122 } else {
2123 Ty = cast<SequentialType>(Ty)->getElementType();
2124
2125 // Handle constant subscripts.
2126 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2127 if (CI->getRawValue() == 0) continue;
2128
2129 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2130 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2131 else
2132 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2133 continue;
2134 }
2135
2136 // Ptr = Ptr + Idx * ElementSize;
2137
2138 // Cast Idx to UIntPtrTy if needed.
2139 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2140
2141 uint64_t ElementSize = TD.getTypeSize(Ty);
2142 // Mask off bits that should not be set.
2143 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2144 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2145
2146 // Multiply by the element size and add to the base.
2147 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2148 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2149 }
2150 }
2151
2152 // Make sure that the offset fits in uintptr_t.
2153 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2154 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2155
2156 // Okay, we have now emitted all of the variable index parts to the BB that
2157 // the GEP is defined in. Loop over all of the using instructions, inserting
2158 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002159 // instruction to use the newly computed value, making GEPI dead. When the
2160 // user is a load or store instruction address, we emit the add into the user
2161 // block, otherwise we use a canonical version right next to the gep (these
2162 // won't be foldable as addresses, so we might as well share the computation).
2163
Chris Lattner35397782005-12-05 07:10:48 +00002164 std::map<BasicBlock*,Value*> InsertedExprs;
2165 while (!GEPI->use_empty()) {
2166 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002167
2168 // If this use is not foldable into the addressing mode, use a version
2169 // emitted in the GEP block.
2170 Value *NewVal;
2171 if (!isa<LoadInst>(User) &&
2172 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2173 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2174 Ptr, PtrOffset);
2175 } else {
2176 // Otherwise, insert the code in the User's block so it can be folded into
2177 // any users in that block.
2178 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002179 User->getParent(), GEPI,
2180 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002181 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002182 User->replaceUsesOfWith(GEPI, NewVal);
2183 }
Chris Lattner35397782005-12-05 07:10:48 +00002184
2185 // Finally, the GEP is dead, remove it.
2186 GEPI->eraseFromParent();
2187}
2188
Chris Lattner7a60d912005-01-07 07:47:53 +00002189bool SelectionDAGISel::runOnFunction(Function &Fn) {
2190 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2191 RegMap = MF.getSSARegMap();
2192 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2193
Chris Lattner35397782005-12-05 07:10:48 +00002194 // First, split all critical edges for PHI nodes with incoming values that are
2195 // constants, this way the load of the constant into a vreg will not be placed
2196 // into MBBs that are used some other way.
2197 //
2198 // In this pass we also look for GEP instructions that are used across basic
2199 // blocks and rewrites them to improve basic-block-at-a-time selection.
2200 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002201 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2202 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002203 BasicBlock::iterator BBI;
2204 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002205 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2206 if (isa<Constant>(PN->getIncomingValue(i)))
2207 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002208
2209 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2210 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2211 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002212 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002213
Chris Lattner7a60d912005-01-07 07:47:53 +00002214 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2215
2216 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2217 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002218
Chris Lattner7a60d912005-01-07 07:47:53 +00002219 return true;
2220}
2221
2222
Chris Lattner718b5c22005-01-13 17:59:43 +00002223SDOperand SelectionDAGISel::
2224CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002225 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002226 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002227 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002228 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002229
2230 // If this type is not legal, we must make sure to not create an invalid
2231 // register use.
2232 MVT::ValueType SrcVT = Op.getValueType();
2233 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2234 SelectionDAG &DAG = SDL.DAG;
2235 if (SrcVT == DestVT) {
2236 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2237 } else if (SrcVT < DestVT) {
2238 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002239 if (MVT::isFloatingPoint(SrcVT))
2240 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2241 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002242 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002243 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2244 } else {
2245 // The src value is expanded into multiple registers.
2246 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2247 Op, DAG.getConstant(0, MVT::i32));
2248 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2249 Op, DAG.getConstant(1, MVT::i32));
2250 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2251 return DAG.getCopyToReg(Op, Reg+1, Hi);
2252 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002253}
2254
Chris Lattner16f64df2005-01-17 17:15:02 +00002255void SelectionDAGISel::
2256LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2257 std::vector<SDOperand> &UnorderedChains) {
2258 // If this is the entry block, emit arguments.
2259 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002260 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002261 SDOperand OldRoot = SDL.DAG.getRoot();
2262 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002263
Chris Lattner6871b232005-10-30 19:42:35 +00002264 unsigned a = 0;
2265 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2266 AI != E; ++AI, ++a)
2267 if (!AI->use_empty()) {
2268 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002269
Chris Lattner6871b232005-10-30 19:42:35 +00002270 // If this argument is live outside of the entry block, insert a copy from
2271 // whereever we got it to the vreg that other BB's will reference it as.
2272 if (FuncInfo.ValueMap.count(AI)) {
2273 SDOperand Copy =
2274 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2275 UnorderedChains.push_back(Copy);
2276 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002277 }
Chris Lattner6871b232005-10-30 19:42:35 +00002278
2279 // Next, if the function has live ins that need to be copied into vregs,
2280 // emit the copies now, into the top of the block.
2281 MachineFunction &MF = SDL.DAG.getMachineFunction();
2282 if (MF.livein_begin() != MF.livein_end()) {
2283 SSARegMap *RegMap = MF.getSSARegMap();
2284 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2285 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2286 E = MF.livein_end(); LI != E; ++LI)
2287 if (LI->second)
2288 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2289 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002290 }
Chris Lattner6871b232005-10-30 19:42:35 +00002291
2292 // Finally, if the target has anything special to do, allow it to do so.
2293 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002294}
2295
2296
Chris Lattner7a60d912005-01-07 07:47:53 +00002297void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2298 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2299 FunctionLoweringInfo &FuncInfo) {
2300 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002301
2302 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002303
Chris Lattner6871b232005-10-30 19:42:35 +00002304 // Lower any arguments needed in this block if this is the entry block.
2305 if (LLVMBB == &LLVMBB->getParent()->front())
2306 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002307
2308 BB = FuncInfo.MBBMap[LLVMBB];
2309 SDL.setCurrentBasicBlock(BB);
2310
2311 // Lower all of the non-terminator instructions.
2312 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2313 I != E; ++I)
2314 SDL.visit(*I);
2315
2316 // Ensure that all instructions which are used outside of their defining
2317 // blocks are available as virtual registers.
2318 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002319 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002320 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002321 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002322 UnorderedChains.push_back(
2323 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002324 }
2325
2326 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2327 // ensure constants are generated when needed. Remember the virtual registers
2328 // that need to be added to the Machine PHI nodes as input. We cannot just
2329 // directly add them, because expansion might result in multiple MBB's for one
2330 // BB. As such, the start of the BB might correspond to a different MBB than
2331 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002332 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002333
2334 // Emit constants only once even if used by multiple PHI nodes.
2335 std::map<Constant*, unsigned> ConstantsOut;
2336
2337 // Check successor nodes PHI nodes that expect a constant to be available from
2338 // this block.
2339 TerminatorInst *TI = LLVMBB->getTerminator();
2340 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2341 BasicBlock *SuccBB = TI->getSuccessor(succ);
2342 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2343 PHINode *PN;
2344
2345 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2346 // nodes and Machine PHI nodes, but the incoming operands have not been
2347 // emitted yet.
2348 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002349 (PN = dyn_cast<PHINode>(I)); ++I)
2350 if (!PN->use_empty()) {
2351 unsigned Reg;
2352 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2353 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2354 unsigned &RegOut = ConstantsOut[C];
2355 if (RegOut == 0) {
2356 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002357 UnorderedChains.push_back(
2358 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002359 }
2360 Reg = RegOut;
2361 } else {
2362 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002363 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002364 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002365 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2366 "Didn't codegen value into a register!??");
2367 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002368 UnorderedChains.push_back(
2369 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002370 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002371 }
Misha Brukman835702a2005-04-21 22:36:52 +00002372
Chris Lattner8ea875f2005-01-07 21:34:19 +00002373 // Remember that this register needs to added to the machine PHI node as
2374 // the input for this MBB.
2375 unsigned NumElements =
2376 TLI.getNumElements(TLI.getValueType(PN->getType()));
2377 for (unsigned i = 0, e = NumElements; i != e; ++i)
2378 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002379 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002380 }
2381 ConstantsOut.clear();
2382
Chris Lattner718b5c22005-01-13 17:59:43 +00002383 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002384 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002385 SDOperand Root = SDL.getRoot();
2386 if (Root.getOpcode() != ISD::EntryToken) {
2387 unsigned i = 0, e = UnorderedChains.size();
2388 for (; i != e; ++i) {
2389 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2390 if (UnorderedChains[i].Val->getOperand(0) == Root)
2391 break; // Don't add the root if we already indirectly depend on it.
2392 }
2393
2394 if (i == e)
2395 UnorderedChains.push_back(Root);
2396 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002397 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2398 }
2399
Chris Lattner7a60d912005-01-07 07:47:53 +00002400 // Lower the terminator after the copies are emitted.
2401 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002402
2403 // Make sure the root of the DAG is up-to-date.
2404 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002405}
2406
2407void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2408 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002409 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002410 CurDAG = &DAG;
2411 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2412
2413 // First step, lower LLVM code to some DAG. This DAG may use operations and
2414 // types that are not supported by the target.
2415 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2416
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002417 // Run the DAG combiner in pre-legalize mode.
2418 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002419
Chris Lattner7a60d912005-01-07 07:47:53 +00002420 DEBUG(std::cerr << "Lowered selection DAG:\n");
2421 DEBUG(DAG.dump());
2422
2423 // Second step, hack on the DAG until it only uses operations and types that
2424 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002425 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002426
2427 DEBUG(std::cerr << "Legalized selection DAG:\n");
2428 DEBUG(DAG.dump());
2429
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002430 // Run the DAG combiner in post-legalize mode.
2431 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002432
Evan Cheng739a6a42006-01-21 02:32:06 +00002433 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002434
Chris Lattner5ca31d92005-03-30 01:10:47 +00002435 // Third, instruction select all of the operations to machine code, adding the
2436 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002437 InstructionSelectBasicBlock(DAG);
2438
Chris Lattner7a60d912005-01-07 07:47:53 +00002439 DEBUG(std::cerr << "Selected machine code:\n");
2440 DEBUG(BB->dump());
2441
Chris Lattner5ca31d92005-03-30 01:10:47 +00002442 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002443 // PHI nodes in successors.
2444 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2445 MachineInstr *PHI = PHINodesToUpdate[i].first;
2446 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2447 "This is not a machine PHI node that we are updating!");
2448 PHI->addRegOperand(PHINodesToUpdate[i].second);
2449 PHI->addMachineBasicBlockOperand(BB);
2450 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002451
2452 // Finally, add the CFG edges from the last selected MBB to the successor
2453 // MBBs.
2454 TerminatorInst *TI = LLVMBB->getTerminator();
2455 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2456 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2457 BB->addSuccessor(Succ0MBB);
2458 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002459}
Evan Cheng739a6a42006-01-21 02:32:06 +00002460
2461//===----------------------------------------------------------------------===//
2462/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2463/// target node in the graph.
2464void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2465 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002466 ScheduleDAG *SL = NULL;
2467
2468 switch (ISHeuristic) {
2469 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002470 case defaultScheduling:
2471 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2472 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2473 else /* TargetLowering::SchedulingForRegPressure */
2474 SL = createBURRListDAGScheduler(DAG, BB);
2475 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002476 case noScheduling:
2477 case simpleScheduling:
2478 case simpleNoItinScheduling:
2479 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2480 break;
Evan Cheng31272342006-01-23 08:26:10 +00002481 case listSchedulingBURR:
2482 SL = createBURRListDAGScheduler(DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002483 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002484 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002485 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002486}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002487
2488/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2489/// by tblgen. Others should not call it.
2490void SelectionDAGISel::
2491SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2492 std::vector<SDOperand> InOps;
2493 std::swap(InOps, Ops);
2494
2495 Ops.push_back(InOps[0]); // input chain.
2496 Ops.push_back(InOps[1]); // input asm string.
2497
2498 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2499 unsigned i = 2, e = InOps.size();
2500 if (InOps[e-1].getValueType() == MVT::Flag)
2501 --e; // Don't process a flag operand if it is here.
2502
2503 while (i != e) {
2504 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2505 if ((Flags & 7) != 4 /*MEM*/) {
2506 // Just skip over this operand, copying the operands verbatim.
2507 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2508 i += (Flags >> 3) + 1;
2509 } else {
2510 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2511 // Otherwise, this is a memory operand. Ask the target to select it.
2512 std::vector<SDOperand> SelOps;
2513 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2514 std::cerr << "Could not match memory address. Inline asm failure!\n";
2515 exit(1);
2516 }
2517
2518 // Add this to the output node.
2519 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2520 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2521 i += 2;
2522 }
2523 }
2524
2525 // Add the flag input back if present.
2526 if (e != InOps.size())
2527 Ops.push_back(InOps.back());
2528}