blob: 2f760f65690875a19e2d6e814309c3b35fdce8da [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner49409cb2006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
185/// PHI nodes or outside of the basic block that defines it.
186static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
187 if (isa<PHINode>(I)) return true;
188 BasicBlock *BB = I->getParent();
189 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
190 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
191 return true;
192 return false;
193}
194
Chris Lattner6871b232005-10-30 19:42:35 +0000195/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
196/// entry block, return true.
197static bool isOnlyUsedInEntryBlock(Argument *A) {
198 BasicBlock *Entry = A->getParent()->begin();
199 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != Entry)
201 return false; // Use not in entry block.
202 return true;
203}
204
Chris Lattner7a60d912005-01-07 07:47:53 +0000205FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000206 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
208
Chris Lattner6871b232005-10-30 19:42:35 +0000209 // Create a vreg for each argument register that is not dead and is used
210 // outside of the entry block for the function.
211 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
212 AI != E; ++AI)
213 if (!isOnlyUsedInEntryBlock(AI))
214 InitializeRegForValue(AI);
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216 // Initialize the mapping of values to registers. This is only set up for
217 // instruction values that are used outside of the block that defines
218 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000219 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
222 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
223 const Type *Ty = AI->getAllocatedType();
224 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000225 unsigned Align =
226 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
227 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000228
229 // If the alignment of the value is smaller than the size of the value,
230 // and if the size of the value is particularly small (<= 8 bytes),
231 // round up to the size of the value for potentially better performance.
232 //
233 // FIXME: This could be made better with a preferred alignment hook in
234 // TargetData. It serves primarily to 8-byte align doubles for X86.
235 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000236 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000237 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000239 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 }
241
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000242 for (; BB != EB; ++BB)
243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
245 if (!isa<AllocaInst>(I) ||
246 !StaticAllocaMap.count(cast<AllocaInst>(I)))
247 InitializeRegForValue(I);
248
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000252 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
254 MBBMap[BB] = MBB;
255 MF.getBasicBlockList().push_back(MBB);
256
257 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
258 // appropriate.
259 PHINode *PN;
260 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000261 (PN = dyn_cast<PHINode>(I)); ++I)
262 if (!PN->use_empty()) {
263 unsigned NumElements =
264 TLI.getNumElements(TLI.getValueType(PN->getType()));
265 unsigned PHIReg = ValueMap[PN];
266 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
267 for (unsigned i = 0; i != NumElements; ++i)
268 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
269 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000270 }
271}
272
Chris Lattner49409cb2006-03-16 19:51:18 +0000273/// CreateRegForValue - Allocate the appropriate number of virtual registers of
274/// the correctly promoted or expanded types. Assign these registers
275/// consecutive vreg numbers and return the first assigned number.
276unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278
279 // The number of multiples of registers that we need, to, e.g., split up
280 // a <2 x int64> -> 4 x i32 registers.
281 unsigned NumVectorRegs = 1;
282
283 // If this is a packed type, figure out what type it will decompose into
284 // and how many of the elements it will use.
285 if (VT == MVT::Vector) {
286 const PackedType *PTy = cast<PackedType>(V->getType());
287 unsigned NumElts = PTy->getNumElements();
288 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
289
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
293 NumElts >>= 1;
294 NumVectorRegs <<= 1;
295 }
296 VT = getVectorType(EltTy, NumElts);
297 }
298
299 // The common case is that we will only create one register for this
300 // value. If we have that case, create and return the virtual register.
301 unsigned NV = TLI.getNumElements(VT);
302 if (NV == 1) {
303 // If we are promoting this value, pick the next largest supported type.
304 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
305 unsigned Reg = MakeReg(PromotedType);
306 // If this is a vector of supported or promoted types (e.g. 4 x i16),
307 // create all of the registers.
308 for (unsigned i = 1; i != NumVectorRegs; ++i)
309 MakeReg(PromotedType);
310 return Reg;
311 }
312
313 // If this value is represented with multiple target registers, make sure
314 // to create enough consecutive registers of the right (smaller) type.
315 unsigned NT = VT-1; // Find the type to use.
316 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
317 --NT;
318
319 unsigned R = MakeReg((MVT::ValueType)NT);
320 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
321 MakeReg((MVT::ValueType)NT);
322 return R;
323}
Chris Lattner7a60d912005-01-07 07:47:53 +0000324
325//===----------------------------------------------------------------------===//
326/// SelectionDAGLowering - This is the common target-independent lowering
327/// implementation that is parameterized by a TargetLowering object.
328/// Also, targets can overload any lowering method.
329///
330namespace llvm {
331class SelectionDAGLowering {
332 MachineBasicBlock *CurMBB;
333
334 std::map<const Value*, SDOperand> NodeMap;
335
Chris Lattner4d9651c2005-01-17 22:19:26 +0000336 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
337 /// them up and then emit token factor nodes when possible. This allows us to
338 /// get simple disambiguation between loads without worrying about alias
339 /// analysis.
340 std::vector<SDOperand> PendingLoads;
341
Chris Lattner7a60d912005-01-07 07:47:53 +0000342public:
343 // TLI - This is information that describes the available target features we
344 // need for lowering. This indicates when operations are unavailable,
345 // implemented with a libcall, etc.
346 TargetLowering &TLI;
347 SelectionDAG &DAG;
348 const TargetData &TD;
349
350 /// FuncInfo - Information about the function as a whole.
351 ///
352 FunctionLoweringInfo &FuncInfo;
353
354 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000355 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000356 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
357 FuncInfo(funcinfo) {
358 }
359
Chris Lattner4108bb02005-01-17 19:43:36 +0000360 /// getRoot - Return the current virtual root of the Selection DAG.
361 ///
362 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000363 if (PendingLoads.empty())
364 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000365
Chris Lattner4d9651c2005-01-17 22:19:26 +0000366 if (PendingLoads.size() == 1) {
367 SDOperand Root = PendingLoads[0];
368 DAG.setRoot(Root);
369 PendingLoads.clear();
370 return Root;
371 }
372
373 // Otherwise, we have to make a token factor node.
374 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
375 PendingLoads.clear();
376 DAG.setRoot(Root);
377 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000378 }
379
Chris Lattner7a60d912005-01-07 07:47:53 +0000380 void visit(Instruction &I) { visit(I.getOpcode(), I); }
381
382 void visit(unsigned Opcode, User &I) {
383 switch (Opcode) {
384 default: assert(0 && "Unknown instruction type encountered!");
385 abort();
386 // Build the switch statement using the Instruction.def file.
387#define HANDLE_INST(NUM, OPCODE, CLASS) \
388 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
389#include "llvm/Instruction.def"
390 }
391 }
392
393 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
394
Chris Lattner4024c002006-03-15 22:19:46 +0000395 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
396 SDOperand SrcValue, SDOperand Root,
397 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000398
399 SDOperand getIntPtrConstant(uint64_t Val) {
400 return DAG.getConstant(Val, TLI.getPointerTy());
401 }
402
Chris Lattner8471b152006-03-16 19:57:50 +0000403 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
405 const SDOperand &setValue(const Value *V, SDOperand NewN) {
406 SDOperand &N = NodeMap[V];
407 assert(N.Val == 0 && "Already set a value for this node!");
408 return N = NewN;
409 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000410
Chris Lattner6f87d182006-02-22 22:37:12 +0000411 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
412 MVT::ValueType VT,
413 bool OutReg, bool InReg,
414 std::set<unsigned> &OutputRegs,
415 std::set<unsigned> &InputRegs);
416
Chris Lattner7a60d912005-01-07 07:47:53 +0000417 // Terminator instructions.
418 void visitRet(ReturnInst &I);
419 void visitBr(BranchInst &I);
420 void visitUnreachable(UnreachableInst &I) { /* noop */ }
421
422 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000423 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000424 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000425 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
426 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
427 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
428
429 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000430 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000431 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000432 void visitAdd(User &I) {
433 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000434 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000435 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000436 void visitMul(User &I) {
437 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000438 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000439 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000440 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000441 visitBinary(I,
442 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
443 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000444 }
445 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000446 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000447 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000449 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
450 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
451 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000452 void visitShl(User &I) { visitShift(I, ISD::SHL); }
453 void visitShr(User &I) {
454 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 }
456
457 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
458 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
459 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
460 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
461 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
462 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
463 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
464
465 void visitGetElementPtr(User &I);
466 void visitCast(User &I);
467 void visitSelect(User &I);
468 //
469
470 void visitMalloc(MallocInst &I);
471 void visitFree(FreeInst &I);
472 void visitAlloca(AllocaInst &I);
473 void visitLoad(LoadInst &I);
474 void visitStore(StoreInst &I);
475 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
476 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000477 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000478 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000479
Chris Lattner7a60d912005-01-07 07:47:53 +0000480 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000481 void visitVAArg(VAArgInst &I);
482 void visitVAEnd(CallInst &I);
483 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000484 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000485
Chris Lattner875def92005-01-11 05:56:49 +0000486 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000487
488 void visitUserOp1(Instruction &I) {
489 assert(0 && "UserOp1 should not exist at instruction selection time!");
490 abort();
491 }
492 void visitUserOp2(Instruction &I) {
493 assert(0 && "UserOp2 should not exist at instruction selection time!");
494 abort();
495 }
496};
497} // end namespace llvm
498
Chris Lattner8471b152006-03-16 19:57:50 +0000499SDOperand SelectionDAGLowering::getValue(const Value *V) {
500 SDOperand &N = NodeMap[V];
501 if (N.Val) return N;
502
503 const Type *VTy = V->getType();
504 MVT::ValueType VT = TLI.getValueType(VTy);
505 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
506 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
507 visit(CE->getOpcode(), *CE);
508 assert(N.Val && "visit didn't populate the ValueMap!");
509 return N;
510 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
511 return N = DAG.getGlobalAddress(GV, VT);
512 } else if (isa<ConstantPointerNull>(C)) {
513 return N = DAG.getConstant(0, TLI.getPointerTy());
514 } else if (isa<UndefValue>(C)) {
515 return N = DAG.getNode(ISD::UNDEF, VT);
516 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
517 return N = DAG.getConstantFP(CFP->getValue(), VT);
518 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
519 unsigned NumElements = PTy->getNumElements();
520 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
521 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
522
523 // Now that we know the number and type of the elements, push a
524 // Constant or ConstantFP node onto the ops list for each element of
525 // the packed constant.
526 std::vector<SDOperand> Ops;
527 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
528 if (MVT::isFloatingPoint(PVT)) {
529 for (unsigned i = 0; i != NumElements; ++i) {
530 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
531 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
532 }
533 } else {
534 for (unsigned i = 0; i != NumElements; ++i) {
535 const ConstantIntegral *El =
536 cast<ConstantIntegral>(CP->getOperand(i));
537 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
538 }
539 }
540 } else {
541 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
542 SDOperand Op;
543 if (MVT::isFloatingPoint(PVT))
544 Op = DAG.getConstantFP(0, PVT);
545 else
546 Op = DAG.getConstant(0, PVT);
547 Ops.assign(NumElements, Op);
548 }
549
550 // Handle the case where we have a 1-element vector, in which
551 // case we want to immediately turn it into a scalar constant.
552 if (Ops.size() == 1) {
553 return N = Ops[0];
554 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
555 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
556 } else {
557 // If the packed type isn't legal, then create a ConstantVec node with
558 // generic Vector type instead.
559 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
560 SDOperand Typ = DAG.getValueType(PVT);
561 Ops.insert(Ops.begin(), Typ);
562 Ops.insert(Ops.begin(), Num);
563 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
564 }
565 } else {
566 // Canonicalize all constant ints to be unsigned.
567 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
568 }
569 }
570
571 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
572 std::map<const AllocaInst*, int>::iterator SI =
573 FuncInfo.StaticAllocaMap.find(AI);
574 if (SI != FuncInfo.StaticAllocaMap.end())
575 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
576 }
577
578 std::map<const Value*, unsigned>::const_iterator VMI =
579 FuncInfo.ValueMap.find(V);
580 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
581
582 unsigned InReg = VMI->second;
583
584 // If this type is not legal, make it so now.
585 if (VT == MVT::Vector) {
586 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
587 const PackedType *PTy = cast<PackedType>(VTy);
588 unsigned NumElements = PTy->getNumElements();
589 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
590 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
591 assert(TLI.isTypeLegal(TVT) &&
592 "FIXME: Cannot handle illegal vector types here yet!");
593 VT = TVT;
594 }
595
596 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
597
598 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
599 if (DestVT < VT) {
600 // Source must be expanded. This input value is actually coming from the
601 // register pair VMI->second and VMI->second+1.
602 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
603 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
604 } else {
605 if (DestVT > VT) { // Promotion case
606 if (MVT::isFloatingPoint(VT))
607 N = DAG.getNode(ISD::FP_ROUND, VT, N);
608 else
609 N = DAG.getNode(ISD::TRUNCATE, VT, N);
610 }
611 }
612
613 return N;
614}
615
616
Chris Lattner7a60d912005-01-07 07:47:53 +0000617void SelectionDAGLowering::visitRet(ReturnInst &I) {
618 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000619 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000620 return;
621 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000622 std::vector<SDOperand> NewValues;
623 NewValues.push_back(getRoot());
624 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
625 SDOperand RetOp = getValue(I.getOperand(i));
626
627 // If this is an integer return value, we need to promote it ourselves to
628 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
629 // than sign/zero.
630 if (MVT::isInteger(RetOp.getValueType()) &&
631 RetOp.getValueType() < MVT::i64) {
632 MVT::ValueType TmpVT;
633 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
634 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
635 else
636 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000637
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000638 if (I.getOperand(i)->getType()->isSigned())
639 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
640 else
641 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
642 }
643 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000644 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000645 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000646}
647
648void SelectionDAGLowering::visitBr(BranchInst &I) {
649 // Update machine-CFG edges.
650 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000651
652 // Figure out which block is immediately after the current one.
653 MachineBasicBlock *NextBlock = 0;
654 MachineFunction::iterator BBI = CurMBB;
655 if (++BBI != CurMBB->getParent()->end())
656 NextBlock = BBI;
657
658 if (I.isUnconditional()) {
659 // If this is not a fall-through branch, emit the branch.
660 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000661 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000662 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000663 } else {
664 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000665
666 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000667 if (Succ1MBB == NextBlock) {
668 // If the condition is false, fall through. This means we should branch
669 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000670 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000671 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000672 } else if (Succ0MBB == NextBlock) {
673 // If the condition is true, fall through. This means we should branch if
674 // the condition is false to Succ #1. Invert the condition first.
675 SDOperand True = DAG.getConstant(1, Cond.getValueType());
676 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000677 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000678 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000679 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000680 std::vector<SDOperand> Ops;
681 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000682 // If the false case is the current basic block, then this is a self
683 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
684 // adds an extra instruction in the loop. Instead, invert the
685 // condition and emit "Loop: ... br!cond Loop; br Out.
686 if (CurMBB == Succ1MBB) {
687 std::swap(Succ0MBB, Succ1MBB);
688 SDOperand True = DAG.getConstant(1, Cond.getValueType());
689 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
690 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000691 Ops.push_back(Cond);
692 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
693 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
694 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000695 }
696 }
697}
698
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000699void SelectionDAGLowering::visitSub(User &I) {
700 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000701 if (I.getType()->isFloatingPoint()) {
702 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
703 if (CFP->isExactlyValue(-0.0)) {
704 SDOperand Op2 = getValue(I.getOperand(1));
705 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
706 return;
707 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000708 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000709 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000710}
711
Nate Begemanb2e089c2005-11-19 00:36:38 +0000712void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
713 unsigned VecOp) {
714 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000715 SDOperand Op1 = getValue(I.getOperand(0));
716 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000717
Chris Lattner19baba62005-11-19 18:40:42 +0000718 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000719 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
720 } else if (Ty->isFloatingPoint()) {
721 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
722 } else {
723 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000724 unsigned NumElements = PTy->getNumElements();
725 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000726 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000727
728 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000729 // the Legalize pass does not have to deal with them. Similarly, if the
730 // abstract vector is going to turn into one that the target natively
731 // supports, generate that type now so that Legalize doesn't have to deal
732 // with that either. These steps ensure that Legalize only has to handle
733 // vector types in its Expand case.
734 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000735 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000736 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Chengb97aab42006-03-01 01:09:54 +0000737 } else if (TVT != MVT::Other &&
738 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000739 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000740 } else {
741 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
742 SDOperand Typ = DAG.getValueType(PVT);
Evan Chengb97aab42006-03-01 01:09:54 +0000743 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000744 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000745 }
Nate Begeman127321b2005-11-18 07:42:56 +0000746}
Chris Lattner96c26752005-01-19 22:31:21 +0000747
Nate Begeman127321b2005-11-18 07:42:56 +0000748void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
749 SDOperand Op1 = getValue(I.getOperand(0));
750 SDOperand Op2 = getValue(I.getOperand(1));
751
752 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
753
Chris Lattner7a60d912005-01-07 07:47:53 +0000754 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
755}
756
757void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
758 ISD::CondCode UnsignedOpcode) {
759 SDOperand Op1 = getValue(I.getOperand(0));
760 SDOperand Op2 = getValue(I.getOperand(1));
761 ISD::CondCode Opcode = SignedOpcode;
762 if (I.getOperand(0)->getType()->isUnsigned())
763 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000764 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000765}
766
767void SelectionDAGLowering::visitSelect(User &I) {
768 SDOperand Cond = getValue(I.getOperand(0));
769 SDOperand TrueVal = getValue(I.getOperand(1));
770 SDOperand FalseVal = getValue(I.getOperand(2));
771 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
772 TrueVal, FalseVal));
773}
774
775void SelectionDAGLowering::visitCast(User &I) {
776 SDOperand N = getValue(I.getOperand(0));
Chris Lattner4024c002006-03-15 22:19:46 +0000777 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
778 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +0000779
Chris Lattner4024c002006-03-15 22:19:46 +0000780 if (N.getValueType() == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +0000782 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000783 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +0000784 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000785 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000786 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +0000787 } else if (isInteger(SrcVT)) {
788 if (isInteger(DestVT)) { // Int -> Int cast
789 if (DestVT < SrcVT) // Truncating cast?
790 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000791 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000792 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000793 else
Chris Lattner4024c002006-03-15 22:19:46 +0000794 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000795 } else { // Int -> FP cast
796 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000797 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000798 else
Chris Lattner4024c002006-03-15 22:19:46 +0000799 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000800 }
Chris Lattner4024c002006-03-15 22:19:46 +0000801 } else if (isFloatingPoint(SrcVT)) {
802 if (isFloatingPoint(DestVT)) { // FP -> FP cast
803 if (DestVT < SrcVT) // Rounding cast?
804 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000805 else
Chris Lattner4024c002006-03-15 22:19:46 +0000806 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000807 } else { // FP -> Int cast.
808 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +0000809 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000810 else
Chris Lattner4024c002006-03-15 22:19:46 +0000811 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
812 }
813 } else {
814 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
815 const PackedType *DstTy = cast<PackedType>(I.getType());
816
817 unsigned SrcNumElements = SrcTy->getNumElements();
818 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
819 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
820
821 unsigned DstNumElements = DstTy->getNumElements();
822 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
823 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
824
825 // If the input and output type are legal, convert this to a bit convert of
826 // the SrcTVT/DstTVT types.
827 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
828 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
829 assert(N.getValueType() == SrcTVT);
830 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
831 } else {
832 // Otherwise, convert this directly into a store/load.
833 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
834 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
835 // Create the stack frame object.
836 uint64_t ByteSize = TD.getTypeSize(SrcTy);
837 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
838 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
839 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
840 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
841
842 // Emit a store to the stack slot.
843 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
844 N, FIPtr, DAG.getSrcValue(NULL));
845 // Result is a load from the stack slot.
846 SDOperand Val =
847 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
848 setValue(&I, Val);
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000849 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000850 }
851}
852
853void SelectionDAGLowering::visitGetElementPtr(User &I) {
854 SDOperand N = getValue(I.getOperand(0));
855 const Type *Ty = I.getOperand(0)->getType();
856 const Type *UIntPtrTy = TD.getIntPtrType();
857
858 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
859 OI != E; ++OI) {
860 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000861 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000862 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
863 if (Field) {
864 // N = N + Offset
865 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
866 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000867 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000868 }
869 Ty = StTy->getElementType(Field);
870 } else {
871 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000872
Chris Lattner43535a12005-11-09 04:45:33 +0000873 // If this is a constant subscript, handle it quickly.
874 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
875 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000876
Chris Lattner43535a12005-11-09 04:45:33 +0000877 uint64_t Offs;
878 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
879 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
880 else
881 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
882 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
883 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000884 }
Chris Lattner43535a12005-11-09 04:45:33 +0000885
886 // N = N + Idx * ElementSize;
887 uint64_t ElementSize = TD.getTypeSize(Ty);
888 SDOperand IdxN = getValue(Idx);
889
890 // If the index is smaller or larger than intptr_t, truncate or extend
891 // it.
892 if (IdxN.getValueType() < N.getValueType()) {
893 if (Idx->getType()->isSigned())
894 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
895 else
896 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
897 } else if (IdxN.getValueType() > N.getValueType())
898 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
899
900 // If this is a multiply by a power of two, turn it into a shl
901 // immediately. This is a very common case.
902 if (isPowerOf2_64(ElementSize)) {
903 unsigned Amt = Log2_64(ElementSize);
904 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000905 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000906 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
907 continue;
908 }
909
910 SDOperand Scale = getIntPtrConstant(ElementSize);
911 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
912 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000913 }
914 }
915 setValue(&I, N);
916}
917
918void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
919 // If this is a fixed sized alloca in the entry block of the function,
920 // allocate it statically on the stack.
921 if (FuncInfo.StaticAllocaMap.count(&I))
922 return; // getValue will auto-populate this.
923
924 const Type *Ty = I.getAllocatedType();
925 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000926 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
927 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000928
929 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000930 MVT::ValueType IntPtr = TLI.getPointerTy();
931 if (IntPtr < AllocSize.getValueType())
932 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
933 else if (IntPtr > AllocSize.getValueType())
934 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000935
Chris Lattnereccb73d2005-01-22 23:04:37 +0000936 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000937 getIntPtrConstant(TySize));
938
939 // Handle alignment. If the requested alignment is less than or equal to the
940 // stack alignment, ignore it and round the size of the allocation up to the
941 // stack alignment size. If the size is greater than the stack alignment, we
942 // note this in the DYNAMIC_STACKALLOC node.
943 unsigned StackAlign =
944 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
945 if (Align <= StackAlign) {
946 Align = 0;
947 // Add SA-1 to the size.
948 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
949 getIntPtrConstant(StackAlign-1));
950 // Mask out the low bits for alignment purposes.
951 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
952 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
953 }
954
Chris Lattner96c262e2005-05-14 07:29:57 +0000955 std::vector<MVT::ValueType> VTs;
956 VTs.push_back(AllocSize.getValueType());
957 VTs.push_back(MVT::Other);
958 std::vector<SDOperand> Ops;
959 Ops.push_back(getRoot());
960 Ops.push_back(AllocSize);
961 Ops.push_back(getIntPtrConstant(Align));
962 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000963 DAG.setRoot(setValue(&I, DSA).getValue(1));
964
965 // Inform the Frame Information that we have just allocated a variable-sized
966 // object.
967 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
968}
969
Chris Lattner7a60d912005-01-07 07:47:53 +0000970void SelectionDAGLowering::visitLoad(LoadInst &I) {
971 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000972
Chris Lattner4d9651c2005-01-17 22:19:26 +0000973 SDOperand Root;
974 if (I.isVolatile())
975 Root = getRoot();
976 else {
977 // Do not serialize non-volatile loads against each other.
978 Root = DAG.getRoot();
979 }
Chris Lattner4024c002006-03-15 22:19:46 +0000980
981 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
982 Root, I.isVolatile()));
983}
984
985SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
986 SDOperand SrcValue, SDOperand Root,
987 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000988 SDOperand L;
989
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000990 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000991 unsigned NumElements = PTy->getNumElements();
992 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000993 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000994
995 // Immediately scalarize packed types containing only one element, so that
996 // the Legalize pass does not have to deal with them.
997 if (NumElements == 1) {
Chris Lattner4024c002006-03-15 22:19:46 +0000998 L = DAG.getLoad(PVT, Root, Ptr, SrcValue);
999 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
1000 TLI.isOperationLegal(ISD::LOAD, TVT)) {
1001 L = DAG.getLoad(TVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +00001002 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001003 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, SrcValue);
Nate Begeman07890bb2005-11-22 01:29:36 +00001004 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001005 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001006 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001007 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001008
Chris Lattner4024c002006-03-15 22:19:46 +00001009 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001010 DAG.setRoot(L.getValue(1));
1011 else
1012 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001013
1014 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001015}
1016
1017
1018void SelectionDAGLowering::visitStore(StoreInst &I) {
1019 Value *SrcV = I.getOperand(0);
1020 SDOperand Src = getValue(SrcV);
1021 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001022 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001023 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001024}
1025
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001026/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1027/// we want to emit this as a call to a named external function, return the name
1028/// otherwise lower it and return null.
1029const char *
1030SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1031 switch (Intrinsic) {
1032 case Intrinsic::vastart: visitVAStart(I); return 0;
1033 case Intrinsic::vaend: visitVAEnd(I); return 0;
1034 case Intrinsic::vacopy: visitVACopy(I); return 0;
1035 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1036 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1037 case Intrinsic::setjmp:
1038 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1039 break;
1040 case Intrinsic::longjmp:
1041 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1042 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001043 case Intrinsic::memcpy_i32:
1044 case Intrinsic::memcpy_i64:
1045 visitMemIntrinsic(I, ISD::MEMCPY);
1046 return 0;
1047 case Intrinsic::memset_i32:
1048 case Intrinsic::memset_i64:
1049 visitMemIntrinsic(I, ISD::MEMSET);
1050 return 0;
1051 case Intrinsic::memmove_i32:
1052 case Intrinsic::memmove_i64:
1053 visitMemIntrinsic(I, ISD::MEMMOVE);
1054 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001055
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001056 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001057 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyacb6e342006-03-13 13:07:37 +00001058 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskey5995d012006-02-11 01:01:30 +00001059 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001060
Jim Laskey5995d012006-02-11 01:01:30 +00001061 // Input Chain
1062 Ops.push_back(getRoot());
1063
1064 // line number
Jim Laskeyacb6e342006-03-13 13:07:37 +00001065 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskey5995d012006-02-11 01:01:30 +00001066
1067 // column
Jim Laskeyacb6e342006-03-13 13:07:37 +00001068 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner435b4022005-11-29 06:21:05 +00001069
Jim Laskeyacb6e342006-03-13 13:07:37 +00001070 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskey5995d012006-02-11 01:01:30 +00001071 assert(DD && "Not a debug information descriptor");
1072 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1073 assert(CompileUnit && "Not a compile unit");
1074 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1075 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1076
1077 if (Ops.size() == 5) // Found filename/workingdir.
1078 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001079 }
1080
Chris Lattner8782b782005-12-03 18:50:48 +00001081 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001082 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001083 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001084 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001085 if (I.getType() != Type::VoidTy)
1086 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1087 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001088 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001089 if (I.getType() != Type::VoidTy)
1090 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1091 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001092 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001093 if (I.getType() != Type::VoidTy)
1094 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1095 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001096
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001097 case Intrinsic::isunordered_f32:
1098 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001099 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1100 getValue(I.getOperand(2)), ISD::SETUO));
1101 return 0;
1102
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001103 case Intrinsic::sqrt_f32:
1104 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001105 setValue(&I, DAG.getNode(ISD::FSQRT,
1106 getValue(I.getOperand(1)).getValueType(),
1107 getValue(I.getOperand(1))));
1108 return 0;
1109 case Intrinsic::pcmarker: {
1110 SDOperand Tmp = getValue(I.getOperand(1));
1111 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1112 return 0;
1113 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001114 case Intrinsic::readcyclecounter: {
1115 std::vector<MVT::ValueType> VTs;
1116 VTs.push_back(MVT::i64);
1117 VTs.push_back(MVT::Other);
1118 std::vector<SDOperand> Ops;
1119 Ops.push_back(getRoot());
1120 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1121 setValue(&I, Tmp);
1122 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001123 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001124 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001125 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001126 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001127 case Intrinsic::bswap_i64:
1128 setValue(&I, DAG.getNode(ISD::BSWAP,
1129 getValue(I.getOperand(1)).getValueType(),
1130 getValue(I.getOperand(1))));
1131 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001132 case Intrinsic::cttz_i8:
1133 case Intrinsic::cttz_i16:
1134 case Intrinsic::cttz_i32:
1135 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001136 setValue(&I, DAG.getNode(ISD::CTTZ,
1137 getValue(I.getOperand(1)).getValueType(),
1138 getValue(I.getOperand(1))));
1139 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001140 case Intrinsic::ctlz_i8:
1141 case Intrinsic::ctlz_i16:
1142 case Intrinsic::ctlz_i32:
1143 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001144 setValue(&I, DAG.getNode(ISD::CTLZ,
1145 getValue(I.getOperand(1)).getValueType(),
1146 getValue(I.getOperand(1))));
1147 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001148 case Intrinsic::ctpop_i8:
1149 case Intrinsic::ctpop_i16:
1150 case Intrinsic::ctpop_i32:
1151 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001152 setValue(&I, DAG.getNode(ISD::CTPOP,
1153 getValue(I.getOperand(1)).getValueType(),
1154 getValue(I.getOperand(1))));
1155 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001156 case Intrinsic::stacksave: {
1157 std::vector<MVT::ValueType> VTs;
1158 VTs.push_back(TLI.getPointerTy());
1159 VTs.push_back(MVT::Other);
1160 std::vector<SDOperand> Ops;
1161 Ops.push_back(getRoot());
1162 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1163 setValue(&I, Tmp);
1164 DAG.setRoot(Tmp.getValue(1));
1165 return 0;
1166 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001167 case Intrinsic::stackrestore: {
1168 SDOperand Tmp = getValue(I.getOperand(1));
1169 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001170 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001171 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001172 case Intrinsic::prefetch:
1173 // FIXME: Currently discarding prefetches.
1174 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001175 default:
1176 std::cerr << I;
1177 assert(0 && "This intrinsic is not implemented yet!");
1178 return 0;
1179 }
1180}
1181
1182
Chris Lattner7a60d912005-01-07 07:47:53 +00001183void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001184 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001185 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001186 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001187 if (unsigned IID = F->getIntrinsicID()) {
1188 RenameFn = visitIntrinsicCall(I, IID);
1189 if (!RenameFn)
1190 return;
1191 } else { // Not an LLVM intrinsic.
1192 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001193 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1194 if (I.getNumOperands() == 3 && // Basic sanity checks.
1195 I.getOperand(1)->getType()->isFloatingPoint() &&
1196 I.getType() == I.getOperand(1)->getType() &&
1197 I.getType() == I.getOperand(2)->getType()) {
1198 SDOperand LHS = getValue(I.getOperand(1));
1199 SDOperand RHS = getValue(I.getOperand(2));
1200 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1201 LHS, RHS));
1202 return;
1203 }
1204 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001205 if (I.getNumOperands() == 2 && // Basic sanity checks.
1206 I.getOperand(1)->getType()->isFloatingPoint() &&
1207 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001208 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001209 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1210 return;
1211 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001212 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001213 if (I.getNumOperands() == 2 && // Basic sanity checks.
1214 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001215 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001216 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001217 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1218 return;
1219 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001220 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001221 if (I.getNumOperands() == 2 && // Basic sanity checks.
1222 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001223 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001224 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001225 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1226 return;
1227 }
1228 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001229 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001230 } else if (isa<InlineAsm>(I.getOperand(0))) {
1231 visitInlineAsm(I);
1232 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001233 }
Misha Brukman835702a2005-04-21 22:36:52 +00001234
Chris Lattner18d2b342005-01-08 22:48:57 +00001235 SDOperand Callee;
1236 if (!RenameFn)
1237 Callee = getValue(I.getOperand(0));
1238 else
1239 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001240 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001241 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001242 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1243 Value *Arg = I.getOperand(i);
1244 SDOperand ArgNode = getValue(Arg);
1245 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1246 }
Misha Brukman835702a2005-04-21 22:36:52 +00001247
Nate Begemanf6565252005-03-26 01:29:23 +00001248 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1249 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001250
Chris Lattner1f45cd72005-01-08 19:26:18 +00001251 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001252 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001253 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001254 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001255 setValue(&I, Result.first);
1256 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001257}
1258
Chris Lattner6f87d182006-02-22 22:37:12 +00001259SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001260 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001261 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1262 Chain = Val.getValue(1);
1263 Flag = Val.getValue(2);
1264
1265 // If the result was expanded, copy from the top part.
1266 if (Regs.size() > 1) {
1267 assert(Regs.size() == 2 &&
1268 "Cannot expand to more than 2 elts yet!");
1269 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1270 Chain = Val.getValue(1);
1271 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001272 if (DAG.getTargetLoweringInfo().isLittleEndian())
1273 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1274 else
1275 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001276 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001277
Chris Lattner6f87d182006-02-22 22:37:12 +00001278 // Otherwise, if the return value was promoted, truncate it to the
1279 // appropriate type.
1280 if (RegVT == ValueVT)
1281 return Val;
1282
1283 if (MVT::isInteger(RegVT))
1284 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1285 else
1286 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1287}
1288
Chris Lattner571d9642006-02-23 19:21:04 +00001289/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1290/// specified value into the registers specified by this object. This uses
1291/// Chain/Flag as the input and updates them for the output Chain/Flag.
1292void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001293 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001294 if (Regs.size() == 1) {
1295 // If there is a single register and the types differ, this must be
1296 // a promotion.
1297 if (RegVT != ValueVT) {
1298 if (MVT::isInteger(RegVT))
1299 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1300 else
1301 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1302 }
1303 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1304 Flag = Chain.getValue(1);
1305 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001306 std::vector<unsigned> R(Regs);
1307 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1308 std::reverse(R.begin(), R.end());
1309
1310 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001311 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1312 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001313 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001314 Flag = Chain.getValue(1);
1315 }
1316 }
1317}
Chris Lattner6f87d182006-02-22 22:37:12 +00001318
Chris Lattner571d9642006-02-23 19:21:04 +00001319/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1320/// operand list. This adds the code marker and includes the number of
1321/// values added into it.
1322void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001323 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001324 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1325 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1326 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1327}
Chris Lattner6f87d182006-02-22 22:37:12 +00001328
1329/// isAllocatableRegister - If the specified register is safe to allocate,
1330/// i.e. it isn't a stack pointer or some other special register, return the
1331/// register class for the register. Otherwise, return null.
1332static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001333isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1334 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1335 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1336 E = MRI->regclass_end(); RCI != E; ++RCI) {
1337 const TargetRegisterClass *RC = *RCI;
1338 // If none of the the value types for this register class are valid, we
1339 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1340 bool isLegal = false;
1341 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1342 I != E; ++I) {
1343 if (TLI.isTypeLegal(*I)) {
1344 isLegal = true;
1345 break;
1346 }
1347 }
1348
1349 if (!isLegal) continue;
1350
Chris Lattner6f87d182006-02-22 22:37:12 +00001351 // NOTE: This isn't ideal. In particular, this might allocate the
1352 // frame pointer in functions that need it (due to them not being taken
1353 // out of allocation, because a variable sized allocation hasn't been seen
1354 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001355 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1356 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001357 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001358 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001359 }
1360 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001361}
1362
1363RegsForValue SelectionDAGLowering::
1364GetRegistersForValue(const std::string &ConstrCode,
1365 MVT::ValueType VT, bool isOutReg, bool isInReg,
1366 std::set<unsigned> &OutputRegs,
1367 std::set<unsigned> &InputRegs) {
1368 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1369 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1370 std::vector<unsigned> Regs;
1371
1372 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1373 MVT::ValueType RegVT;
1374 MVT::ValueType ValueVT = VT;
1375
1376 if (PhysReg.first) {
1377 if (VT == MVT::Other)
1378 ValueVT = *PhysReg.second->vt_begin();
1379 RegVT = VT;
1380
1381 // This is a explicit reference to a physical register.
1382 Regs.push_back(PhysReg.first);
1383
1384 // If this is an expanded reference, add the rest of the regs to Regs.
1385 if (NumRegs != 1) {
1386 RegVT = *PhysReg.second->vt_begin();
1387 TargetRegisterClass::iterator I = PhysReg.second->begin();
1388 TargetRegisterClass::iterator E = PhysReg.second->end();
1389 for (; *I != PhysReg.first; ++I)
1390 assert(I != E && "Didn't find reg!");
1391
1392 // Already added the first reg.
1393 --NumRegs; ++I;
1394 for (; NumRegs; --NumRegs, ++I) {
1395 assert(I != E && "Ran out of registers to allocate!");
1396 Regs.push_back(*I);
1397 }
1398 }
1399 return RegsForValue(Regs, RegVT, ValueVT);
1400 }
1401
1402 // This is a reference to a register class. Allocate NumRegs consecutive,
1403 // available, registers from the class.
1404 std::vector<unsigned> RegClassRegs =
1405 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1406
1407 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1408 MachineFunction &MF = *CurMBB->getParent();
1409 unsigned NumAllocated = 0;
1410 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1411 unsigned Reg = RegClassRegs[i];
1412 // See if this register is available.
1413 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1414 (isInReg && InputRegs.count(Reg))) { // Already used.
1415 // Make sure we find consecutive registers.
1416 NumAllocated = 0;
1417 continue;
1418 }
1419
1420 // Check to see if this register is allocatable (i.e. don't give out the
1421 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001422 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001423 if (!RC) {
1424 // Make sure we find consecutive registers.
1425 NumAllocated = 0;
1426 continue;
1427 }
1428
1429 // Okay, this register is good, we can use it.
1430 ++NumAllocated;
1431
1432 // If we allocated enough consecutive
1433 if (NumAllocated == NumRegs) {
1434 unsigned RegStart = (i-NumAllocated)+1;
1435 unsigned RegEnd = i+1;
1436 // Mark all of the allocated registers used.
1437 for (unsigned i = RegStart; i != RegEnd; ++i) {
1438 unsigned Reg = RegClassRegs[i];
1439 Regs.push_back(Reg);
1440 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1441 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1442 }
1443
1444 return RegsForValue(Regs, *RC->vt_begin(), VT);
1445 }
1446 }
1447
1448 // Otherwise, we couldn't allocate enough registers for this.
1449 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001450}
1451
Chris Lattner6f87d182006-02-22 22:37:12 +00001452
Chris Lattner476e67b2006-01-26 22:24:51 +00001453/// visitInlineAsm - Handle a call to an InlineAsm object.
1454///
1455void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1456 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1457
1458 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1459 MVT::Other);
1460
1461 // Note, we treat inline asms both with and without side-effects as the same.
1462 // If an inline asm doesn't have side effects and doesn't access memory, we
1463 // could not choose to not chain it.
1464 bool hasSideEffects = IA->hasSideEffects();
1465
Chris Lattner3a5ed552006-02-01 01:28:23 +00001466 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001467 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001468
1469 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1470 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1471 /// if it is a def of that register.
1472 std::vector<SDOperand> AsmNodeOperands;
1473 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1474 AsmNodeOperands.push_back(AsmStr);
1475
1476 SDOperand Chain = getRoot();
1477 SDOperand Flag;
1478
Chris Lattner1558fc62006-02-01 18:59:47 +00001479 // We fully assign registers here at isel time. This is not optimal, but
1480 // should work. For register classes that correspond to LLVM classes, we
1481 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1482 // over the constraints, collecting fixed registers that we know we can't use.
1483 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001484 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001485 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1486 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1487 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001488
Chris Lattner7ad77df2006-02-22 00:56:39 +00001489 MVT::ValueType OpVT;
1490
1491 // Compute the value type for each operand and add it to ConstraintVTs.
1492 switch (Constraints[i].Type) {
1493 case InlineAsm::isOutput:
1494 if (!Constraints[i].isIndirectOutput) {
1495 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1496 OpVT = TLI.getValueType(I.getType());
1497 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001498 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001499 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1500 OpNum++; // Consumes a call operand.
1501 }
1502 break;
1503 case InlineAsm::isInput:
1504 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1505 OpNum++; // Consumes a call operand.
1506 break;
1507 case InlineAsm::isClobber:
1508 OpVT = MVT::Other;
1509 break;
1510 }
1511
1512 ConstraintVTs.push_back(OpVT);
1513
Chris Lattner6f87d182006-02-22 22:37:12 +00001514 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1515 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001516
Chris Lattner6f87d182006-02-22 22:37:12 +00001517 // Build a list of regs that this operand uses. This always has a single
1518 // element for promoted/expanded operands.
1519 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1520 false, false,
1521 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001522
1523 switch (Constraints[i].Type) {
1524 case InlineAsm::isOutput:
1525 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001526 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001527 // If this is an early-clobber output, it cannot be assigned to the same
1528 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001529 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001530 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001531 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001532 case InlineAsm::isInput:
1533 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001534 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001535 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001536 case InlineAsm::isClobber:
1537 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001538 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1539 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001540 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001541 }
1542 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001543
Chris Lattner5c79f982006-02-21 23:12:12 +00001544 // Loop over all of the inputs, copying the operand values into the
1545 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001546 RegsForValue RetValRegs;
1547 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001548 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001549
Chris Lattner2e56e892006-01-31 02:03:41 +00001550 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001551 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1552 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001553
Chris Lattner3a5ed552006-02-01 01:28:23 +00001554 switch (Constraints[i].Type) {
1555 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001556 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1557 if (ConstraintCode.size() == 1) // not a physreg name.
1558 CTy = TLI.getConstraintType(ConstraintCode[0]);
1559
1560 if (CTy == TargetLowering::C_Memory) {
1561 // Memory output.
1562 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1563
1564 // Check that the operand (the address to store to) isn't a float.
1565 if (!MVT::isInteger(InOperandVal.getValueType()))
1566 assert(0 && "MATCH FAIL!");
1567
1568 if (!Constraints[i].isIndirectOutput)
1569 assert(0 && "MATCH FAIL!");
1570
1571 OpNum++; // Consumes a call operand.
1572
1573 // Extend/truncate to the right pointer type if needed.
1574 MVT::ValueType PtrType = TLI.getPointerTy();
1575 if (InOperandVal.getValueType() < PtrType)
1576 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1577 else if (InOperandVal.getValueType() > PtrType)
1578 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1579
1580 // Add information to the INLINEASM node to know about this output.
1581 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1582 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1583 AsmNodeOperands.push_back(InOperandVal);
1584 break;
1585 }
1586
1587 // Otherwise, this is a register output.
1588 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1589
Chris Lattner6f87d182006-02-22 22:37:12 +00001590 // If this is an early-clobber output, or if there is an input
1591 // constraint that matches this, we need to reserve the input register
1592 // so no other inputs allocate to it.
1593 bool UsesInputRegister = false;
1594 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1595 UsesInputRegister = true;
1596
1597 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001598 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001599 RegsForValue Regs =
1600 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1601 true, UsesInputRegister,
1602 OutputRegs, InputRegs);
1603 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001604
Chris Lattner3a5ed552006-02-01 01:28:23 +00001605 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001606 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001607 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001608 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001609 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001610 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001611 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1612 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001613 OpNum++; // Consumes a call operand.
1614 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001615
1616 // Add information to the INLINEASM node to know that this register is
1617 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001618 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001619 break;
1620 }
1621 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001622 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001623 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001624
Chris Lattner7f5880b2006-02-02 00:25:23 +00001625 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1626 // If this is required to match an output register we have already set,
1627 // just use its register.
1628 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001629
Chris Lattner571d9642006-02-23 19:21:04 +00001630 // Scan until we find the definition we already emitted of this operand.
1631 // When we find it, create a RegsForValue operand.
1632 unsigned CurOp = 2; // The first operand.
1633 for (; OperandNo; --OperandNo) {
1634 // Advance to the next operand.
1635 unsigned NumOps =
1636 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1637 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1638 "Skipped past definitions?");
1639 CurOp += (NumOps>>3)+1;
1640 }
1641
1642 unsigned NumOps =
1643 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1644 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1645 "Skipped past definitions?");
1646
1647 // Add NumOps>>3 registers to MatchedRegs.
1648 RegsForValue MatchedRegs;
1649 MatchedRegs.ValueVT = InOperandVal.getValueType();
1650 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1651 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1652 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1653 MatchedRegs.Regs.push_back(Reg);
1654 }
1655
1656 // Use the produced MatchedRegs object to
1657 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1658 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001659 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001660 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001661
1662 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1663 if (ConstraintCode.size() == 1) // not a physreg name.
1664 CTy = TLI.getConstraintType(ConstraintCode[0]);
1665
1666 if (CTy == TargetLowering::C_Other) {
1667 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1668 assert(0 && "MATCH FAIL!");
1669
1670 // Add information to the INLINEASM node to know about this input.
1671 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1672 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1673 AsmNodeOperands.push_back(InOperandVal);
1674 break;
1675 } else if (CTy == TargetLowering::C_Memory) {
1676 // Memory input.
1677
1678 // Check that the operand isn't a float.
1679 if (!MVT::isInteger(InOperandVal.getValueType()))
1680 assert(0 && "MATCH FAIL!");
1681
1682 // Extend/truncate to the right pointer type if needed.
1683 MVT::ValueType PtrType = TLI.getPointerTy();
1684 if (InOperandVal.getValueType() < PtrType)
1685 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1686 else if (InOperandVal.getValueType() > PtrType)
1687 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1688
1689 // Add information to the INLINEASM node to know about this input.
1690 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1691 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1692 AsmNodeOperands.push_back(InOperandVal);
1693 break;
1694 }
1695
1696 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1697
1698 // Copy the input into the appropriate registers.
1699 RegsForValue InRegs =
1700 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1701 false, true, OutputRegs, InputRegs);
1702 // FIXME: should be match fail.
1703 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1704
1705 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1706
1707 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001708 break;
1709 }
Chris Lattner571d9642006-02-23 19:21:04 +00001710 case InlineAsm::isClobber: {
1711 RegsForValue ClobberedRegs =
1712 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1713 OutputRegs, InputRegs);
1714 // Add the clobbered value to the operand list, so that the register
1715 // allocator is aware that the physreg got clobbered.
1716 if (!ClobberedRegs.Regs.empty())
1717 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001718 break;
1719 }
Chris Lattner571d9642006-02-23 19:21:04 +00001720 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001721 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001722
1723 // Finish up input operands.
1724 AsmNodeOperands[0] = Chain;
1725 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1726
1727 std::vector<MVT::ValueType> VTs;
1728 VTs.push_back(MVT::Other);
1729 VTs.push_back(MVT::Flag);
1730 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1731 Flag = Chain.getValue(1);
1732
Chris Lattner2e56e892006-01-31 02:03:41 +00001733 // If this asm returns a register value, copy the result from that register
1734 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001735 if (!RetValRegs.Regs.empty())
1736 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001737
Chris Lattner2e56e892006-01-31 02:03:41 +00001738 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1739
1740 // Process indirect outputs, first output all of the flagged copies out of
1741 // physregs.
1742 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001743 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001744 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001745 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1746 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001747 }
1748
1749 // Emit the non-flagged stores from the physregs.
1750 std::vector<SDOperand> OutChains;
1751 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1752 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1753 StoresToEmit[i].first,
1754 getValue(StoresToEmit[i].second),
1755 DAG.getSrcValue(StoresToEmit[i].second)));
1756 if (!OutChains.empty())
1757 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001758 DAG.setRoot(Chain);
1759}
1760
1761
Chris Lattner7a60d912005-01-07 07:47:53 +00001762void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1763 SDOperand Src = getValue(I.getOperand(0));
1764
1765 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001766
1767 if (IntPtr < Src.getValueType())
1768 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1769 else if (IntPtr > Src.getValueType())
1770 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001771
1772 // Scale the source by the type size.
1773 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1774 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1775 Src, getIntPtrConstant(ElementSize));
1776
1777 std::vector<std::pair<SDOperand, const Type*> > Args;
1778 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001779
1780 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001781 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001782 DAG.getExternalSymbol("malloc", IntPtr),
1783 Args, DAG);
1784 setValue(&I, Result.first); // Pointers always fit in registers
1785 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001786}
1787
1788void SelectionDAGLowering::visitFree(FreeInst &I) {
1789 std::vector<std::pair<SDOperand, const Type*> > Args;
1790 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1791 TLI.getTargetData().getIntPtrType()));
1792 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001793 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001794 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001795 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1796 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001797}
1798
Chris Lattner13d7c252005-08-26 20:54:47 +00001799// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1800// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1801// instructions are special in various ways, which require special support to
1802// insert. The specified MachineInstr is created but not inserted into any
1803// basic blocks, and the scheduler passes ownership of it to this method.
1804MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1805 MachineBasicBlock *MBB) {
1806 std::cerr << "If a target marks an instruction with "
1807 "'usesCustomDAGSchedInserter', it must implement "
1808 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1809 abort();
1810 return 0;
1811}
1812
Chris Lattner58cfd792005-01-09 00:00:49 +00001813void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001814 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1815 getValue(I.getOperand(1)),
1816 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001817}
1818
1819void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001820 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1821 getValue(I.getOperand(0)),
1822 DAG.getSrcValue(I.getOperand(0)));
1823 setValue(&I, V);
1824 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001825}
1826
1827void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001828 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1829 getValue(I.getOperand(1)),
1830 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001831}
1832
1833void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001834 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1835 getValue(I.getOperand(1)),
1836 getValue(I.getOperand(2)),
1837 DAG.getSrcValue(I.getOperand(1)),
1838 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001839}
1840
Chris Lattner58cfd792005-01-09 00:00:49 +00001841// It is always conservatively correct for llvm.returnaddress and
1842// llvm.frameaddress to return 0.
1843std::pair<SDOperand, SDOperand>
1844TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1845 unsigned Depth, SelectionDAG &DAG) {
1846 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001847}
1848
Chris Lattner29dcc712005-05-14 05:50:48 +00001849SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001850 assert(0 && "LowerOperation not implemented for this target!");
1851 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001852 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001853}
1854
Nate Begeman595ec732006-01-28 03:14:31 +00001855SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1856 SelectionDAG &DAG) {
1857 assert(0 && "CustomPromoteOperation not implemented for this target!");
1858 abort();
1859 return SDOperand();
1860}
1861
Chris Lattner58cfd792005-01-09 00:00:49 +00001862void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1863 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1864 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001865 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001866 setValue(&I, Result.first);
1867 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001868}
1869
Evan Cheng6781b6e2006-02-15 21:59:04 +00001870/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001871/// operand.
1872static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001873 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001874 MVT::ValueType CurVT = VT;
1875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1876 uint64_t Val = C->getValue() & 255;
1877 unsigned Shift = 8;
1878 while (CurVT != MVT::i8) {
1879 Val = (Val << Shift) | Val;
1880 Shift <<= 1;
1881 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001882 }
1883 return DAG.getConstant(Val, VT);
1884 } else {
1885 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1886 unsigned Shift = 8;
1887 while (CurVT != MVT::i8) {
1888 Value =
1889 DAG.getNode(ISD::OR, VT,
1890 DAG.getNode(ISD::SHL, VT, Value,
1891 DAG.getConstant(Shift, MVT::i8)), Value);
1892 Shift <<= 1;
1893 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001894 }
1895
1896 return Value;
1897 }
1898}
1899
Evan Cheng6781b6e2006-02-15 21:59:04 +00001900/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1901/// used when a memcpy is turned into a memset when the source is a constant
1902/// string ptr.
1903static SDOperand getMemsetStringVal(MVT::ValueType VT,
1904 SelectionDAG &DAG, TargetLowering &TLI,
1905 std::string &Str, unsigned Offset) {
1906 MVT::ValueType CurVT = VT;
1907 uint64_t Val = 0;
1908 unsigned MSB = getSizeInBits(VT) / 8;
1909 if (TLI.isLittleEndian())
1910 Offset = Offset + MSB - 1;
1911 for (unsigned i = 0; i != MSB; ++i) {
1912 Val = (Val << 8) | Str[Offset];
1913 Offset += TLI.isLittleEndian() ? -1 : 1;
1914 }
1915 return DAG.getConstant(Val, VT);
1916}
1917
Evan Cheng81fcea82006-02-14 08:22:34 +00001918/// getMemBasePlusOffset - Returns base and offset node for the
1919static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1920 SelectionDAG &DAG, TargetLowering &TLI) {
1921 MVT::ValueType VT = Base.getValueType();
1922 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1923}
1924
Evan Chengdb2a7a72006-02-14 20:12:38 +00001925/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001926/// to replace the memset / memcpy is below the threshold. It also returns the
1927/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001928static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1929 unsigned Limit, uint64_t Size,
1930 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001931 MVT::ValueType VT;
1932
1933 if (TLI.allowsUnalignedMemoryAccesses()) {
1934 VT = MVT::i64;
1935 } else {
1936 switch (Align & 7) {
1937 case 0:
1938 VT = MVT::i64;
1939 break;
1940 case 4:
1941 VT = MVT::i32;
1942 break;
1943 case 2:
1944 VT = MVT::i16;
1945 break;
1946 default:
1947 VT = MVT::i8;
1948 break;
1949 }
1950 }
1951
Evan Chengd5026102006-02-14 09:11:59 +00001952 MVT::ValueType LVT = MVT::i64;
1953 while (!TLI.isTypeLegal(LVT))
1954 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1955 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001956
Evan Chengd5026102006-02-14 09:11:59 +00001957 if (VT > LVT)
1958 VT = LVT;
1959
Evan Cheng04514992006-02-14 23:05:54 +00001960 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001961 while (Size != 0) {
1962 unsigned VTSize = getSizeInBits(VT) / 8;
1963 while (VTSize > Size) {
1964 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001965 VTSize >>= 1;
1966 }
Evan Chengd5026102006-02-14 09:11:59 +00001967 assert(MVT::isInteger(VT));
1968
1969 if (++NumMemOps > Limit)
1970 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001971 MemOps.push_back(VT);
1972 Size -= VTSize;
1973 }
Evan Chengd5026102006-02-14 09:11:59 +00001974
1975 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001976}
1977
Chris Lattner875def92005-01-11 05:56:49 +00001978void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001979 SDOperand Op1 = getValue(I.getOperand(1));
1980 SDOperand Op2 = getValue(I.getOperand(2));
1981 SDOperand Op3 = getValue(I.getOperand(3));
1982 SDOperand Op4 = getValue(I.getOperand(4));
1983 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1984 if (Align == 0) Align = 1;
1985
1986 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1987 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001988
1989 // Expand memset / memcpy to a series of load / store ops
1990 // if the size operand falls below a certain threshold.
1991 std::vector<SDOperand> OutChains;
1992 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001993 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001994 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001995 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1996 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001997 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001998 unsigned Offset = 0;
1999 for (unsigned i = 0; i < NumMemOps; i++) {
2000 MVT::ValueType VT = MemOps[i];
2001 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002002 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002003 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2004 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002005 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2006 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002007 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002008 Offset += VTSize;
2009 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002010 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002011 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002012 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002013 case ISD::MEMCPY: {
2014 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2015 Size->getValue(), Align, TLI)) {
2016 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002017 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002018 GlobalAddressSDNode *G = NULL;
2019 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002020 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002021
2022 if (Op2.getOpcode() == ISD::GlobalAddress)
2023 G = cast<GlobalAddressSDNode>(Op2);
2024 else if (Op2.getOpcode() == ISD::ADD &&
2025 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2026 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2027 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002028 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002029 }
2030 if (G) {
2031 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002032 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002033 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002034 if (!Str.empty()) {
2035 CopyFromStr = true;
2036 SrcOff += SrcDelta;
2037 }
2038 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002039 }
2040
Evan Chenge2038bd2006-02-15 01:54:51 +00002041 for (unsigned i = 0; i < NumMemOps; i++) {
2042 MVT::ValueType VT = MemOps[i];
2043 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002044 SDOperand Value, Chain, Store;
2045
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002046 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002047 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2048 Chain = getRoot();
2049 Store =
2050 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2051 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2052 DAG.getSrcValue(I.getOperand(1), DstOff));
2053 } else {
2054 Value = DAG.getLoad(VT, getRoot(),
2055 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2056 DAG.getSrcValue(I.getOperand(2), SrcOff));
2057 Chain = Value.getValue(1);
2058 Store =
2059 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2060 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2061 DAG.getSrcValue(I.getOperand(1), DstOff));
2062 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002063 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002064 SrcOff += VTSize;
2065 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002066 }
2067 }
2068 break;
2069 }
2070 }
2071
2072 if (!OutChains.empty()) {
2073 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2074 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002075 }
2076 }
2077
Chris Lattner875def92005-01-11 05:56:49 +00002078 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002079 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002080 Ops.push_back(Op1);
2081 Ops.push_back(Op2);
2082 Ops.push_back(Op3);
2083 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002084 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002085}
2086
Chris Lattner875def92005-01-11 05:56:49 +00002087//===----------------------------------------------------------------------===//
2088// SelectionDAGISel code
2089//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002090
2091unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2092 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2093}
2094
Chris Lattnerc9950c12005-08-17 06:37:43 +00002095void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002096 // FIXME: we only modify the CFG to split critical edges. This
2097 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002098}
Chris Lattner7a60d912005-01-07 07:47:53 +00002099
Chris Lattner35397782005-12-05 07:10:48 +00002100
2101/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2102/// casting to the type of GEPI.
2103static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2104 Value *Ptr, Value *PtrOffset) {
2105 if (V) return V; // Already computed.
2106
2107 BasicBlock::iterator InsertPt;
2108 if (BB == GEPI->getParent()) {
2109 // If insert into the GEP's block, insert right after the GEP.
2110 InsertPt = GEPI;
2111 ++InsertPt;
2112 } else {
2113 // Otherwise, insert at the top of BB, after any PHI nodes
2114 InsertPt = BB->begin();
2115 while (isa<PHINode>(InsertPt)) ++InsertPt;
2116 }
2117
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002118 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2119 // BB so that there is only one value live across basic blocks (the cast
2120 // operand).
2121 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2122 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2123 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2124
Chris Lattner35397782005-12-05 07:10:48 +00002125 // Add the offset, cast it to the right type.
2126 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2127 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2128 return V = Ptr;
2129}
2130
2131
2132/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2133/// selection, we want to be a bit careful about some things. In particular, if
2134/// we have a GEP instruction that is used in a different block than it is
2135/// defined, the addressing expression of the GEP cannot be folded into loads or
2136/// stores that use it. In this case, decompose the GEP and move constant
2137/// indices into blocks that use it.
2138static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2139 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002140 // If this GEP is only used inside the block it is defined in, there is no
2141 // need to rewrite it.
2142 bool isUsedOutsideDefBB = false;
2143 BasicBlock *DefBB = GEPI->getParent();
2144 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2145 UI != E; ++UI) {
2146 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2147 isUsedOutsideDefBB = true;
2148 break;
2149 }
2150 }
2151 if (!isUsedOutsideDefBB) return;
2152
2153 // If this GEP has no non-zero constant indices, there is nothing we can do,
2154 // ignore it.
2155 bool hasConstantIndex = false;
2156 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2157 E = GEPI->op_end(); OI != E; ++OI) {
2158 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2159 if (CI->getRawValue()) {
2160 hasConstantIndex = true;
2161 break;
2162 }
2163 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002164 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2165 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002166
2167 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2168 // constant offset (which we now know is non-zero) and deal with it later.
2169 uint64_t ConstantOffset = 0;
2170 const Type *UIntPtrTy = TD.getIntPtrType();
2171 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2172 const Type *Ty = GEPI->getOperand(0)->getType();
2173
2174 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2175 E = GEPI->op_end(); OI != E; ++OI) {
2176 Value *Idx = *OI;
2177 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2178 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2179 if (Field)
2180 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2181 Ty = StTy->getElementType(Field);
2182 } else {
2183 Ty = cast<SequentialType>(Ty)->getElementType();
2184
2185 // Handle constant subscripts.
2186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2187 if (CI->getRawValue() == 0) continue;
2188
2189 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2190 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2191 else
2192 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2193 continue;
2194 }
2195
2196 // Ptr = Ptr + Idx * ElementSize;
2197
2198 // Cast Idx to UIntPtrTy if needed.
2199 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2200
2201 uint64_t ElementSize = TD.getTypeSize(Ty);
2202 // Mask off bits that should not be set.
2203 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2204 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2205
2206 // Multiply by the element size and add to the base.
2207 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2208 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2209 }
2210 }
2211
2212 // Make sure that the offset fits in uintptr_t.
2213 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2214 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2215
2216 // Okay, we have now emitted all of the variable index parts to the BB that
2217 // the GEP is defined in. Loop over all of the using instructions, inserting
2218 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002219 // instruction to use the newly computed value, making GEPI dead. When the
2220 // user is a load or store instruction address, we emit the add into the user
2221 // block, otherwise we use a canonical version right next to the gep (these
2222 // won't be foldable as addresses, so we might as well share the computation).
2223
Chris Lattner35397782005-12-05 07:10:48 +00002224 std::map<BasicBlock*,Value*> InsertedExprs;
2225 while (!GEPI->use_empty()) {
2226 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002227
2228 // If this use is not foldable into the addressing mode, use a version
2229 // emitted in the GEP block.
2230 Value *NewVal;
2231 if (!isa<LoadInst>(User) &&
2232 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2233 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2234 Ptr, PtrOffset);
2235 } else {
2236 // Otherwise, insert the code in the User's block so it can be folded into
2237 // any users in that block.
2238 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002239 User->getParent(), GEPI,
2240 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002241 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002242 User->replaceUsesOfWith(GEPI, NewVal);
2243 }
Chris Lattner35397782005-12-05 07:10:48 +00002244
2245 // Finally, the GEP is dead, remove it.
2246 GEPI->eraseFromParent();
2247}
2248
Chris Lattner7a60d912005-01-07 07:47:53 +00002249bool SelectionDAGISel::runOnFunction(Function &Fn) {
2250 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2251 RegMap = MF.getSSARegMap();
2252 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2253
Chris Lattner35397782005-12-05 07:10:48 +00002254 // First, split all critical edges for PHI nodes with incoming values that are
2255 // constants, this way the load of the constant into a vreg will not be placed
2256 // into MBBs that are used some other way.
2257 //
2258 // In this pass we also look for GEP instructions that are used across basic
2259 // blocks and rewrites them to improve basic-block-at-a-time selection.
2260 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002261 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2262 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002263 BasicBlock::iterator BBI;
2264 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002265 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2266 if (isa<Constant>(PN->getIncomingValue(i)))
2267 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002268
2269 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2270 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2271 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002272 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002273
Chris Lattner7a60d912005-01-07 07:47:53 +00002274 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2275
2276 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2277 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002278
Chris Lattner7a60d912005-01-07 07:47:53 +00002279 return true;
2280}
2281
2282
Chris Lattner718b5c22005-01-13 17:59:43 +00002283SDOperand SelectionDAGISel::
2284CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002285 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002286 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002287 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002288 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002289
2290 // If this type is not legal, we must make sure to not create an invalid
2291 // register use.
2292 MVT::ValueType SrcVT = Op.getValueType();
2293 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2294 SelectionDAG &DAG = SDL.DAG;
2295 if (SrcVT == DestVT) {
2296 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2297 } else if (SrcVT < DestVT) {
2298 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002299 if (MVT::isFloatingPoint(SrcVT))
2300 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2301 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002302 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002303 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2304 } else {
2305 // The src value is expanded into multiple registers.
2306 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2307 Op, DAG.getConstant(0, MVT::i32));
2308 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2309 Op, DAG.getConstant(1, MVT::i32));
2310 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2311 return DAG.getCopyToReg(Op, Reg+1, Hi);
2312 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002313}
2314
Chris Lattner16f64df2005-01-17 17:15:02 +00002315void SelectionDAGISel::
2316LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2317 std::vector<SDOperand> &UnorderedChains) {
2318 // If this is the entry block, emit arguments.
2319 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002320 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002321 SDOperand OldRoot = SDL.DAG.getRoot();
2322 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002323
Chris Lattner6871b232005-10-30 19:42:35 +00002324 unsigned a = 0;
2325 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2326 AI != E; ++AI, ++a)
2327 if (!AI->use_empty()) {
2328 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002329
Chris Lattner6871b232005-10-30 19:42:35 +00002330 // If this argument is live outside of the entry block, insert a copy from
2331 // whereever we got it to the vreg that other BB's will reference it as.
2332 if (FuncInfo.ValueMap.count(AI)) {
2333 SDOperand Copy =
2334 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2335 UnorderedChains.push_back(Copy);
2336 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002337 }
Chris Lattner6871b232005-10-30 19:42:35 +00002338
2339 // Next, if the function has live ins that need to be copied into vregs,
2340 // emit the copies now, into the top of the block.
2341 MachineFunction &MF = SDL.DAG.getMachineFunction();
2342 if (MF.livein_begin() != MF.livein_end()) {
2343 SSARegMap *RegMap = MF.getSSARegMap();
2344 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2345 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2346 E = MF.livein_end(); LI != E; ++LI)
2347 if (LI->second)
2348 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2349 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002350 }
Chris Lattner6871b232005-10-30 19:42:35 +00002351
2352 // Finally, if the target has anything special to do, allow it to do so.
2353 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002354}
2355
2356
Chris Lattner7a60d912005-01-07 07:47:53 +00002357void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2358 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2359 FunctionLoweringInfo &FuncInfo) {
2360 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002361
2362 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002363
Chris Lattner6871b232005-10-30 19:42:35 +00002364 // Lower any arguments needed in this block if this is the entry block.
2365 if (LLVMBB == &LLVMBB->getParent()->front())
2366 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002367
2368 BB = FuncInfo.MBBMap[LLVMBB];
2369 SDL.setCurrentBasicBlock(BB);
2370
2371 // Lower all of the non-terminator instructions.
2372 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2373 I != E; ++I)
2374 SDL.visit(*I);
2375
2376 // Ensure that all instructions which are used outside of their defining
2377 // blocks are available as virtual registers.
2378 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002379 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002380 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002381 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002382 UnorderedChains.push_back(
2383 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002384 }
2385
2386 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2387 // ensure constants are generated when needed. Remember the virtual registers
2388 // that need to be added to the Machine PHI nodes as input. We cannot just
2389 // directly add them, because expansion might result in multiple MBB's for one
2390 // BB. As such, the start of the BB might correspond to a different MBB than
2391 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002392 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002393
2394 // Emit constants only once even if used by multiple PHI nodes.
2395 std::map<Constant*, unsigned> ConstantsOut;
2396
2397 // Check successor nodes PHI nodes that expect a constant to be available from
2398 // this block.
2399 TerminatorInst *TI = LLVMBB->getTerminator();
2400 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2401 BasicBlock *SuccBB = TI->getSuccessor(succ);
2402 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2403 PHINode *PN;
2404
2405 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2406 // nodes and Machine PHI nodes, but the incoming operands have not been
2407 // emitted yet.
2408 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002409 (PN = dyn_cast<PHINode>(I)); ++I)
2410 if (!PN->use_empty()) {
2411 unsigned Reg;
2412 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2413 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2414 unsigned &RegOut = ConstantsOut[C];
2415 if (RegOut == 0) {
2416 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002417 UnorderedChains.push_back(
2418 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002419 }
2420 Reg = RegOut;
2421 } else {
2422 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002423 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002424 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002425 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2426 "Didn't codegen value into a register!??");
2427 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002428 UnorderedChains.push_back(
2429 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002430 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002431 }
Misha Brukman835702a2005-04-21 22:36:52 +00002432
Chris Lattner8ea875f2005-01-07 21:34:19 +00002433 // Remember that this register needs to added to the machine PHI node as
2434 // the input for this MBB.
2435 unsigned NumElements =
2436 TLI.getNumElements(TLI.getValueType(PN->getType()));
2437 for (unsigned i = 0, e = NumElements; i != e; ++i)
2438 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002439 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002440 }
2441 ConstantsOut.clear();
2442
Chris Lattner718b5c22005-01-13 17:59:43 +00002443 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002444 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002445 SDOperand Root = SDL.getRoot();
2446 if (Root.getOpcode() != ISD::EntryToken) {
2447 unsigned i = 0, e = UnorderedChains.size();
2448 for (; i != e; ++i) {
2449 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2450 if (UnorderedChains[i].Val->getOperand(0) == Root)
2451 break; // Don't add the root if we already indirectly depend on it.
2452 }
2453
2454 if (i == e)
2455 UnorderedChains.push_back(Root);
2456 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002457 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2458 }
2459
Chris Lattner7a60d912005-01-07 07:47:53 +00002460 // Lower the terminator after the copies are emitted.
2461 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002462
2463 // Make sure the root of the DAG is up-to-date.
2464 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002465}
2466
2467void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2468 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002469 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002470 CurDAG = &DAG;
2471 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2472
2473 // First step, lower LLVM code to some DAG. This DAG may use operations and
2474 // types that are not supported by the target.
2475 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2476
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002477 // Run the DAG combiner in pre-legalize mode.
2478 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002479
Chris Lattner7a60d912005-01-07 07:47:53 +00002480 DEBUG(std::cerr << "Lowered selection DAG:\n");
2481 DEBUG(DAG.dump());
2482
2483 // Second step, hack on the DAG until it only uses operations and types that
2484 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002485 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002486
2487 DEBUG(std::cerr << "Legalized selection DAG:\n");
2488 DEBUG(DAG.dump());
2489
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002490 // Run the DAG combiner in post-legalize mode.
2491 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002492
Evan Cheng739a6a42006-01-21 02:32:06 +00002493 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002494
Chris Lattner5ca31d92005-03-30 01:10:47 +00002495 // Third, instruction select all of the operations to machine code, adding the
2496 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002497 InstructionSelectBasicBlock(DAG);
2498
Chris Lattner7a60d912005-01-07 07:47:53 +00002499 DEBUG(std::cerr << "Selected machine code:\n");
2500 DEBUG(BB->dump());
2501
Chris Lattner5ca31d92005-03-30 01:10:47 +00002502 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002503 // PHI nodes in successors.
2504 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2505 MachineInstr *PHI = PHINodesToUpdate[i].first;
2506 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2507 "This is not a machine PHI node that we are updating!");
2508 PHI->addRegOperand(PHINodesToUpdate[i].second);
2509 PHI->addMachineBasicBlockOperand(BB);
2510 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002511
2512 // Finally, add the CFG edges from the last selected MBB to the successor
2513 // MBBs.
2514 TerminatorInst *TI = LLVMBB->getTerminator();
2515 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2516 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2517 BB->addSuccessor(Succ0MBB);
2518 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002519}
Evan Cheng739a6a42006-01-21 02:32:06 +00002520
2521//===----------------------------------------------------------------------===//
2522/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2523/// target node in the graph.
2524void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2525 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002526 ScheduleDAG *SL = NULL;
2527
2528 switch (ISHeuristic) {
2529 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002530 case defaultScheduling:
2531 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2532 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2533 else /* TargetLowering::SchedulingForRegPressure */
2534 SL = createBURRListDAGScheduler(DAG, BB);
2535 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002536 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002537 SL = createBFS_DAGScheduler(DAG, BB);
2538 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002539 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002540 SL = createSimpleDAGScheduler(false, DAG, BB);
2541 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002542 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002543 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002544 break;
Evan Cheng31272342006-01-23 08:26:10 +00002545 case listSchedulingBURR:
2546 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002547 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002548 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002549 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002550 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002551 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002552 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002553 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002554}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002555
Chris Lattner543832d2006-03-08 04:25:59 +00002556HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2557 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002558}
2559
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002560/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2561/// by tblgen. Others should not call it.
2562void SelectionDAGISel::
2563SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2564 std::vector<SDOperand> InOps;
2565 std::swap(InOps, Ops);
2566
2567 Ops.push_back(InOps[0]); // input chain.
2568 Ops.push_back(InOps[1]); // input asm string.
2569
2570 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2571 unsigned i = 2, e = InOps.size();
2572 if (InOps[e-1].getValueType() == MVT::Flag)
2573 --e; // Don't process a flag operand if it is here.
2574
2575 while (i != e) {
2576 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2577 if ((Flags & 7) != 4 /*MEM*/) {
2578 // Just skip over this operand, copying the operands verbatim.
2579 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2580 i += (Flags >> 3) + 1;
2581 } else {
2582 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2583 // Otherwise, this is a memory operand. Ask the target to select it.
2584 std::vector<SDOperand> SelOps;
2585 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2586 std::cerr << "Could not match memory address. Inline asm failure!\n";
2587 exit(1);
2588 }
2589
2590 // Add this to the output node.
2591 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2592 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2593 i += 2;
2594 }
2595 }
2596
2597 // Add the flag input back if present.
2598 if (e != InOps.size())
2599 Ops.push_back(InOps.back());
2600}