blob: 7e2a2777dfe459c1ab31c9bae04dc727e397e243 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000074namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey9ff542f2006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner864635a2006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000134 };
135}
Evan Cheng4ef10862006-01-23 07:01:07 +0000136
Chris Lattner1c08c712005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattner571e4342006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000190
Chris Lattner3c384492006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattnerbf209482005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner1c08c712005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner58092e32007-01-20 22:35:55 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000249
Reid Spencerb83eb642006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000254 }
255
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
284 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
285 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000286 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000292 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner3c384492006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
306 // If this is a packed type, figure out what type it will decompose into
307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
309 const PackedType *PTy = cast<PackedType>(V->getType());
310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner1c08c712005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
357 std::map<const Value*, SDOperand> NodeMap;
358
Chris Lattnerd3948112005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemanf15485a2006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner1c08c712005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000404
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000409
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 }
419
Chris Lattnera651cf62005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000425
Chris Lattnerd3948112005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000439 }
440
Chris Lattner571e4342006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner199862b2006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000469
470 const SDOperand &setValue(const Value *V, SDOperand NewN) {
471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
473 return N = NewN;
474 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000475
Chris Lattner864635a2006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000481
Chris Lattner571e4342006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
487
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemanf15485a2006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000497
Chris Lattner1c08c712005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Reid Spencer24d6da52007-01-21 00:29:26 +0000502 void visitScalarBinary(User &I, unsigned OpCode);
503 void visitVectorBinary(User &I, unsigned OpCode);
504 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000505 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000506 void visitAdd(User &I) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000507 if (isa<PackedType>(I.getType()))
508 visitVectorBinary(I, ISD::VADD);
509 else if (I.getType()->isFloatingPoint())
510 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000511 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000512 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000513 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000514 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000515 void visitMul(User &I) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000516 if (isa<PackedType>(I.getType()))
517 visitVectorBinary(I, ISD::VMUL);
518 else if (I.getType()->isFloatingPoint())
519 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000521 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000522 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000523 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
524 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
525 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
526 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
527 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
528 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
529 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
530 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
531 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
532 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000533 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
534 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000535 void visitICmp(User &I);
536 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000537 // Visit the conversion instructions
538 void visitTrunc(User &I);
539 void visitZExt(User &I);
540 void visitSExt(User &I);
541 void visitFPTrunc(User &I);
542 void visitFPExt(User &I);
543 void visitFPToUI(User &I);
544 void visitFPToSI(User &I);
545 void visitUIToFP(User &I);
546 void visitSIToFP(User &I);
547 void visitPtrToInt(User &I);
548 void visitIntToPtr(User &I);
549 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000550
Chris Lattner2bbd8102006-03-29 00:11:43 +0000551 void visitExtractElement(User &I);
552 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000553 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000554
Chris Lattner1c08c712005-01-07 07:47:53 +0000555 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000556 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557
558 void visitMalloc(MallocInst &I);
559 void visitFree(FreeInst &I);
560 void visitAlloca(AllocaInst &I);
561 void visitLoad(LoadInst &I);
562 void visitStore(StoreInst &I);
563 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
564 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000565 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000566 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000567 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000568
Chris Lattner1c08c712005-01-07 07:47:53 +0000569 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 void visitVAArg(VAArgInst &I);
571 void visitVAEnd(CallInst &I);
572 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000573
Chris Lattner7041ee32005-01-11 05:56:49 +0000574 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000575
576 void visitUserOp1(Instruction &I) {
577 assert(0 && "UserOp1 should not exist at instruction selection time!");
578 abort();
579 }
580 void visitUserOp2(Instruction &I) {
581 assert(0 && "UserOp2 should not exist at instruction selection time!");
582 abort();
583 }
584};
585} // end namespace llvm
586
Chris Lattner199862b2006-03-16 19:57:50 +0000587SDOperand SelectionDAGLowering::getValue(const Value *V) {
588 SDOperand &N = NodeMap[V];
589 if (N.Val) return N;
590
591 const Type *VTy = V->getType();
592 MVT::ValueType VT = TLI.getValueType(VTy);
593 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
595 visit(CE->getOpcode(), *CE);
596 assert(N.Val && "visit didn't populate the ValueMap!");
597 return N;
598 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
599 return N = DAG.getGlobalAddress(GV, VT);
600 } else if (isa<ConstantPointerNull>(C)) {
601 return N = DAG.getConstant(0, TLI.getPointerTy());
602 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000603 if (!isa<PackedType>(VTy))
604 return N = DAG.getNode(ISD::UNDEF, VT);
605
Chris Lattnerb2827b02006-03-19 00:52:58 +0000606 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000607 const PackedType *PTy = cast<PackedType>(VTy);
608 unsigned NumElements = PTy->getNumElements();
609 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
610
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000611 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000612 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
613
614 // Create a VConstant node with generic Vector type.
615 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
616 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000617 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
618 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000619 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
620 return N = DAG.getConstantFP(CFP->getValue(), VT);
621 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
622 unsigned NumElements = PTy->getNumElements();
623 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000624
625 // Now that we know the number and type of the elements, push a
626 // Constant or ConstantFP node onto the ops list for each element of
627 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000628 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000629 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000630 for (unsigned i = 0; i != NumElements; ++i)
631 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000632 } else {
633 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
634 SDOperand Op;
635 if (MVT::isFloatingPoint(PVT))
636 Op = DAG.getConstantFP(0, PVT);
637 else
638 Op = DAG.getConstant(0, PVT);
639 Ops.assign(NumElements, Op);
640 }
641
Chris Lattnerb2827b02006-03-19 00:52:58 +0000642 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000643 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
644 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000645 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000646 } else {
647 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000648 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000649 }
650 }
651
652 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
653 std::map<const AllocaInst*, int>::iterator SI =
654 FuncInfo.StaticAllocaMap.find(AI);
655 if (SI != FuncInfo.StaticAllocaMap.end())
656 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
657 }
658
659 std::map<const Value*, unsigned>::const_iterator VMI =
660 FuncInfo.ValueMap.find(V);
661 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
662
663 unsigned InReg = VMI->second;
664
665 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000666 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000667 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000668 // Source must be expanded. This input value is actually coming from the
669 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000670 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
671 unsigned NumVals = TLI.getNumElements(VT);
672 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
673 if (NumVals == 1)
674 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
675 else {
676 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
677 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
678 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
679 }
680 } else {
681 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
682 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
683 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
684 N = MVT::isFloatingPoint(VT)
685 ? DAG.getNode(ISD::FP_ROUND, VT, N)
686 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000687 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000688 } else {
689 // Otherwise, if this is a vector, make it available as a generic vector
690 // here.
691 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000692 const PackedType *PTy = cast<PackedType>(VTy);
693 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000694 PTyLegalElementVT);
695
696 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000697 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000698 if (PTyElementVT == PTyLegalElementVT) {
699 // If the value types are legal, just VBUILD the CopyFromReg nodes.
700 for (unsigned i = 0; i != NE; ++i)
701 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
702 PTyElementVT));
703 } else if (PTyElementVT < PTyLegalElementVT) {
704 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
705 for (unsigned i = 0; i != NE; ++i) {
706 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT);
708 if (MVT::isFloatingPoint(PTyElementVT))
709 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
710 else
711 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
712 Ops.push_back(Op);
713 }
714 } else {
715 // If the register was expanded, use BUILD_PAIR.
716 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
717 for (unsigned i = 0; i != NE/2; ++i) {
718 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
719 PTyElementVT);
720 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
721 PTyElementVT);
722 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
723 }
724 }
725
726 Ops.push_back(DAG.getConstant(NE, MVT::i32));
727 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000728 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000729
730 // Finally, use a VBIT_CONVERT to make this available as the appropriate
731 // vector type.
732 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
733 DAG.getConstant(PTy->getNumElements(),
734 MVT::i32),
735 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000736 }
737
738 return N;
739}
740
741
Chris Lattner1c08c712005-01-07 07:47:53 +0000742void SelectionDAGLowering::visitRet(ReturnInst &I) {
743 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000744 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000745 return;
746 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000747 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000748 NewValues.push_back(getRoot());
749 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
750 SDOperand RetOp = getValue(I.getOperand(i));
751
752 // If this is an integer return value, we need to promote it ourselves to
753 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
754 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000755 // FIXME: C calling convention requires the return type to be promoted to
756 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000757 if (MVT::isInteger(RetOp.getValueType()) &&
758 RetOp.getValueType() < MVT::i64) {
759 MVT::ValueType TmpVT;
760 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
761 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
762 else
763 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000764 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000765 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000766 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
767 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000768 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
769 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000770 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000771 }
772 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000773 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000774 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000775 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
776 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000777}
778
Chris Lattner571e4342006-10-27 21:36:01 +0000779/// ExportFromCurrentBlock - If this condition isn't known to be exported from
780/// the current basic block, add it to ValueMap now so that we'll get a
781/// CopyTo/FromReg.
782void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
783 // No need to export constants.
784 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
785
786 // Already exported?
787 if (FuncInfo.isExportedInst(V)) return;
788
789 unsigned Reg = FuncInfo.InitializeRegForValue(V);
790 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
791}
792
Chris Lattner8c494ab2006-10-27 23:50:33 +0000793bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
794 const BasicBlock *FromBB) {
795 // The operands of the setcc have to be in this block. We don't know
796 // how to export them from some other block.
797 if (Instruction *VI = dyn_cast<Instruction>(V)) {
798 // Can export from current BB.
799 if (VI->getParent() == FromBB)
800 return true;
801
802 // Is already exported, noop.
803 return FuncInfo.isExportedInst(V);
804 }
805
806 // If this is an argument, we can export it if the BB is the entry block or
807 // if it is already exported.
808 if (isa<Argument>(V)) {
809 if (FromBB == &FromBB->getParent()->getEntryBlock())
810 return true;
811
812 // Otherwise, can only export this if it is already exported.
813 return FuncInfo.isExportedInst(V);
814 }
815
816 // Otherwise, constants can always be exported.
817 return true;
818}
819
Chris Lattner6a586c82006-10-29 21:01:20 +0000820static bool InBlock(const Value *V, const BasicBlock *BB) {
821 if (const Instruction *I = dyn_cast<Instruction>(V))
822 return I->getParent() == BB;
823 return true;
824}
825
Chris Lattner571e4342006-10-27 21:36:01 +0000826/// FindMergedConditions - If Cond is an expression like
827void SelectionDAGLowering::FindMergedConditions(Value *Cond,
828 MachineBasicBlock *TBB,
829 MachineBasicBlock *FBB,
830 MachineBasicBlock *CurBB,
831 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000832 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000833 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000834
Reid Spencere4d87aa2006-12-23 06:05:41 +0000835 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
836 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000837 BOp->getParent() != CurBB->getBasicBlock() ||
838 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
839 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000840 const BasicBlock *BB = CurBB->getBasicBlock();
841
Reid Spencere4d87aa2006-12-23 06:05:41 +0000842 // If the leaf of the tree is a comparison, merge the condition into
843 // the caseblock.
844 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
845 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000846 // how to export them from some other block. If this is the first block
847 // of the sequence, no exporting is needed.
848 (CurBB == CurMBB ||
849 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
850 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000851 BOp = cast<Instruction>(Cond);
852 ISD::CondCode Condition;
853 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
854 switch (IC->getPredicate()) {
855 default: assert(0 && "Unknown icmp predicate opcode!");
856 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
857 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
858 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
859 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
860 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
861 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
862 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
863 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
864 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
865 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
866 }
867 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
868 ISD::CondCode FPC, FOC;
869 switch (FC->getPredicate()) {
870 default: assert(0 && "Unknown fcmp predicate opcode!");
871 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
872 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
873 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
874 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
875 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
876 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
877 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
878 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
879 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
880 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
881 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
882 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
883 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
884 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
885 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
886 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
887 }
888 if (FiniteOnlyFPMath())
889 Condition = FOC;
890 else
891 Condition = FPC;
892 } else {
893 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000894 }
895
Chris Lattner571e4342006-10-27 21:36:01 +0000896 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
897 BOp->getOperand(1), TBB, FBB, CurBB);
898 SwitchCases.push_back(CB);
899 return;
900 }
901
902 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000903 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000904 TBB, FBB, CurBB);
905 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000906 return;
907 }
908
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000909
910 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000911 MachineFunction::iterator BBI = CurBB;
912 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
913 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
914
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000915 if (Opc == Instruction::Or) {
916 // Codegen X | Y as:
917 // jmp_if_X TBB
918 // jmp TmpBB
919 // TmpBB:
920 // jmp_if_Y TBB
921 // jmp FBB
922 //
Chris Lattner571e4342006-10-27 21:36:01 +0000923
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000924 // Emit the LHS condition.
925 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
926
927 // Emit the RHS condition into TmpBB.
928 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
929 } else {
930 assert(Opc == Instruction::And && "Unknown merge op!");
931 // Codegen X & Y as:
932 // jmp_if_X TmpBB
933 // jmp FBB
934 // TmpBB:
935 // jmp_if_Y TBB
936 // jmp FBB
937 //
938 // This requires creation of TmpBB after CurBB.
939
940 // Emit the LHS condition.
941 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
942
943 // Emit the RHS condition into TmpBB.
944 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
945 }
Chris Lattner571e4342006-10-27 21:36:01 +0000946}
947
Chris Lattnerdf19f272006-10-31 22:37:42 +0000948/// If the set of cases should be emitted as a series of branches, return true.
949/// If we should emit this as a bunch of and/or'd together conditions, return
950/// false.
951static bool
952ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
953 if (Cases.size() != 2) return true;
954
Chris Lattner0ccb5002006-10-31 23:06:00 +0000955 // If this is two comparisons of the same values or'd or and'd together, they
956 // will get folded into a single comparison, so don't emit two blocks.
957 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
958 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
959 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
960 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
961 return false;
962 }
963
Chris Lattnerdf19f272006-10-31 22:37:42 +0000964 return true;
965}
966
Chris Lattner1c08c712005-01-07 07:47:53 +0000967void SelectionDAGLowering::visitBr(BranchInst &I) {
968 // Update machine-CFG edges.
969 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000970
971 // Figure out which block is immediately after the current one.
972 MachineBasicBlock *NextBlock = 0;
973 MachineFunction::iterator BBI = CurMBB;
974 if (++BBI != CurMBB->getParent()->end())
975 NextBlock = BBI;
976
977 if (I.isUnconditional()) {
978 // If this is not a fall-through branch, emit the branch.
979 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000980 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000981 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000982
Chris Lattner57ab6592006-10-24 17:57:59 +0000983 // Update machine-CFG edges.
984 CurMBB->addSuccessor(Succ0MBB);
985
986 return;
987 }
988
989 // If this condition is one of the special cases we handle, do special stuff
990 // now.
991 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000992 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000993
994 // If this is a series of conditions that are or'd or and'd together, emit
995 // this as a sequence of branches instead of setcc's with and/or operations.
996 // For example, instead of something like:
997 // cmp A, B
998 // C = seteq
999 // cmp D, E
1000 // F = setle
1001 // or C, F
1002 // jnz foo
1003 // Emit:
1004 // cmp A, B
1005 // je foo
1006 // cmp D, E
1007 // jle foo
1008 //
1009 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1010 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001011 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001012 BOp->getOpcode() == Instruction::Or)) {
1013 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001014 // If the compares in later blocks need to use values not currently
1015 // exported from this block, export them now. This block should always
1016 // be the first entry.
1017 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1018
Chris Lattnerdf19f272006-10-31 22:37:42 +00001019 // Allow some cases to be rejected.
1020 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001021 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1022 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1023 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1024 }
1025
1026 // Emit the branch for this block.
1027 visitSwitchCase(SwitchCases[0]);
1028 SwitchCases.erase(SwitchCases.begin());
1029 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001030 }
1031
Chris Lattner0ccb5002006-10-31 23:06:00 +00001032 // Okay, we decided not to do this, remove any inserted MBB's and clear
1033 // SwitchCases.
1034 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1035 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1036
Chris Lattnerdf19f272006-10-31 22:37:42 +00001037 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001038 }
1039 }
Chris Lattner24525952006-10-24 18:07:37 +00001040
1041 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001042 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001043 Succ0MBB, Succ1MBB, CurMBB);
1044 // Use visitSwitchCase to actually insert the fast branch sequence for this
1045 // cond branch.
1046 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001047}
1048
Nate Begemanf15485a2006-03-27 01:32:24 +00001049/// visitSwitchCase - Emits the necessary code to represent a single node in
1050/// the binary search tree resulting from lowering a switch instruction.
1051void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001052 SDOperand Cond;
1053 SDOperand CondLHS = getValue(CB.CmpLHS);
1054
Chris Lattner571e4342006-10-27 21:36:01 +00001055 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1056 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001057 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001058 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001059 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001060 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1061 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1062 } else
1063 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001064
1065 // Set NextBlock to be the MBB immediately after the current one, if any.
1066 // This is used to avoid emitting unnecessary branches to the next block.
1067 MachineBasicBlock *NextBlock = 0;
1068 MachineFunction::iterator BBI = CurMBB;
1069 if (++BBI != CurMBB->getParent()->end())
1070 NextBlock = BBI;
1071
1072 // If the lhs block is the next block, invert the condition so that we can
1073 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001074 if (CB.TrueBB == NextBlock) {
1075 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001076 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1077 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1078 }
1079 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001080 DAG.getBasicBlock(CB.TrueBB));
1081 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001082 DAG.setRoot(BrCond);
1083 else
1084 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001085 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001086 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001087 CurMBB->addSuccessor(CB.TrueBB);
1088 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001089}
1090
Nate Begeman37efe672006-04-22 18:53:45 +00001091void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001092 // Emit the code for the jump table
1093 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001094 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1095 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1096 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1097 Table, Index));
1098 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001099}
1100
Nate Begemanf15485a2006-03-27 01:32:24 +00001101void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1102 // Figure out which block is immediately after the current one.
1103 MachineBasicBlock *NextBlock = 0;
1104 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001105
Nate Begemanf15485a2006-03-27 01:32:24 +00001106 if (++BBI != CurMBB->getParent()->end())
1107 NextBlock = BBI;
1108
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001109 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1110
Nate Begemanf15485a2006-03-27 01:32:24 +00001111 // If there is only the default destination, branch to it if it is not the
1112 // next basic block. Otherwise, just fall through.
1113 if (I.getNumOperands() == 2) {
1114 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001115
Nate Begemanf15485a2006-03-27 01:32:24 +00001116 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001117 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001118 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001119 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001120
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001121 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001122 return;
1123 }
1124
1125 // If there are any non-default case statements, create a vector of Cases
1126 // representing each one, and sort the vector so that we can efficiently
1127 // create a binary search tree from them.
1128 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001129
Nate Begemanf15485a2006-03-27 01:32:24 +00001130 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1131 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1132 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1133 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001134
Nate Begemanf15485a2006-03-27 01:32:24 +00001135 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1136
1137 // Get the Value to be switched on and default basic blocks, which will be
1138 // inserted into CaseBlock records, representing basic blocks in the binary
1139 // search tree.
1140 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001141
1142 // Get the MachineFunction which holds the current MBB. This is used during
1143 // emission of jump tables, and when inserting any additional MBBs necessary
1144 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001145 MachineFunction *CurMF = CurMBB->getParent();
1146 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001147
1148 // If the switch has few cases (two or less) emit a series of specific
1149 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001150 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001151 // TODO: If any two of the cases has the same destination, and if one value
1152 // is the same as the other, but has one bit unset that the other has set,
1153 // use bit manipulation to do two compares at once. For example:
1154 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1155
Chris Lattnerb3543432006-10-23 18:38:22 +00001156 // Rearrange the case blocks so that the last one falls through if possible.
1157 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1158 // The last case block won't fall through into 'NextBlock' if we emit the
1159 // branches in this order. See if rearranging a case value would help.
1160 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1161 if (Cases[i].second == NextBlock) {
1162 std::swap(Cases[i], Cases.back());
1163 break;
1164 }
1165 }
1166 }
1167
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001168 // Create a CaseBlock record representing a conditional branch to
1169 // the Case's target mbb if the value being switched on SV is equal
1170 // to C.
1171 MachineBasicBlock *CurBlock = CurMBB;
1172 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1173 MachineBasicBlock *FallThrough;
1174 if (i != e-1) {
1175 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1176 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1177 } else {
1178 // If the last case doesn't match, go to the default block.
1179 FallThrough = Default;
1180 }
1181
1182 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1183 Cases[i].second, FallThrough, CurBlock);
1184
1185 // If emitting the first comparison, just call visitSwitchCase to emit the
1186 // code into the current block. Otherwise, push the CaseBlock onto the
1187 // vector to be later processed by SDISel, and insert the node's MBB
1188 // before the next MBB.
1189 if (CurBlock == CurMBB)
1190 visitSwitchCase(CB);
1191 else
1192 SwitchCases.push_back(CB);
1193
1194 CurBlock = FallThrough;
1195 }
1196 return;
1197 }
Nate Begeman37efe672006-04-22 18:53:45 +00001198
Nate Begeman17c275f2006-05-08 16:51:36 +00001199 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1200 // target supports indirect branches, then emit a jump table rather than
1201 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001202 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1203 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001204 Cases.size() > 5) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001205 uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1206 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001207 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1208
Nate Begeman17c275f2006-05-08 16:51:36 +00001209 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001210 // Create a new basic block to hold the code for loading the address
1211 // of the jump table, and jumping to it. Update successor information;
1212 // we will either branch to the default case for the switch, or the jump
1213 // table.
1214 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1215 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1216 CurMBB->addSuccessor(Default);
1217 CurMBB->addSuccessor(JumpTableBB);
1218
1219 // Subtract the lowest switch case value from the value being switched on
1220 // and conditional branch to default mbb if the result is greater than the
1221 // difference between smallest and largest cases.
1222 SDOperand SwitchOp = getValue(SV);
1223 MVT::ValueType VT = SwitchOp.getValueType();
1224 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1225 DAG.getConstant(First, VT));
1226
1227 // The SDNode we just created, which holds the value being switched on
1228 // minus the the smallest case value, needs to be copied to a virtual
1229 // register so it can be used as an index into the jump table in a
1230 // subsequent basic block. This value may be smaller or larger than the
1231 // target's pointer type, and therefore require extension or truncating.
1232 if (VT > TLI.getPointerTy())
1233 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1234 else
1235 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001236
Nate Begeman37efe672006-04-22 18:53:45 +00001237 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1238 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1239
1240 // Emit the range check for the jump table, and branch to the default
1241 // block for the switch statement if the value being switched on exceeds
1242 // the largest case in the switch.
1243 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1244 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1245 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1246 DAG.getBasicBlock(Default)));
1247
Nate Begemanf4360a42006-05-03 03:48:02 +00001248 // Build a vector of destination BBs, corresponding to each target
1249 // of the jump table. If the value of the jump table slot corresponds to
1250 // a case statement, push the case's BB onto the vector, otherwise, push
1251 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001252 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001253 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001254 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001255 if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001256 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001257 ++ii;
1258 } else {
1259 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001260 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001261
Chris Lattner8c494ab2006-10-27 23:50:33 +00001262 // Update successor info. Add one edge to each unique successor.
1263 // Vector bool would be better, but vector<bool> is really slow.
1264 std::vector<unsigned char> SuccsHandled;
1265 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1266
Chris Lattnerc66764c2006-09-10 06:36:57 +00001267 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001268 E = DestBBs.end(); I != E; ++I) {
1269 if (!SuccsHandled[(*I)->getNumber()]) {
1270 SuccsHandled[(*I)->getNumber()] = true;
1271 JumpTableBB->addSuccessor(*I);
1272 }
1273 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001274
1275 // Create a jump table index for this jump table, or return an existing
1276 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001277 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1278
1279 // Set the jump table information so that we can codegen it as a second
1280 // MachineBasicBlock
1281 JT.Reg = JumpTableReg;
1282 JT.JTI = JTI;
1283 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001284 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001285 return;
1286 }
1287 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001288
1289 // Push the initial CaseRec onto the worklist
1290 std::vector<CaseRec> CaseVec;
1291 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1292
1293 while (!CaseVec.empty()) {
1294 // Grab a record representing a case range to process off the worklist
1295 CaseRec CR = CaseVec.back();
1296 CaseVec.pop_back();
1297
1298 // Size is the number of Cases represented by this range. If Size is 1,
1299 // then we are processing a leaf of the binary search tree. Otherwise,
1300 // we need to pick a pivot, and push left and right ranges onto the
1301 // worklist.
1302 unsigned Size = CR.Range.second - CR.Range.first;
1303
1304 if (Size == 1) {
1305 // Create a CaseBlock record representing a conditional branch to
1306 // the Case's target mbb if the value being switched on SV is equal
1307 // to C. Otherwise, branch to default.
1308 Constant *C = CR.Range.first->first;
1309 MachineBasicBlock *Target = CR.Range.first->second;
1310 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1311 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001312
Nate Begemanf15485a2006-03-27 01:32:24 +00001313 // If the MBB representing the leaf node is the current MBB, then just
1314 // call visitSwitchCase to emit the code into the current block.
1315 // Otherwise, push the CaseBlock onto the vector to be later processed
1316 // by SDISel, and insert the node's MBB before the next MBB.
1317 if (CR.CaseBB == CurMBB)
1318 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001319 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001320 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001321 } else {
1322 // split case range at pivot
1323 CaseItr Pivot = CR.Range.first + (Size / 2);
1324 CaseRange LHSR(CR.Range.first, Pivot);
1325 CaseRange RHSR(Pivot, CR.Range.second);
1326 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001327 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001328
Nate Begemanf15485a2006-03-27 01:32:24 +00001329 // We know that we branch to the LHS if the Value being switched on is
1330 // less than the Pivot value, C. We use this to optimize our binary
1331 // tree a bit, by recognizing that if SV is greater than or equal to the
1332 // LHS's Case Value, and that Case Value is exactly one less than the
1333 // Pivot's Value, then we can branch directly to the LHS's Target,
1334 // rather than creating a leaf node for it.
1335 if ((LHSR.second - LHSR.first) == 1 &&
1336 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001337 cast<ConstantInt>(C)->getZExtValue() ==
1338 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001339 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001340 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001341 TrueBB = new MachineBasicBlock(LLVMBB);
1342 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1343 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001344 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001345
Nate Begemanf15485a2006-03-27 01:32:24 +00001346 // Similar to the optimization above, if the Value being switched on is
1347 // known to be less than the Constant CR.LT, and the current Case Value
1348 // is CR.LT - 1, then we can branch directly to the target block for
1349 // the current Case Value, rather than emitting a RHS leaf node for it.
1350 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001351 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1352 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001353 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001354 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001355 FalseBB = new MachineBasicBlock(LLVMBB);
1356 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1357 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001358 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001359
Nate Begemanf15485a2006-03-27 01:32:24 +00001360 // Create a CaseBlock record representing a conditional branch to
1361 // the LHS node if the value being switched on SV is less than C.
1362 // Otherwise, branch to LHS.
Reid Spencer8c57dfb2007-01-03 04:25:33 +00001363 ISD::CondCode CC = ISD::SETLT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001364 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001365
Nate Begemanf15485a2006-03-27 01:32:24 +00001366 if (CR.CaseBB == CurMBB)
1367 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001368 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001369 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001370 }
1371 }
1372}
1373
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001374void SelectionDAGLowering::visitSub(User &I) {
1375 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001376 const Type *Ty = I.getType();
1377 if (isa<PackedType>(Ty)) {
1378 visitVectorBinary(I, ISD::VSUB);
1379 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1381 if (CFP->isExactlyValue(-0.0)) {
1382 SDOperand Op2 = getValue(I.getOperand(1));
1383 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1384 return;
1385 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001386 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001387 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001388 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001389}
1390
Reid Spencer24d6da52007-01-21 00:29:26 +00001391void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001392 SDOperand Op1 = getValue(I.getOperand(0));
1393 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001394
1395 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001396}
1397
Reid Spencer24d6da52007-01-21 00:29:26 +00001398void
1399SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1400 assert(isa<PackedType>(I.getType()));
1401 const PackedType *Ty = cast<PackedType>(I.getType());
1402 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001403
Reid Spencer24d6da52007-01-21 00:29:26 +00001404 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1405 getValue(I.getOperand(0)),
1406 getValue(I.getOperand(1)),
1407 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1408 Typ));
1409}
1410
1411void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1412 unsigned VectorOp) {
1413 if (isa<PackedType>(I.getType()))
1414 visitVectorBinary(I, VectorOp);
1415 else
1416 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001417}
Chris Lattner2c49f272005-01-19 22:31:21 +00001418
Nate Begemane21ea612005-11-18 07:42:56 +00001419void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1420 SDOperand Op1 = getValue(I.getOperand(0));
1421 SDOperand Op2 = getValue(I.getOperand(1));
1422
1423 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1424
Chris Lattner1c08c712005-01-07 07:47:53 +00001425 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1426}
1427
Reid Spencer45fb3f32006-11-20 01:22:35 +00001428void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001429 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1430 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1431 predicate = IC->getPredicate();
1432 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1433 predicate = ICmpInst::Predicate(IC->getPredicate());
1434 SDOperand Op1 = getValue(I.getOperand(0));
1435 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001436 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001437 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001438 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1439 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1440 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1441 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1442 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1443 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1444 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1445 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1446 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1447 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1448 default:
1449 assert(!"Invalid ICmp predicate value");
1450 Opcode = ISD::SETEQ;
1451 break;
1452 }
1453 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1454}
1455
1456void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001457 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1458 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1459 predicate = FC->getPredicate();
1460 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1461 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001462 SDOperand Op1 = getValue(I.getOperand(0));
1463 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001464 ISD::CondCode Condition, FOC, FPC;
1465 switch (predicate) {
1466 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1467 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1468 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1469 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1470 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1471 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1472 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1473 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1474 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1475 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1476 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1477 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1478 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1479 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1480 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1481 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1482 default:
1483 assert(!"Invalid FCmp predicate value");
1484 FOC = FPC = ISD::SETFALSE;
1485 break;
1486 }
1487 if (FiniteOnlyFPMath())
1488 Condition = FOC;
1489 else
1490 Condition = FPC;
1491 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001492}
1493
1494void SelectionDAGLowering::visitSelect(User &I) {
1495 SDOperand Cond = getValue(I.getOperand(0));
1496 SDOperand TrueVal = getValue(I.getOperand(1));
1497 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001498 if (!isa<PackedType>(I.getType())) {
1499 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1500 TrueVal, FalseVal));
1501 } else {
1502 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1503 *(TrueVal.Val->op_end()-2),
1504 *(TrueVal.Val->op_end()-1)));
1505 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001506}
1507
Reid Spencer3da59db2006-11-27 01:05:10 +00001508
1509void SelectionDAGLowering::visitTrunc(User &I) {
1510 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1511 SDOperand N = getValue(I.getOperand(0));
1512 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1513 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1514}
1515
1516void SelectionDAGLowering::visitZExt(User &I) {
1517 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1518 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1519 SDOperand N = getValue(I.getOperand(0));
1520 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1521 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1522}
1523
1524void SelectionDAGLowering::visitSExt(User &I) {
1525 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1526 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1527 SDOperand N = getValue(I.getOperand(0));
1528 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1529 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1530}
1531
1532void SelectionDAGLowering::visitFPTrunc(User &I) {
1533 // FPTrunc is never a no-op cast, no need to check
1534 SDOperand N = getValue(I.getOperand(0));
1535 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1536 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1537}
1538
1539void SelectionDAGLowering::visitFPExt(User &I){
1540 // FPTrunc is never a no-op cast, no need to check
1541 SDOperand N = getValue(I.getOperand(0));
1542 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1543 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1544}
1545
1546void SelectionDAGLowering::visitFPToUI(User &I) {
1547 // FPToUI is never a no-op cast, no need to check
1548 SDOperand N = getValue(I.getOperand(0));
1549 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1550 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1551}
1552
1553void SelectionDAGLowering::visitFPToSI(User &I) {
1554 // FPToSI is never a no-op cast, no need to check
1555 SDOperand N = getValue(I.getOperand(0));
1556 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1557 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1558}
1559
1560void SelectionDAGLowering::visitUIToFP(User &I) {
1561 // UIToFP is never a no-op cast, no need to check
1562 SDOperand N = getValue(I.getOperand(0));
1563 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1564 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1565}
1566
1567void SelectionDAGLowering::visitSIToFP(User &I){
1568 // UIToFP is never a no-op cast, no need to check
1569 SDOperand N = getValue(I.getOperand(0));
1570 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1571 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1572}
1573
1574void SelectionDAGLowering::visitPtrToInt(User &I) {
1575 // What to do depends on the size of the integer and the size of the pointer.
1576 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001577 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001578 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001579 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001580 SDOperand Result;
1581 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1582 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1583 else
1584 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1585 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1586 setValue(&I, Result);
1587}
Chris Lattner1c08c712005-01-07 07:47:53 +00001588
Reid Spencer3da59db2006-11-27 01:05:10 +00001589void SelectionDAGLowering::visitIntToPtr(User &I) {
1590 // What to do depends on the size of the integer and the size of the pointer.
1591 // We can either truncate, zero extend, or no-op, accordingly.
1592 SDOperand N = getValue(I.getOperand(0));
1593 MVT::ValueType SrcVT = N.getValueType();
1594 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1595 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1596 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1597 else
1598 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1599 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1600}
1601
1602void SelectionDAGLowering::visitBitCast(User &I) {
1603 SDOperand N = getValue(I.getOperand(0));
1604 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001605 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001606 // This is a cast to a vector from something else.
1607 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001608 const PackedType *DestTy = cast<PackedType>(I.getType());
1609 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1610 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1611 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1612 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001613 return;
1614 }
1615 MVT::ValueType SrcVT = N.getValueType();
1616 if (SrcVT == MVT::Vector) {
1617 // This is a cast from a vctor to something else.
1618 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001619 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001620 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001621 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001622
1623 // BitCast assures us that source and destination are the same size so this
1624 // is either a BIT_CONVERT or a no-op.
1625 if (DestVT != N.getValueType())
1626 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1627 else
1628 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001629}
1630
Chris Lattner2bbd8102006-03-29 00:11:43 +00001631void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001632 SDOperand InVec = getValue(I.getOperand(0));
1633 SDOperand InVal = getValue(I.getOperand(1));
1634 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1635 getValue(I.getOperand(2)));
1636
Chris Lattner2332b9f2006-03-19 01:17:20 +00001637 SDOperand Num = *(InVec.Val->op_end()-2);
1638 SDOperand Typ = *(InVec.Val->op_end()-1);
1639 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1640 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001641}
1642
Chris Lattner2bbd8102006-03-29 00:11:43 +00001643void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001644 SDOperand InVec = getValue(I.getOperand(0));
1645 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1646 getValue(I.getOperand(1)));
1647 SDOperand Typ = *(InVec.Val->op_end()-1);
1648 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1649 TLI.getValueType(I.getType()), InVec, InIdx));
1650}
Chris Lattnerc7029802006-03-18 01:44:44 +00001651
Chris Lattner3e104b12006-04-08 04:15:24 +00001652void SelectionDAGLowering::visitShuffleVector(User &I) {
1653 SDOperand V1 = getValue(I.getOperand(0));
1654 SDOperand V2 = getValue(I.getOperand(1));
1655 SDOperand Mask = getValue(I.getOperand(2));
1656
1657 SDOperand Num = *(V1.Val->op_end()-2);
1658 SDOperand Typ = *(V2.Val->op_end()-1);
1659 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1660 V1, V2, Mask, Num, Typ));
1661}
1662
1663
Chris Lattner1c08c712005-01-07 07:47:53 +00001664void SelectionDAGLowering::visitGetElementPtr(User &I) {
1665 SDOperand N = getValue(I.getOperand(0));
1666 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001667
1668 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1669 OI != E; ++OI) {
1670 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001671 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001672 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001673 if (Field) {
1674 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001675 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001676 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001677 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001678 }
1679 Ty = StTy->getElementType(Field);
1680 } else {
1681 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001682
Chris Lattner7c0104b2005-11-09 04:45:33 +00001683 // If this is a constant subscript, handle it quickly.
1684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001685 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001686 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001687 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001688 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1689 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001690 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001691
1692 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001693 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001694 SDOperand IdxN = getValue(Idx);
1695
1696 // If the index is smaller or larger than intptr_t, truncate or extend
1697 // it.
1698 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001699 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001700 } else if (IdxN.getValueType() > N.getValueType())
1701 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1702
1703 // If this is a multiply by a power of two, turn it into a shl
1704 // immediately. This is a very common case.
1705 if (isPowerOf2_64(ElementSize)) {
1706 unsigned Amt = Log2_64(ElementSize);
1707 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001708 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001709 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1710 continue;
1711 }
1712
1713 SDOperand Scale = getIntPtrConstant(ElementSize);
1714 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1715 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001716 }
1717 }
1718 setValue(&I, N);
1719}
1720
1721void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1722 // If this is a fixed sized alloca in the entry block of the function,
1723 // allocate it statically on the stack.
1724 if (FuncInfo.StaticAllocaMap.count(&I))
1725 return; // getValue will auto-populate this.
1726
1727 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001728 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001729 unsigned Align =
1730 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1731 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001732
1733 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001734 MVT::ValueType IntPtr = TLI.getPointerTy();
1735 if (IntPtr < AllocSize.getValueType())
1736 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1737 else if (IntPtr > AllocSize.getValueType())
1738 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001739
Chris Lattner68cd65e2005-01-22 23:04:37 +00001740 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001741 getIntPtrConstant(TySize));
1742
1743 // Handle alignment. If the requested alignment is less than or equal to the
1744 // stack alignment, ignore it and round the size of the allocation up to the
1745 // stack alignment size. If the size is greater than the stack alignment, we
1746 // note this in the DYNAMIC_STACKALLOC node.
1747 unsigned StackAlign =
1748 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1749 if (Align <= StackAlign) {
1750 Align = 0;
1751 // Add SA-1 to the size.
1752 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1753 getIntPtrConstant(StackAlign-1));
1754 // Mask out the low bits for alignment purposes.
1755 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1756 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1757 }
1758
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001759 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001760 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1761 MVT::Other);
1762 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001763 DAG.setRoot(setValue(&I, DSA).getValue(1));
1764
1765 // Inform the Frame Information that we have just allocated a variable-sized
1766 // object.
1767 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1768}
1769
Chris Lattner1c08c712005-01-07 07:47:53 +00001770void SelectionDAGLowering::visitLoad(LoadInst &I) {
1771 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001772
Chris Lattnerd3948112005-01-17 22:19:26 +00001773 SDOperand Root;
1774 if (I.isVolatile())
1775 Root = getRoot();
1776 else {
1777 // Do not serialize non-volatile loads against each other.
1778 Root = DAG.getRoot();
1779 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001780
Evan Cheng466685d2006-10-09 20:57:25 +00001781 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001782 Root, I.isVolatile()));
1783}
1784
1785SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001786 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001787 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001788 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001789 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001790 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001791 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1792 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001793 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001794 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001795 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001796
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001797 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001798 DAG.setRoot(L.getValue(1));
1799 else
1800 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001801
1802 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001803}
1804
1805
1806void SelectionDAGLowering::visitStore(StoreInst &I) {
1807 Value *SrcV = I.getOperand(0);
1808 SDOperand Src = getValue(SrcV);
1809 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001810 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001811 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001812}
1813
Chris Lattner0eade312006-03-24 02:22:33 +00001814/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1815/// access memory and has no other side effects at all.
1816static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1817#define GET_NO_MEMORY_INTRINSICS
1818#include "llvm/Intrinsics.gen"
1819#undef GET_NO_MEMORY_INTRINSICS
1820 return false;
1821}
1822
Chris Lattnere58a7802006-04-02 03:41:14 +00001823// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1824// have any side-effects or if it only reads memory.
1825static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1826#define GET_SIDE_EFFECT_INFO
1827#include "llvm/Intrinsics.gen"
1828#undef GET_SIDE_EFFECT_INFO
1829 return false;
1830}
1831
Chris Lattner0eade312006-03-24 02:22:33 +00001832/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1833/// node.
1834void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1835 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001836 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001837 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001838
1839 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001840 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001841 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1842 if (OnlyLoad) {
1843 // We don't need to serialize loads against other loads.
1844 Ops.push_back(DAG.getRoot());
1845 } else {
1846 Ops.push_back(getRoot());
1847 }
1848 }
Chris Lattner0eade312006-03-24 02:22:33 +00001849
1850 // Add the intrinsic ID as an integer operand.
1851 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1852
1853 // Add all operands of the call to the operand list.
1854 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1855 SDOperand Op = getValue(I.getOperand(i));
1856
1857 // If this is a vector type, force it to the right packed type.
1858 if (Op.getValueType() == MVT::Vector) {
1859 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1860 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1861
1862 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1863 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1864 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1865 }
1866
1867 assert(TLI.isTypeLegal(Op.getValueType()) &&
1868 "Intrinsic uses a non-legal type?");
1869 Ops.push_back(Op);
1870 }
1871
1872 std::vector<MVT::ValueType> VTs;
1873 if (I.getType() != Type::VoidTy) {
1874 MVT::ValueType VT = TLI.getValueType(I.getType());
1875 if (VT == MVT::Vector) {
1876 const PackedType *DestTy = cast<PackedType>(I.getType());
1877 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1878
1879 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1880 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1881 }
1882
1883 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1884 VTs.push_back(VT);
1885 }
1886 if (HasChain)
1887 VTs.push_back(MVT::Other);
1888
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001889 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1890
Chris Lattner0eade312006-03-24 02:22:33 +00001891 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001892 SDOperand Result;
1893 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001894 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1895 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001896 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001897 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1898 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001899 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001900 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1901 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001902
Chris Lattnere58a7802006-04-02 03:41:14 +00001903 if (HasChain) {
1904 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1905 if (OnlyLoad)
1906 PendingLoads.push_back(Chain);
1907 else
1908 DAG.setRoot(Chain);
1909 }
Chris Lattner0eade312006-03-24 02:22:33 +00001910 if (I.getType() != Type::VoidTy) {
1911 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1912 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1913 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1914 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1915 DAG.getValueType(EVT));
1916 }
1917 setValue(&I, Result);
1918 }
1919}
1920
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001921/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1922/// we want to emit this as a call to a named external function, return the name
1923/// otherwise lower it and return null.
1924const char *
1925SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1926 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001927 default:
1928 // By default, turn this into a target intrinsic node.
1929 visitTargetIntrinsic(I, Intrinsic);
1930 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001931 case Intrinsic::vastart: visitVAStart(I); return 0;
1932 case Intrinsic::vaend: visitVAEnd(I); return 0;
1933 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00001934 case Intrinsic::returnaddress:
1935 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1936 getValue(I.getOperand(1))));
1937 return 0;
1938 case Intrinsic::frameaddress:
1939 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1940 getValue(I.getOperand(1))));
1941 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001942 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001943 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001944 break;
1945 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001946 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001947 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001948 case Intrinsic::memcpy_i32:
1949 case Intrinsic::memcpy_i64:
1950 visitMemIntrinsic(I, ISD::MEMCPY);
1951 return 0;
1952 case Intrinsic::memset_i32:
1953 case Intrinsic::memset_i64:
1954 visitMemIntrinsic(I, ISD::MEMSET);
1955 return 0;
1956 case Intrinsic::memmove_i32:
1957 case Intrinsic::memmove_i64:
1958 visitMemIntrinsic(I, ISD::MEMMOVE);
1959 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001960
Chris Lattner86cb6432005-12-13 17:40:33 +00001961 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001962 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001963 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001964 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001965 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001966
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001967 Ops[0] = getRoot();
1968 Ops[1] = getValue(SPI.getLineValue());
1969 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001970
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001971 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001972 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001973 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1974
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001975 Ops[3] = DAG.getString(CompileUnit->getFileName());
1976 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001977
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001978 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001979 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001980
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001981 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001982 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001983 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001984 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001985 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001986 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
1987 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00001988 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001989 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001990 }
1991
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001992 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001993 }
1994 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001995 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001996 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001997 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
1998 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00001999 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002000 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002001 }
2002
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002003 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002004 }
2005 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002006 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002007 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002008 if (MMI && FSI.getSubprogram() &&
2009 MMI->Verify(FSI.getSubprogram())) {
2010 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002011 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002012 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002013 }
2014
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002015 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002016 }
2017 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002018 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002019 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002020 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002021 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002022 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002023 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002024 }
2025
2026 return 0;
2027 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002028
Reid Spencer0b118202006-01-16 21:12:35 +00002029 case Intrinsic::sqrt_f32:
2030 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002031 setValue(&I, DAG.getNode(ISD::FSQRT,
2032 getValue(I.getOperand(1)).getValueType(),
2033 getValue(I.getOperand(1))));
2034 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002035 case Intrinsic::powi_f32:
2036 case Intrinsic::powi_f64:
2037 setValue(&I, DAG.getNode(ISD::FPOWI,
2038 getValue(I.getOperand(1)).getValueType(),
2039 getValue(I.getOperand(1)),
2040 getValue(I.getOperand(2))));
2041 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002042 case Intrinsic::pcmarker: {
2043 SDOperand Tmp = getValue(I.getOperand(1));
2044 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2045 return 0;
2046 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002047 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002048 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002049 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2050 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2051 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002052 setValue(&I, Tmp);
2053 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002054 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002055 }
Nate Begemand88fc032006-01-14 03:14:10 +00002056 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002057 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002058 case Intrinsic::bswap_i64:
2059 setValue(&I, DAG.getNode(ISD::BSWAP,
2060 getValue(I.getOperand(1)).getValueType(),
2061 getValue(I.getOperand(1))));
2062 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002063 case Intrinsic::cttz_i8:
2064 case Intrinsic::cttz_i16:
2065 case Intrinsic::cttz_i32:
2066 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002067 setValue(&I, DAG.getNode(ISD::CTTZ,
2068 getValue(I.getOperand(1)).getValueType(),
2069 getValue(I.getOperand(1))));
2070 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002071 case Intrinsic::ctlz_i8:
2072 case Intrinsic::ctlz_i16:
2073 case Intrinsic::ctlz_i32:
2074 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002075 setValue(&I, DAG.getNode(ISD::CTLZ,
2076 getValue(I.getOperand(1)).getValueType(),
2077 getValue(I.getOperand(1))));
2078 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002079 case Intrinsic::ctpop_i8:
2080 case Intrinsic::ctpop_i16:
2081 case Intrinsic::ctpop_i32:
2082 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002083 setValue(&I, DAG.getNode(ISD::CTPOP,
2084 getValue(I.getOperand(1)).getValueType(),
2085 getValue(I.getOperand(1))));
2086 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002087 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002088 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002089 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2090 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002091 setValue(&I, Tmp);
2092 DAG.setRoot(Tmp.getValue(1));
2093 return 0;
2094 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002095 case Intrinsic::stackrestore: {
2096 SDOperand Tmp = getValue(I.getOperand(1));
2097 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002098 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002099 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002100 case Intrinsic::prefetch:
2101 // FIXME: Currently discarding prefetches.
2102 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002103 }
2104}
2105
2106
Chris Lattner1c08c712005-01-07 07:47:53 +00002107void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002108 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002109 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002110 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002111 if (unsigned IID = F->getIntrinsicID()) {
2112 RenameFn = visitIntrinsicCall(I, IID);
2113 if (!RenameFn)
2114 return;
2115 } else { // Not an LLVM intrinsic.
2116 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002117 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2118 if (I.getNumOperands() == 3 && // Basic sanity checks.
2119 I.getOperand(1)->getType()->isFloatingPoint() &&
2120 I.getType() == I.getOperand(1)->getType() &&
2121 I.getType() == I.getOperand(2)->getType()) {
2122 SDOperand LHS = getValue(I.getOperand(1));
2123 SDOperand RHS = getValue(I.getOperand(2));
2124 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2125 LHS, RHS));
2126 return;
2127 }
2128 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002129 if (I.getNumOperands() == 2 && // Basic sanity checks.
2130 I.getOperand(1)->getType()->isFloatingPoint() &&
2131 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002132 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002133 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2134 return;
2135 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002136 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002137 if (I.getNumOperands() == 2 && // Basic sanity checks.
2138 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002139 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002140 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002141 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2142 return;
2143 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002144 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002145 if (I.getNumOperands() == 2 && // Basic sanity checks.
2146 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2150 return;
2151 }
2152 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002153 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002154 } else if (isa<InlineAsm>(I.getOperand(0))) {
2155 visitInlineAsm(I);
2156 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002157 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002158
Reid Spencer47857812006-12-31 05:55:36 +00002159 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2160 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2161
Chris Lattner64e14b12005-01-08 22:48:57 +00002162 SDOperand Callee;
2163 if (!RenameFn)
2164 Callee = getValue(I.getOperand(0));
2165 else
2166 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencer47857812006-12-31 05:55:36 +00002167 TargetLowering::ArgListTy Args;
2168 TargetLowering::ArgListEntry Entry;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002169 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002170 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2171 Value *Arg = I.getOperand(i);
2172 SDOperand ArgNode = getValue(Arg);
Reid Spencer47857812006-12-31 05:55:36 +00002173 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2174 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002175 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2176 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
Reid Spencer47857812006-12-31 05:55:36 +00002177 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002178 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002179
Chris Lattnercf5734d2005-01-08 19:26:18 +00002180 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002181 TLI.LowerCallTo(getRoot(), I.getType(),
2182 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2183 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2184 Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002185 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002186 setValue(&I, Result.first);
2187 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002188}
2189
Chris Lattner864635a2006-02-22 22:37:12 +00002190SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002191 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002192 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2193 Chain = Val.getValue(1);
2194 Flag = Val.getValue(2);
2195
2196 // If the result was expanded, copy from the top part.
2197 if (Regs.size() > 1) {
2198 assert(Regs.size() == 2 &&
2199 "Cannot expand to more than 2 elts yet!");
2200 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002201 Chain = Hi.getValue(1);
2202 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002203 if (DAG.getTargetLoweringInfo().isLittleEndian())
2204 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2205 else
2206 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002207 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002208
Chris Lattnercf752aa2006-06-08 18:22:48 +00002209 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002210 // appropriate type.
2211 if (RegVT == ValueVT)
2212 return Val;
2213
Chris Lattnercf752aa2006-06-08 18:22:48 +00002214 if (MVT::isInteger(RegVT)) {
2215 if (ValueVT < RegVT)
2216 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2217 else
2218 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2219 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002220 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002221 }
Chris Lattner864635a2006-02-22 22:37:12 +00002222}
2223
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002224/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2225/// specified value into the registers specified by this object. This uses
2226/// Chain/Flag as the input and updates them for the output Chain/Flag.
2227void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002228 SDOperand &Chain, SDOperand &Flag,
2229 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002230 if (Regs.size() == 1) {
2231 // If there is a single register and the types differ, this must be
2232 // a promotion.
2233 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002234 if (MVT::isInteger(RegVT)) {
2235 if (RegVT < ValueVT)
2236 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2237 else
2238 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2239 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002240 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2241 }
2242 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2243 Flag = Chain.getValue(1);
2244 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002245 std::vector<unsigned> R(Regs);
2246 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2247 std::reverse(R.begin(), R.end());
2248
2249 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002250 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002251 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002252 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002253 Flag = Chain.getValue(1);
2254 }
2255 }
2256}
Chris Lattner864635a2006-02-22 22:37:12 +00002257
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002258/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2259/// operand list. This adds the code marker and includes the number of
2260/// values added into it.
2261void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002262 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002263 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2264 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2265 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2266}
Chris Lattner864635a2006-02-22 22:37:12 +00002267
2268/// isAllocatableRegister - If the specified register is safe to allocate,
2269/// i.e. it isn't a stack pointer or some other special register, return the
2270/// register class for the register. Otherwise, return null.
2271static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002272isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2273 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002274 MVT::ValueType FoundVT = MVT::Other;
2275 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002276 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2277 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002278 MVT::ValueType ThisVT = MVT::Other;
2279
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002280 const TargetRegisterClass *RC = *RCI;
2281 // If none of the the value types for this register class are valid, we
2282 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002283 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2284 I != E; ++I) {
2285 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002286 // If we have already found this register in a different register class,
2287 // choose the one with the largest VT specified. For example, on
2288 // PowerPC, we favor f64 register classes over f32.
2289 if (FoundVT == MVT::Other ||
2290 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2291 ThisVT = *I;
2292 break;
2293 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002294 }
2295 }
2296
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002297 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002298
Chris Lattner864635a2006-02-22 22:37:12 +00002299 // NOTE: This isn't ideal. In particular, this might allocate the
2300 // frame pointer in functions that need it (due to them not being taken
2301 // out of allocation, because a variable sized allocation hasn't been seen
2302 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002303 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2304 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002305 if (*I == Reg) {
2306 // We found a matching register class. Keep looking at others in case
2307 // we find one with larger registers that this physreg is also in.
2308 FoundRC = RC;
2309 FoundVT = ThisVT;
2310 break;
2311 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002312 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002313 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002314}
2315
2316RegsForValue SelectionDAGLowering::
2317GetRegistersForValue(const std::string &ConstrCode,
2318 MVT::ValueType VT, bool isOutReg, bool isInReg,
2319 std::set<unsigned> &OutputRegs,
2320 std::set<unsigned> &InputRegs) {
2321 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2322 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2323 std::vector<unsigned> Regs;
2324
2325 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2326 MVT::ValueType RegVT;
2327 MVT::ValueType ValueVT = VT;
2328
Chris Lattner2a821602006-11-02 01:41:49 +00002329 // If this is a constraint for a specific physical register, like {r17},
2330 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002331 if (PhysReg.first) {
2332 if (VT == MVT::Other)
2333 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002334
2335 // Get the actual register value type. This is important, because the user
2336 // may have asked for (e.g.) the AX register in i32 type. We need to
2337 // remember that AX is actually i16 to get the right extension.
2338 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002339
2340 // This is a explicit reference to a physical register.
2341 Regs.push_back(PhysReg.first);
2342
2343 // If this is an expanded reference, add the rest of the regs to Regs.
2344 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002345 TargetRegisterClass::iterator I = PhysReg.second->begin();
2346 TargetRegisterClass::iterator E = PhysReg.second->end();
2347 for (; *I != PhysReg.first; ++I)
2348 assert(I != E && "Didn't find reg!");
2349
2350 // Already added the first reg.
2351 --NumRegs; ++I;
2352 for (; NumRegs; --NumRegs, ++I) {
2353 assert(I != E && "Ran out of registers to allocate!");
2354 Regs.push_back(*I);
2355 }
2356 }
2357 return RegsForValue(Regs, RegVT, ValueVT);
2358 }
2359
Chris Lattner2a821602006-11-02 01:41:49 +00002360 // Otherwise, if this was a reference to an LLVM register class, create vregs
2361 // for this reference.
2362 std::vector<unsigned> RegClassRegs;
2363 if (PhysReg.second) {
2364 // If this is an early clobber or tied register, our regalloc doesn't know
2365 // how to maintain the constraint. If it isn't, go ahead and create vreg
2366 // and let the regalloc do the right thing.
2367 if (!isOutReg || !isInReg) {
2368 if (VT == MVT::Other)
2369 ValueVT = *PhysReg.second->vt_begin();
2370 RegVT = *PhysReg.second->vt_begin();
2371
2372 // Create the appropriate number of virtual registers.
2373 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2374 for (; NumRegs; --NumRegs)
2375 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2376
2377 return RegsForValue(Regs, RegVT, ValueVT);
2378 }
2379
2380 // Otherwise, we can't allocate it. Let the code below figure out how to
2381 // maintain these constraints.
2382 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2383
2384 } else {
2385 // This is a reference to a register class that doesn't directly correspond
2386 // to an LLVM register class. Allocate NumRegs consecutive, available,
2387 // registers from the class.
2388 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2389 }
Chris Lattner864635a2006-02-22 22:37:12 +00002390
2391 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2392 MachineFunction &MF = *CurMBB->getParent();
2393 unsigned NumAllocated = 0;
2394 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2395 unsigned Reg = RegClassRegs[i];
2396 // See if this register is available.
2397 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2398 (isInReg && InputRegs.count(Reg))) { // Already used.
2399 // Make sure we find consecutive registers.
2400 NumAllocated = 0;
2401 continue;
2402 }
2403
2404 // Check to see if this register is allocatable (i.e. don't give out the
2405 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002406 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002407 if (!RC) {
2408 // Make sure we find consecutive registers.
2409 NumAllocated = 0;
2410 continue;
2411 }
2412
2413 // Okay, this register is good, we can use it.
2414 ++NumAllocated;
2415
2416 // If we allocated enough consecutive
2417 if (NumAllocated == NumRegs) {
2418 unsigned RegStart = (i-NumAllocated)+1;
2419 unsigned RegEnd = i+1;
2420 // Mark all of the allocated registers used.
2421 for (unsigned i = RegStart; i != RegEnd; ++i) {
2422 unsigned Reg = RegClassRegs[i];
2423 Regs.push_back(Reg);
2424 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2425 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2426 }
2427
2428 return RegsForValue(Regs, *RC->vt_begin(), VT);
2429 }
2430 }
2431
2432 // Otherwise, we couldn't allocate enough registers for this.
2433 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002434}
2435
Chris Lattner367f1092007-01-29 23:45:14 +00002436/// getConstraintGenerality - Return an integer indicating how general CT is.
2437static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2438 switch (CT) {
2439 default: assert(0 && "Unknown constraint type!");
2440 case TargetLowering::C_Other:
2441 case TargetLowering::C_Unknown:
2442 return 0;
2443 case TargetLowering::C_Register:
2444 return 1;
2445 case TargetLowering::C_RegisterClass:
2446 return 2;
2447 case TargetLowering::C_Memory:
2448 return 3;
2449 }
2450}
2451
2452static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2453 const TargetLowering &TLI) {
2454 assert(!C.empty() && "Must have at least one constraint");
2455 if (C.size() == 1) return C[0];
2456
2457 std::string *Current = &C[0];
2458 // If we have multiple constraints, try to pick the most general one ahead
2459 // of time. This isn't a wonderful solution, but handles common cases.
2460 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2461 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2462 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2463 if (getConstraintGenerality(ThisFlavor) >
2464 getConstraintGenerality(Flavor)) {
2465 // This constraint letter is more general than the previous one,
2466 // use it.
2467 Flavor = ThisFlavor;
2468 Current = &C[j];
2469 }
2470 }
2471 return *Current;
2472}
2473
Chris Lattner864635a2006-02-22 22:37:12 +00002474
Chris Lattnerce7518c2006-01-26 22:24:51 +00002475/// visitInlineAsm - Handle a call to an InlineAsm object.
2476///
2477void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2478 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2479
2480 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2481 MVT::Other);
2482
Chris Lattner2cc2f662006-02-01 01:28:23 +00002483 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002484 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002485
2486 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2487 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2488 /// if it is a def of that register.
2489 std::vector<SDOperand> AsmNodeOperands;
2490 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2491 AsmNodeOperands.push_back(AsmStr);
2492
2493 SDOperand Chain = getRoot();
2494 SDOperand Flag;
2495
Chris Lattner4e4b5762006-02-01 18:59:47 +00002496 // We fully assign registers here at isel time. This is not optimal, but
2497 // should work. For register classes that correspond to LLVM classes, we
2498 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2499 // over the constraints, collecting fixed registers that we know we can't use.
2500 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002501 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002502 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002503 std::string ConstraintCode =
2504 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002505
Chris Lattner1efa40f2006-02-22 00:56:39 +00002506 MVT::ValueType OpVT;
2507
2508 // Compute the value type for each operand and add it to ConstraintVTs.
2509 switch (Constraints[i].Type) {
2510 case InlineAsm::isOutput:
2511 if (!Constraints[i].isIndirectOutput) {
2512 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2513 OpVT = TLI.getValueType(I.getType());
2514 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002515 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002516 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2517 OpNum++; // Consumes a call operand.
2518 }
2519 break;
2520 case InlineAsm::isInput:
2521 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2522 OpNum++; // Consumes a call operand.
2523 break;
2524 case InlineAsm::isClobber:
2525 OpVT = MVT::Other;
2526 break;
2527 }
2528
2529 ConstraintVTs.push_back(OpVT);
2530
Chris Lattner864635a2006-02-22 22:37:12 +00002531 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2532 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002533
Chris Lattner864635a2006-02-22 22:37:12 +00002534 // Build a list of regs that this operand uses. This always has a single
2535 // element for promoted/expanded operands.
2536 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2537 false, false,
2538 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002539
2540 switch (Constraints[i].Type) {
2541 case InlineAsm::isOutput:
2542 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002543 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002544 // If this is an early-clobber output, it cannot be assigned to the same
2545 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002546 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002547 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002548 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002549 case InlineAsm::isInput:
2550 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002551 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002552 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002553 case InlineAsm::isClobber:
2554 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002555 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2556 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002557 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002558 }
2559 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002560
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002561 // Loop over all of the inputs, copying the operand values into the
2562 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002563 RegsForValue RetValRegs;
2564 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002565 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002566
Chris Lattner6656dd12006-01-31 02:03:41 +00002567 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002568 std::string ConstraintCode =
2569 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002570
Chris Lattner2cc2f662006-02-01 01:28:23 +00002571 switch (Constraints[i].Type) {
2572 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002573 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2574 if (ConstraintCode.size() == 1) // not a physreg name.
2575 CTy = TLI.getConstraintType(ConstraintCode[0]);
2576
2577 if (CTy == TargetLowering::C_Memory) {
2578 // Memory output.
2579 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2580
2581 // Check that the operand (the address to store to) isn't a float.
2582 if (!MVT::isInteger(InOperandVal.getValueType()))
2583 assert(0 && "MATCH FAIL!");
2584
2585 if (!Constraints[i].isIndirectOutput)
2586 assert(0 && "MATCH FAIL!");
2587
2588 OpNum++; // Consumes a call operand.
2589
2590 // Extend/truncate to the right pointer type if needed.
2591 MVT::ValueType PtrType = TLI.getPointerTy();
2592 if (InOperandVal.getValueType() < PtrType)
2593 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2594 else if (InOperandVal.getValueType() > PtrType)
2595 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2596
2597 // Add information to the INLINEASM node to know about this output.
2598 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2599 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2600 AsmNodeOperands.push_back(InOperandVal);
2601 break;
2602 }
2603
2604 // Otherwise, this is a register output.
2605 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2606
Chris Lattner864635a2006-02-22 22:37:12 +00002607 // If this is an early-clobber output, or if there is an input
2608 // constraint that matches this, we need to reserve the input register
2609 // so no other inputs allocate to it.
2610 bool UsesInputRegister = false;
2611 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2612 UsesInputRegister = true;
2613
2614 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002615 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002616 RegsForValue Regs =
2617 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2618 true, UsesInputRegister,
2619 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002620 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002621 cerr << "Couldn't allocate output reg for contraint '"
2622 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002623 exit(1);
2624 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002625
Chris Lattner2cc2f662006-02-01 01:28:23 +00002626 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002627 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002628 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002629 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002630 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002631 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002632 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2633 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002634 OpNum++; // Consumes a call operand.
2635 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002636
2637 // Add information to the INLINEASM node to know that this register is
2638 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002639 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002640 break;
2641 }
2642 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002643 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002644 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002645
Chris Lattner2223aea2006-02-02 00:25:23 +00002646 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2647 // If this is required to match an output register we have already set,
2648 // just use its register.
2649 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002650
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002651 // Scan until we find the definition we already emitted of this operand.
2652 // When we find it, create a RegsForValue operand.
2653 unsigned CurOp = 2; // The first operand.
2654 for (; OperandNo; --OperandNo) {
2655 // Advance to the next operand.
2656 unsigned NumOps =
2657 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002658 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2659 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002660 "Skipped past definitions?");
2661 CurOp += (NumOps>>3)+1;
2662 }
2663
2664 unsigned NumOps =
2665 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2666 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2667 "Skipped past definitions?");
2668
2669 // Add NumOps>>3 registers to MatchedRegs.
2670 RegsForValue MatchedRegs;
2671 MatchedRegs.ValueVT = InOperandVal.getValueType();
2672 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2673 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2674 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2675 MatchedRegs.Regs.push_back(Reg);
2676 }
2677
2678 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002679 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2680 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002681 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002682 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002683 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002684
2685 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2686 if (ConstraintCode.size() == 1) // not a physreg name.
2687 CTy = TLI.getConstraintType(ConstraintCode[0]);
2688
2689 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002690 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2691 ConstraintCode[0], DAG);
2692 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002693 cerr << "Invalid operand for inline asm constraint '"
2694 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002695 exit(1);
2696 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002697
2698 // Add information to the INLINEASM node to know about this input.
2699 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2700 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2701 AsmNodeOperands.push_back(InOperandVal);
2702 break;
2703 } else if (CTy == TargetLowering::C_Memory) {
2704 // Memory input.
2705
2706 // Check that the operand isn't a float.
2707 if (!MVT::isInteger(InOperandVal.getValueType()))
2708 assert(0 && "MATCH FAIL!");
2709
2710 // Extend/truncate to the right pointer type if needed.
2711 MVT::ValueType PtrType = TLI.getPointerTy();
2712 if (InOperandVal.getValueType() < PtrType)
2713 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2714 else if (InOperandVal.getValueType() > PtrType)
2715 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2716
2717 // Add information to the INLINEASM node to know about this input.
2718 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2719 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2720 AsmNodeOperands.push_back(InOperandVal);
2721 break;
2722 }
2723
2724 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2725
2726 // Copy the input into the appropriate registers.
2727 RegsForValue InRegs =
2728 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2729 false, true, OutputRegs, InputRegs);
2730 // FIXME: should be match fail.
2731 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2732
Evan Chenga8441262006-06-15 08:11:54 +00002733 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002734
2735 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002736 break;
2737 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002738 case InlineAsm::isClobber: {
2739 RegsForValue ClobberedRegs =
2740 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2741 OutputRegs, InputRegs);
2742 // Add the clobbered value to the operand list, so that the register
2743 // allocator is aware that the physreg got clobbered.
2744 if (!ClobberedRegs.Regs.empty())
2745 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002746 break;
2747 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002748 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002749 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002750
2751 // Finish up input operands.
2752 AsmNodeOperands[0] = Chain;
2753 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2754
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002755 Chain = DAG.getNode(ISD::INLINEASM,
2756 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002757 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002758 Flag = Chain.getValue(1);
2759
Chris Lattner6656dd12006-01-31 02:03:41 +00002760 // If this asm returns a register value, copy the result from that register
2761 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002762 if (!RetValRegs.Regs.empty())
2763 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002764
Chris Lattner6656dd12006-01-31 02:03:41 +00002765 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2766
2767 // Process indirect outputs, first output all of the flagged copies out of
2768 // physregs.
2769 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002770 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002771 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002772 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2773 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002774 }
2775
2776 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002777 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002778 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002779 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002780 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002781 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002782 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002783 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2784 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002785 DAG.setRoot(Chain);
2786}
2787
2788
Chris Lattner1c08c712005-01-07 07:47:53 +00002789void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2790 SDOperand Src = getValue(I.getOperand(0));
2791
2792 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002793
2794 if (IntPtr < Src.getValueType())
2795 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2796 else if (IntPtr > Src.getValueType())
2797 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002798
2799 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002800 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002801 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2802 Src, getIntPtrConstant(ElementSize));
2803
Reid Spencer47857812006-12-31 05:55:36 +00002804 TargetLowering::ArgListTy Args;
2805 TargetLowering::ArgListEntry Entry;
2806 Entry.Node = Src;
2807 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2808 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002809 Entry.isInReg = false;
2810 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002811 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002812
2813 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002814 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002815 DAG.getExternalSymbol("malloc", IntPtr),
2816 Args, DAG);
2817 setValue(&I, Result.first); // Pointers always fit in registers
2818 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002819}
2820
2821void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002822 TargetLowering::ArgListTy Args;
2823 TargetLowering::ArgListEntry Entry;
2824 Entry.Node = getValue(I.getOperand(0));
2825 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2826 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002827 Entry.isInReg = false;
2828 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002829 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002830 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002831 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002832 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002833 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2834 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002835}
2836
Chris Lattner025c39b2005-08-26 20:54:47 +00002837// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2838// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2839// instructions are special in various ways, which require special support to
2840// insert. The specified MachineInstr is created but not inserted into any
2841// basic blocks, and the scheduler passes ownership of it to this method.
2842MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2843 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002844 cerr << "If a target marks an instruction with "
2845 << "'usesCustomDAGSchedInserter', it must implement "
2846 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002847 abort();
2848 return 0;
2849}
2850
Chris Lattner39ae3622005-01-09 00:00:49 +00002851void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002852 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2853 getValue(I.getOperand(1)),
2854 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002855}
2856
2857void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002858 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2859 getValue(I.getOperand(0)),
2860 DAG.getSrcValue(I.getOperand(0)));
2861 setValue(&I, V);
2862 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002863}
2864
2865void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002866 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2867 getValue(I.getOperand(1)),
2868 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002869}
2870
2871void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002872 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2873 getValue(I.getOperand(1)),
2874 getValue(I.getOperand(2)),
2875 DAG.getSrcValue(I.getOperand(1)),
2876 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002877}
2878
Evan Chengb15974a2006-12-12 07:27:38 +00002879/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2880/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2881static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2882 unsigned &i, SelectionDAG &DAG,
2883 TargetLowering &TLI) {
2884 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2885 return SDOperand(Arg, i++);
2886
2887 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2888 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2889 if (NumVals == 1) {
2890 return DAG.getNode(ISD::BIT_CONVERT, VT,
2891 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2892 } else if (NumVals == 2) {
2893 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2894 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2895 if (!TLI.isLittleEndian())
2896 std::swap(Lo, Hi);
2897 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2898 } else {
2899 // Value scalarized into many values. Unimp for now.
2900 assert(0 && "Cannot expand i64 -> i16 yet!");
2901 }
2902 return SDOperand();
2903}
2904
Chris Lattnerfdfded52006-04-12 16:20:43 +00002905/// TargetLowering::LowerArguments - This is the default LowerArguments
2906/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002907/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2908/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002909std::vector<SDOperand>
2910TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002911 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002912 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2913 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002914 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002915 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2916 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2917
2918 // Add one result value for each formal argument.
2919 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00002920 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00002921 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
2922 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002923 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00002924 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002925 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
2926 unsigned Flags = (isInReg << 1) | (isSRet << 2);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002927
2928 switch (getTypeAction(VT)) {
2929 default: assert(0 && "Unknown type action!");
2930 case Legal:
2931 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002932 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002933 break;
2934 case Promote:
2935 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002936 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002937 break;
2938 case Expand:
2939 if (VT != MVT::Vector) {
2940 // If this is a large integer, it needs to be broken up into small
2941 // integers. Figure out what the destination type is and how many small
2942 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00002943 MVT::ValueType NVT = getTypeToExpandTo(VT);
2944 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002945 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002946 RetVals.push_back(NVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002947 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2948 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00002949 } else {
2950 // Otherwise, this is a vector type. We only support legal vectors
2951 // right now.
2952 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2953 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002954
Chris Lattnerfdfded52006-04-12 16:20:43 +00002955 // Figure out if there is a Packed type corresponding to this Vector
2956 // type. If so, convert to the packed type.
2957 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2958 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2959 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002960 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002961 } else {
2962 assert(0 && "Don't support illegal by-val vector arguments yet!");
2963 }
2964 }
2965 break;
2966 }
2967 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002968
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002969 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002970
2971 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002972 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2973 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002974 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002975
2976 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002977
2978 // Set up the return result vector.
2979 Ops.clear();
2980 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00002981 unsigned Idx = 1;
2982 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2983 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002984 MVT::ValueType VT = getValueType(I->getType());
2985
2986 switch (getTypeAction(VT)) {
2987 default: assert(0 && "Unknown type action!");
2988 case Legal:
2989 Ops.push_back(SDOperand(Result, i++));
2990 break;
2991 case Promote: {
2992 SDOperand Op(Result, i++);
2993 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00002994 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
2995 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
2996 DAG.getValueType(VT));
2997 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
2998 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
2999 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003000 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3001 } else {
3002 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3003 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3004 }
3005 Ops.push_back(Op);
3006 break;
3007 }
3008 case Expand:
3009 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003010 // If this is a large integer or a floating point node that needs to be
3011 // expanded, it needs to be reassembled from small integers. Figure out
3012 // what the source elt type is and how many small integers it is.
3013 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003014 } else {
3015 // Otherwise, this is a vector type. We only support legal vectors
3016 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00003017 const PackedType *PTy = cast<PackedType>(I->getType());
3018 unsigned NumElems = PTy->getNumElements();
3019 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003020
Chris Lattnerfdfded52006-04-12 16:20:43 +00003021 // Figure out if there is a Packed type corresponding to this Vector
3022 // type. If so, convert to the packed type.
3023 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003024 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003025 SDOperand N = SDOperand(Result, i++);
3026 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003027 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3028 DAG.getConstant(NumElems, MVT::i32),
3029 DAG.getValueType(getValueType(EltTy)));
3030 Ops.push_back(N);
3031 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003032 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003033 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003034 }
3035 }
3036 break;
3037 }
3038 }
3039 return Ops;
3040}
3041
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003042
Evan Chengb15974a2006-12-12 07:27:38 +00003043/// ExpandScalarCallArgs - Recursively expand call argument node by
3044/// bit_converting it or extract a pair of elements from the larger node.
3045static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003046 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003047 SmallVector<SDOperand, 32> &Ops,
3048 SelectionDAG &DAG,
3049 TargetLowering &TLI) {
3050 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3051 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003052 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003053 return;
3054 }
3055
3056 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3057 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3058 if (NumVals == 1) {
3059 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003060 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI);
Evan Chengb15974a2006-12-12 07:27:38 +00003061 } else if (NumVals == 2) {
3062 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3063 DAG.getConstant(0, TLI.getPointerTy()));
3064 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3065 DAG.getConstant(1, TLI.getPointerTy()));
3066 if (!TLI.isLittleEndian())
3067 std::swap(Lo, Hi);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003068 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI);
3069 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI);
Evan Chengb15974a2006-12-12 07:27:38 +00003070 } else {
3071 // Value scalarized into many values. Unimp for now.
3072 assert(0 && "Cannot expand i64 -> i16 yet!");
3073 }
3074}
3075
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003076/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3077/// implementation, which just inserts an ISD::CALL node, which is later custom
3078/// lowered by the target to something concrete. FIXME: When all targets are
3079/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3080std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003081TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3082 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003083 unsigned CallingConv, bool isTailCall,
3084 SDOperand Callee,
3085 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003086 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003087 Ops.push_back(Chain); // Op#0 - Chain
3088 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3089 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3090 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3091 Ops.push_back(Callee);
3092
3093 // Handle all of the outgoing arguments.
3094 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003095 MVT::ValueType VT = getValueType(Args[i].Ty);
3096 SDOperand Op = Args[i].Node;
3097 bool isSigned = Args[i].isSigned;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003098 bool isInReg = Args[i].isInReg;
3099 bool isSRet = Args[i].isSRet;
3100 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003101 switch (getTypeAction(VT)) {
3102 default: assert(0 && "Unknown type action!");
3103 case Legal:
3104 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003105 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003106 break;
3107 case Promote:
3108 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003109 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003110 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3111 } else {
3112 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3113 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3114 }
3115 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003116 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003117 break;
3118 case Expand:
3119 if (VT != MVT::Vector) {
3120 // If this is a large integer, it needs to be broken down into small
3121 // integers. Figure out what the source elt type is and how many small
3122 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003123 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003124 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003125 // Otherwise, this is a vector type. We only support legal vectors
3126 // right now.
Reid Spencer47857812006-12-31 05:55:36 +00003127 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003128 unsigned NumElems = PTy->getNumElements();
3129 const Type *EltTy = PTy->getElementType();
3130
3131 // Figure out if there is a Packed type corresponding to this Vector
3132 // type. If so, convert to the packed type.
3133 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003134 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3135 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3136 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3137 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003138 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003139 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003140 assert(0 && "Don't support illegal by-val vector call args yet!");
3141 abort();
3142 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003143 }
3144 break;
3145 }
3146 }
3147
3148 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003149 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003150
3151 if (RetTy != Type::VoidTy) {
3152 MVT::ValueType VT = getValueType(RetTy);
3153 switch (getTypeAction(VT)) {
3154 default: assert(0 && "Unknown type action!");
3155 case Legal:
3156 RetTys.push_back(VT);
3157 break;
3158 case Promote:
3159 RetTys.push_back(getTypeToTransformTo(VT));
3160 break;
3161 case Expand:
3162 if (VT != MVT::Vector) {
3163 // If this is a large integer, it needs to be reassembled from small
3164 // integers. Figure out what the source elt type is and how many small
3165 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003166 MVT::ValueType NVT = getTypeToExpandTo(VT);
3167 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003168 for (unsigned i = 0; i != NumVals; ++i)
3169 RetTys.push_back(NVT);
3170 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003171 // Otherwise, this is a vector type. We only support legal vectors
3172 // right now.
3173 const PackedType *PTy = cast<PackedType>(RetTy);
3174 unsigned NumElems = PTy->getNumElements();
3175 const Type *EltTy = PTy->getElementType();
3176
3177 // Figure out if there is a Packed type corresponding to this Vector
3178 // type. If so, convert to the packed type.
3179 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3180 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3181 RetTys.push_back(TVT);
3182 } else {
3183 assert(0 && "Don't support illegal by-val vector call results yet!");
3184 abort();
3185 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003186 }
3187 }
3188 }
3189
3190 RetTys.push_back(MVT::Other); // Always has a chain.
3191
3192 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003193 SDOperand Res = DAG.getNode(ISD::CALL,
3194 DAG.getVTList(&RetTys[0], RetTys.size()),
3195 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003196
3197 // This returns a pair of operands. The first element is the
3198 // return value for the function (if RetTy is not VoidTy). The second
3199 // element is the outgoing token chain.
3200 SDOperand ResVal;
3201 if (RetTys.size() != 1) {
3202 MVT::ValueType VT = getValueType(RetTy);
3203 if (RetTys.size() == 2) {
3204 ResVal = Res;
3205
3206 // If this value was promoted, truncate it down.
3207 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003208 if (VT == MVT::Vector) {
3209 // Insert a VBITCONVERT to convert from the packed result type to the
3210 // MVT::Vector type.
3211 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3212 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3213
3214 // Figure out if there is a Packed type corresponding to this Vector
3215 // type. If so, convert to the packed type.
3216 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3217 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003218 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3219 // "N x PTyElementVT" MVT::Vector type.
3220 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003221 DAG.getConstant(NumElems, MVT::i32),
3222 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003223 } else {
3224 abort();
3225 }
3226 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003227 unsigned AssertOp = ISD::AssertSext;
3228 if (!RetTyIsSigned)
3229 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003230 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3231 DAG.getValueType(VT));
3232 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3233 } else {
3234 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003235 if (getTypeAction(VT) == Expand)
3236 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3237 else
3238 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003239 }
3240 }
3241 } else if (RetTys.size() == 3) {
3242 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3243 Res.getValue(0), Res.getValue(1));
3244
3245 } else {
3246 assert(0 && "Case not handled yet!");
3247 }
3248 }
3249
3250 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3251}
3252
Chris Lattner50381b62005-05-14 05:50:48 +00003253SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003254 assert(0 && "LowerOperation not implemented for this target!");
3255 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003256 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003257}
3258
Nate Begeman0aed7842006-01-28 03:14:31 +00003259SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3260 SelectionDAG &DAG) {
3261 assert(0 && "CustomPromoteOperation not implemented for this target!");
3262 abort();
3263 return SDOperand();
3264}
3265
Evan Cheng74d0aa92006-02-15 21:59:04 +00003266/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003267/// operand.
3268static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003269 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003270 MVT::ValueType CurVT = VT;
3271 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3272 uint64_t Val = C->getValue() & 255;
3273 unsigned Shift = 8;
3274 while (CurVT != MVT::i8) {
3275 Val = (Val << Shift) | Val;
3276 Shift <<= 1;
3277 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003278 }
3279 return DAG.getConstant(Val, VT);
3280 } else {
3281 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3282 unsigned Shift = 8;
3283 while (CurVT != MVT::i8) {
3284 Value =
3285 DAG.getNode(ISD::OR, VT,
3286 DAG.getNode(ISD::SHL, VT, Value,
3287 DAG.getConstant(Shift, MVT::i8)), Value);
3288 Shift <<= 1;
3289 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003290 }
3291
3292 return Value;
3293 }
3294}
3295
Evan Cheng74d0aa92006-02-15 21:59:04 +00003296/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3297/// used when a memcpy is turned into a memset when the source is a constant
3298/// string ptr.
3299static SDOperand getMemsetStringVal(MVT::ValueType VT,
3300 SelectionDAG &DAG, TargetLowering &TLI,
3301 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003302 uint64_t Val = 0;
3303 unsigned MSB = getSizeInBits(VT) / 8;
3304 if (TLI.isLittleEndian())
3305 Offset = Offset + MSB - 1;
3306 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003307 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003308 Offset += TLI.isLittleEndian() ? -1 : 1;
3309 }
3310 return DAG.getConstant(Val, VT);
3311}
3312
Evan Cheng1db92f92006-02-14 08:22:34 +00003313/// getMemBasePlusOffset - Returns base and offset node for the
3314static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3315 SelectionDAG &DAG, TargetLowering &TLI) {
3316 MVT::ValueType VT = Base.getValueType();
3317 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3318}
3319
Evan Chengc4f8eee2006-02-14 20:12:38 +00003320/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003321/// to replace the memset / memcpy is below the threshold. It also returns the
3322/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003323static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3324 unsigned Limit, uint64_t Size,
3325 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003326 MVT::ValueType VT;
3327
3328 if (TLI.allowsUnalignedMemoryAccesses()) {
3329 VT = MVT::i64;
3330 } else {
3331 switch (Align & 7) {
3332 case 0:
3333 VT = MVT::i64;
3334 break;
3335 case 4:
3336 VT = MVT::i32;
3337 break;
3338 case 2:
3339 VT = MVT::i16;
3340 break;
3341 default:
3342 VT = MVT::i8;
3343 break;
3344 }
3345 }
3346
Evan Cheng80e89d72006-02-14 09:11:59 +00003347 MVT::ValueType LVT = MVT::i64;
3348 while (!TLI.isTypeLegal(LVT))
3349 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3350 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003351
Evan Cheng80e89d72006-02-14 09:11:59 +00003352 if (VT > LVT)
3353 VT = LVT;
3354
Evan Chengdea72452006-02-14 23:05:54 +00003355 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003356 while (Size != 0) {
3357 unsigned VTSize = getSizeInBits(VT) / 8;
3358 while (VTSize > Size) {
3359 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003360 VTSize >>= 1;
3361 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003362 assert(MVT::isInteger(VT));
3363
3364 if (++NumMemOps > Limit)
3365 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003366 MemOps.push_back(VT);
3367 Size -= VTSize;
3368 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003369
3370 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003371}
3372
Chris Lattner7041ee32005-01-11 05:56:49 +00003373void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003374 SDOperand Op1 = getValue(I.getOperand(1));
3375 SDOperand Op2 = getValue(I.getOperand(2));
3376 SDOperand Op3 = getValue(I.getOperand(3));
3377 SDOperand Op4 = getValue(I.getOperand(4));
3378 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3379 if (Align == 0) Align = 1;
3380
3381 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3382 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003383
3384 // Expand memset / memcpy to a series of load / store ops
3385 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003386 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003387 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003388 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003389 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003390 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3391 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003392 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003393 unsigned Offset = 0;
3394 for (unsigned i = 0; i < NumMemOps; i++) {
3395 MVT::ValueType VT = MemOps[i];
3396 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003397 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003398 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003399 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003400 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003401 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003402 Offset += VTSize;
3403 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003404 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003405 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003406 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003407 case ISD::MEMCPY: {
3408 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3409 Size->getValue(), Align, TLI)) {
3410 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003411 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003412 GlobalAddressSDNode *G = NULL;
3413 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003414 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003415
3416 if (Op2.getOpcode() == ISD::GlobalAddress)
3417 G = cast<GlobalAddressSDNode>(Op2);
3418 else if (Op2.getOpcode() == ISD::ADD &&
3419 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3420 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3421 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003422 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003423 }
3424 if (G) {
3425 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003426 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003427 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003428 if (!Str.empty()) {
3429 CopyFromStr = true;
3430 SrcOff += SrcDelta;
3431 }
3432 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003433 }
3434
Evan Chengc080d6f2006-02-15 01:54:51 +00003435 for (unsigned i = 0; i < NumMemOps; i++) {
3436 MVT::ValueType VT = MemOps[i];
3437 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003438 SDOperand Value, Chain, Store;
3439
Evan Chengcffbb512006-02-16 23:11:42 +00003440 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003441 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3442 Chain = getRoot();
3443 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003444 DAG.getStore(Chain, Value,
3445 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003446 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003447 } else {
3448 Value = DAG.getLoad(VT, getRoot(),
3449 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003450 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003451 Chain = Value.getValue(1);
3452 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003453 DAG.getStore(Chain, Value,
3454 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003455 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003456 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003457 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003458 SrcOff += VTSize;
3459 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003460 }
3461 }
3462 break;
3463 }
3464 }
3465
3466 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003467 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3468 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003469 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003470 }
3471 }
3472
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003473 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003474}
3475
Chris Lattner7041ee32005-01-11 05:56:49 +00003476//===----------------------------------------------------------------------===//
3477// SelectionDAGISel code
3478//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003479
3480unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3481 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3482}
3483
Chris Lattner495a0b52005-08-17 06:37:43 +00003484void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003485 // FIXME: we only modify the CFG to split critical edges. This
3486 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003487 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003488}
Chris Lattner1c08c712005-01-07 07:47:53 +00003489
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003490
Chris Lattner90323642006-05-05 21:17:49 +00003491/// OptimizeNoopCopyExpression - We have determined that the specified cast
3492/// instruction is a noop copy (e.g. it's casting from one pointer type to
3493/// another, int->uint, or int->sbyte on PPC.
3494///
3495/// Return true if any changes are made.
3496static bool OptimizeNoopCopyExpression(CastInst *CI) {
3497 BasicBlock *DefBB = CI->getParent();
3498
3499 /// InsertedCasts - Only insert a cast in each block once.
3500 std::map<BasicBlock*, CastInst*> InsertedCasts;
3501
3502 bool MadeChange = false;
3503 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3504 UI != E; ) {
3505 Use &TheUse = UI.getUse();
3506 Instruction *User = cast<Instruction>(*UI);
3507
3508 // Figure out which BB this cast is used in. For PHI's this is the
3509 // appropriate predecessor block.
3510 BasicBlock *UserBB = User->getParent();
3511 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3512 unsigned OpVal = UI.getOperandNo()/2;
3513 UserBB = PN->getIncomingBlock(OpVal);
3514 }
3515
3516 // Preincrement use iterator so we don't invalidate it.
3517 ++UI;
3518
3519 // If this user is in the same block as the cast, don't change the cast.
3520 if (UserBB == DefBB) continue;
3521
3522 // If we have already inserted a cast into this block, use it.
3523 CastInst *&InsertedCast = InsertedCasts[UserBB];
3524
3525 if (!InsertedCast) {
3526 BasicBlock::iterator InsertPt = UserBB->begin();
3527 while (isa<PHINode>(InsertPt)) ++InsertPt;
3528
3529 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003530 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3531 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003532 MadeChange = true;
3533 }
3534
3535 // Replace a use of the cast with a use of the new casat.
3536 TheUse = InsertedCast;
3537 }
3538
3539 // If we removed all uses, nuke the cast.
3540 if (CI->use_empty())
3541 CI->eraseFromParent();
3542
3543 return MadeChange;
3544}
3545
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003546/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3547/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003548static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3549 Instruction *GEPI, Value *Ptr,
3550 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003551 if (V) return V; // Already computed.
3552
Reid Spencer3da59db2006-11-27 01:05:10 +00003553 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003554 BasicBlock::iterator InsertPt;
3555 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003556 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003557 InsertPt = GEPI;
3558 ++InsertPt;
3559 } else {
3560 // Otherwise, insert at the top of BB, after any PHI nodes
3561 InsertPt = BB->begin();
3562 while (isa<PHINode>(InsertPt)) ++InsertPt;
3563 }
3564
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003565 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3566 // BB so that there is only one value live across basic blocks (the cast
3567 // operand).
3568 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3569 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003570 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3571 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003572
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003573 // Add the offset, cast it to the right type.
3574 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003575 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3576 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3577 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003578}
3579
Chris Lattner90323642006-05-05 21:17:49 +00003580/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3581/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3582/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3583/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3584/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3585/// the constant add into a load or store instruction. Additionally, if a user
3586/// is a pointer-pointer cast, we look through it to find its users.
3587static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3588 Constant *PtrOffset, BasicBlock *DefBB,
3589 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003590 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003591 while (!RepPtr->use_empty()) {
3592 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003593
Reid Spencer3da59db2006-11-27 01:05:10 +00003594 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3595 // used for a Pointer-Pointer cast.
3596 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003597 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003598
Chris Lattner90323642006-05-05 21:17:49 +00003599 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3600 // could invalidate an iterator.
3601 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3602 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003603 }
3604
Chris Lattner90323642006-05-05 21:17:49 +00003605 // If this is a load of the pointer, or a store through the pointer, emit
3606 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003607 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003608 if (isa<LoadInst>(User) ||
3609 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3610 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3611 User->getParent(), GEPI,
3612 Ptr, PtrOffset);
3613 } else {
3614 // If this use is not foldable into the addressing mode, use a version
3615 // emitted in the GEP block.
3616 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3617 Ptr, PtrOffset);
3618 }
3619
Chris Lattnerf0df8822006-05-06 09:10:37 +00003620 if (GEPI->getType() != RepPtr->getType()) {
3621 BasicBlock::iterator IP = NewVal;
3622 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003623 // NewVal must be a GEP which must be pointer type, so BitCast
3624 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003625 }
Chris Lattner90323642006-05-05 21:17:49 +00003626 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003627 }
3628}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003629
Chris Lattner90323642006-05-05 21:17:49 +00003630
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003631/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3632/// selection, we want to be a bit careful about some things. In particular, if
3633/// we have a GEP instruction that is used in a different block than it is
3634/// defined, the addressing expression of the GEP cannot be folded into loads or
3635/// stores that use it. In this case, decompose the GEP and move constant
3636/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003637static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003638 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003639 // If this GEP is only used inside the block it is defined in, there is no
3640 // need to rewrite it.
3641 bool isUsedOutsideDefBB = false;
3642 BasicBlock *DefBB = GEPI->getParent();
3643 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3644 UI != E; ++UI) {
3645 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3646 isUsedOutsideDefBB = true;
3647 break;
3648 }
3649 }
Chris Lattner90323642006-05-05 21:17:49 +00003650 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003651
3652 // If this GEP has no non-zero constant indices, there is nothing we can do,
3653 // ignore it.
3654 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003655 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003656 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3657 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003658 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003659 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003660 hasConstantIndex = true;
3661 break;
3662 }
Chris Lattner90323642006-05-05 21:17:49 +00003663 } else {
3664 hasVariableIndex = true;
3665 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003666 }
Chris Lattner90323642006-05-05 21:17:49 +00003667
3668 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3669 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003670 /// The GEP operand must be a pointer, so must its result -> BitCast
3671 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003672 GEPI->getName(), GEPI);
3673 GEPI->replaceAllUsesWith(NC);
3674 GEPI->eraseFromParent();
3675 return true;
3676 }
3677
Chris Lattner3802c252005-12-11 09:05:13 +00003678 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003679 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3680 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003681
3682 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3683 // constant offset (which we now know is non-zero) and deal with it later.
3684 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003685 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003686 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003687 const Type *Ty = GEPI->getOperand(0)->getType();
3688
3689 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3690 E = GEPI->op_end(); OI != E; ++OI) {
3691 Value *Idx = *OI;
3692 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003693 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003694 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003695 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003696 Ty = StTy->getElementType(Field);
3697 } else {
3698 Ty = cast<SequentialType>(Ty)->getElementType();
3699
3700 // Handle constant subscripts.
3701 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003702 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003703 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003704 continue;
3705 }
3706
3707 // Ptr = Ptr + Idx * ElementSize;
3708
3709 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003710 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003711
Owen Andersona69571c2006-05-03 01:29:57 +00003712 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003713 // Mask off bits that should not be set.
3714 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003715 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003716
3717 // Multiply by the element size and add to the base.
3718 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3719 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3720 }
3721 }
3722
3723 // Make sure that the offset fits in uintptr_t.
3724 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003725 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003726
3727 // Okay, we have now emitted all of the variable index parts to the BB that
3728 // the GEP is defined in. Loop over all of the using instructions, inserting
3729 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003730 // instruction to use the newly computed value, making GEPI dead. When the
3731 // user is a load or store instruction address, we emit the add into the user
3732 // block, otherwise we use a canonical version right next to the gep (these
3733 // won't be foldable as addresses, so we might as well share the computation).
3734
Chris Lattnerf0df8822006-05-06 09:10:37 +00003735 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003736 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003737
3738 // Finally, the GEP is dead, remove it.
3739 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003740
3741 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003742}
3743
Chris Lattnerbad7f482006-10-28 19:22:10 +00003744
3745/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3746/// successor if it will improve codegen. We only do this if the successor has
3747/// phi nodes (otherwise critical edges are ok). If there is already another
3748/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3749/// instead of introducing a new block.
3750static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3751 BasicBlock *TIBB = TI->getParent();
3752 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3753 assert(isa<PHINode>(Dest->begin()) &&
3754 "This should only be called if Dest has a PHI!");
3755
3756 /// TIPHIValues - This array is lazily computed to determine the values of
3757 /// PHIs in Dest that TI would provide.
3758 std::vector<Value*> TIPHIValues;
3759
3760 // Check to see if Dest has any blocks that can be used as a split edge for
3761 // this terminator.
3762 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3763 BasicBlock *Pred = *PI;
3764 // To be usable, the pred has to end with an uncond branch to the dest.
3765 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3766 if (!PredBr || !PredBr->isUnconditional() ||
3767 // Must be empty other than the branch.
3768 &Pred->front() != PredBr)
3769 continue;
3770
3771 // Finally, since we know that Dest has phi nodes in it, we have to make
3772 // sure that jumping to Pred will have the same affect as going to Dest in
3773 // terms of PHI values.
3774 PHINode *PN;
3775 unsigned PHINo = 0;
3776 bool FoundMatch = true;
3777 for (BasicBlock::iterator I = Dest->begin();
3778 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3779 if (PHINo == TIPHIValues.size())
3780 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3781
3782 // If the PHI entry doesn't work, we can't use this pred.
3783 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3784 FoundMatch = false;
3785 break;
3786 }
3787 }
3788
3789 // If we found a workable predecessor, change TI to branch to Succ.
3790 if (FoundMatch) {
3791 Dest->removePredecessor(TIBB);
3792 TI->setSuccessor(SuccNum, Pred);
3793 return;
3794 }
3795 }
3796
3797 SplitCriticalEdge(TI, SuccNum, P, true);
3798}
3799
3800
Chris Lattner1c08c712005-01-07 07:47:53 +00003801bool SelectionDAGISel::runOnFunction(Function &Fn) {
3802 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3803 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003804 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003805
Chris Lattner47e32e62006-10-28 17:04:37 +00003806 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003807 //
Chris Lattner7e598092006-05-05 01:04:50 +00003808 // In this pass we also look for GEP and cast instructions that are used
3809 // across basic blocks and rewrite them to improve basic-block-at-a-time
3810 // selection.
3811 //
Chris Lattner90323642006-05-05 21:17:49 +00003812 bool MadeChange = true;
3813 while (MadeChange) {
3814 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003815 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003816 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003817 TerminatorInst *BBTI = BB->getTerminator();
3818 if (BBTI->getNumSuccessors() > 1) {
3819 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003820 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3821 isCriticalEdge(BBTI, i, true))
3822 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003823 }
3824
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003825
Chris Lattner57f9a432006-09-28 06:17:10 +00003826 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003827 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003828
3829 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3830 // If we found an inline asm expession, and if the target knows how to
3831 // lower it to normal LLVM code, do so now.
3832 if (isa<InlineAsm>(CI->getCalledValue()))
3833 if (const TargetAsmInfo *TAI =
3834 TLI.getTargetMachine().getTargetAsmInfo()) {
3835 if (TAI->ExpandInlineAsm(CI))
3836 BBI = BB->begin();
3837 }
3838 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003839 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003840 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003841 // If the source of the cast is a constant, then this should have
3842 // already been constant folded. The only reason NOT to constant fold
3843 // it is if something (e.g. LSR) was careful to place the constant
3844 // evaluation in a block other than then one that uses it (e.g. to hoist
3845 // the address of globals out of a loop). If this is the case, we don't
3846 // want to forward-subst the cast.
3847 if (isa<Constant>(CI->getOperand(0)))
3848 continue;
3849
Chris Lattner7e598092006-05-05 01:04:50 +00003850 // If this is a noop copy, sink it into user blocks to reduce the number
3851 // of virtual registers that must be created and coallesced.
3852 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3853 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3854
3855 // This is an fp<->int conversion?
3856 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3857 continue;
3858
3859 // If this is an extension, it will be a zero or sign extension, which
3860 // isn't a noop.
3861 if (SrcVT < DstVT) continue;
3862
3863 // If these values will be promoted, find out what they will be promoted
3864 // to. This helps us consider truncates on PPC as noop copies when they
3865 // are.
3866 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3867 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3868 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3869 DstVT = TLI.getTypeToTransformTo(DstVT);
3870
3871 // If, after promotion, these are the same types, this is a noop copy.
3872 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003873 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003874 }
3875 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003876 }
Chris Lattner90323642006-05-05 21:17:49 +00003877 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003878
Chris Lattner1c08c712005-01-07 07:47:53 +00003879 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3880
3881 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3882 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003883
Chris Lattner1c08c712005-01-07 07:47:53 +00003884 return true;
3885}
3886
Chris Lattner571e4342006-10-27 21:36:01 +00003887SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3888 unsigned Reg) {
3889 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003890 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003891 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003892 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003893
3894 // If this type is not legal, we must make sure to not create an invalid
3895 // register use.
3896 MVT::ValueType SrcVT = Op.getValueType();
3897 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003898 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003899 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003900 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003901 // Handle copies from generic vectors to registers.
3902 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3903 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3904 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003905
Chris Lattner70c2a612006-03-31 02:06:56 +00003906 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3907 // MVT::Vector type.
3908 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3909 DAG.getConstant(NE, MVT::i32),
3910 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003911
Chris Lattner70c2a612006-03-31 02:06:56 +00003912 // Loop over all of the elements of the resultant vector,
3913 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3914 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003915 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003916 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003917 for (unsigned i = 0; i != NE; ++i) {
3918 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003919 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003920 if (PTyElementVT == PTyLegalElementVT) {
3921 // Elements are legal.
3922 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3923 } else if (PTyLegalElementVT > PTyElementVT) {
3924 // Elements are promoted.
3925 if (MVT::isFloatingPoint(PTyLegalElementVT))
3926 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3927 else
3928 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3929 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3930 } else {
3931 // Elements are expanded.
3932 // The src value is expanded into multiple registers.
3933 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003934 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003935 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003936 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003937 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3938 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3939 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003940 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003941 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3942 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00003943 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003944 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003945 if (MVT::isFloatingPoint(SrcVT))
3946 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3947 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003948 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003949 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003950 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00003951 DestVT = TLI.getTypeToExpandTo(SrcVT);
3952 unsigned NumVals = TLI.getNumElements(SrcVT);
3953 if (NumVals == 1)
3954 return DAG.getCopyToReg(getRoot(), Reg,
3955 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3956 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003957 // The src value is expanded into multiple registers.
3958 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003959 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003960 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003961 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003962 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003963 return DAG.getCopyToReg(Op, Reg+1, Hi);
3964 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003965}
3966
Chris Lattner068a81e2005-01-17 17:15:02 +00003967void SelectionDAGISel::
3968LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3969 std::vector<SDOperand> &UnorderedChains) {
3970 // If this is the entry block, emit arguments.
3971 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003972 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003973 SDOperand OldRoot = SDL.DAG.getRoot();
3974 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003975
Chris Lattnerbf209482005-10-30 19:42:35 +00003976 unsigned a = 0;
3977 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3978 AI != E; ++AI, ++a)
3979 if (!AI->use_empty()) {
3980 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003981
Chris Lattnerbf209482005-10-30 19:42:35 +00003982 // If this argument is live outside of the entry block, insert a copy from
3983 // whereever we got it to the vreg that other BB's will reference it as.
3984 if (FuncInfo.ValueMap.count(AI)) {
3985 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003986 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003987 UnorderedChains.push_back(Copy);
3988 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003989 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003990
Chris Lattnerbf209482005-10-30 19:42:35 +00003991 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003992 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003993 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003994}
3995
Chris Lattner1c08c712005-01-07 07:47:53 +00003996void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3997 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003998 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003999 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004000
4001 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004002
Chris Lattnerbf209482005-10-30 19:42:35 +00004003 // Lower any arguments needed in this block if this is the entry block.
4004 if (LLVMBB == &LLVMBB->getParent()->front())
4005 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004006
4007 BB = FuncInfo.MBBMap[LLVMBB];
4008 SDL.setCurrentBasicBlock(BB);
4009
4010 // Lower all of the non-terminator instructions.
4011 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4012 I != E; ++I)
4013 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00004014
Chris Lattner1c08c712005-01-07 07:47:53 +00004015 // Ensure that all instructions which are used outside of their defining
4016 // blocks are available as virtual registers.
4017 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004018 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00004019 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004020 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004021 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004022 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004023 }
4024
4025 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4026 // ensure constants are generated when needed. Remember the virtual registers
4027 // that need to be added to the Machine PHI nodes as input. We cannot just
4028 // directly add them, because expansion might result in multiple MBB's for one
4029 // BB. As such, the start of the BB might correspond to a different MBB than
4030 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004031 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004032 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004033
4034 // Emit constants only once even if used by multiple PHI nodes.
4035 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004036
Chris Lattner8c494ab2006-10-27 23:50:33 +00004037 // Vector bool would be better, but vector<bool> is really slow.
4038 std::vector<unsigned char> SuccsHandled;
4039 if (TI->getNumSuccessors())
4040 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4041
Chris Lattner1c08c712005-01-07 07:47:53 +00004042 // Check successor nodes PHI nodes that expect a constant to be available from
4043 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004044 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4045 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004046 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004047 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004048
Chris Lattner8c494ab2006-10-27 23:50:33 +00004049 // If this terminator has multiple identical successors (common for
4050 // switches), only handle each succ once.
4051 unsigned SuccMBBNo = SuccMBB->getNumber();
4052 if (SuccsHandled[SuccMBBNo]) continue;
4053 SuccsHandled[SuccMBBNo] = true;
4054
4055 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004056 PHINode *PN;
4057
4058 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4059 // nodes and Machine PHI nodes, but the incoming operands have not been
4060 // emitted yet.
4061 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004062 (PN = dyn_cast<PHINode>(I)); ++I) {
4063 // Ignore dead phi's.
4064 if (PN->use_empty()) continue;
4065
4066 unsigned Reg;
4067 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004068
Chris Lattner8c494ab2006-10-27 23:50:33 +00004069 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4070 unsigned &RegOut = ConstantsOut[C];
4071 if (RegOut == 0) {
4072 RegOut = FuncInfo.CreateRegForValue(C);
4073 UnorderedChains.push_back(
4074 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004075 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004076 Reg = RegOut;
4077 } else {
4078 Reg = FuncInfo.ValueMap[PHIOp];
4079 if (Reg == 0) {
4080 assert(isa<AllocaInst>(PHIOp) &&
4081 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4082 "Didn't codegen value into a register!??");
4083 Reg = FuncInfo.CreateRegForValue(PHIOp);
4084 UnorderedChains.push_back(
4085 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004086 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004087 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004088
4089 // Remember that this register needs to added to the machine PHI node as
4090 // the input for this MBB.
4091 MVT::ValueType VT = TLI.getValueType(PN->getType());
4092 unsigned NumElements;
4093 if (VT != MVT::Vector)
4094 NumElements = TLI.getNumElements(VT);
4095 else {
4096 MVT::ValueType VT1,VT2;
4097 NumElements =
4098 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4099 VT1, VT2);
4100 }
4101 for (unsigned i = 0, e = NumElements; i != e; ++i)
4102 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4103 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004104 }
4105 ConstantsOut.clear();
4106
Chris Lattnerddb870b2005-01-13 17:59:43 +00004107 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004108 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004109 SDOperand Root = SDL.getRoot();
4110 if (Root.getOpcode() != ISD::EntryToken) {
4111 unsigned i = 0, e = UnorderedChains.size();
4112 for (; i != e; ++i) {
4113 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4114 if (UnorderedChains[i].Val->getOperand(0) == Root)
4115 break; // Don't add the root if we already indirectly depend on it.
4116 }
4117
4118 if (i == e)
4119 UnorderedChains.push_back(Root);
4120 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004121 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4122 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004123 }
4124
Chris Lattner1c08c712005-01-07 07:47:53 +00004125 // Lower the terminator after the copies are emitted.
4126 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004127
Nate Begemanf15485a2006-03-27 01:32:24 +00004128 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004129 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004130 SwitchCases.clear();
4131 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004132 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004133
Chris Lattnera651cf62005-01-17 19:43:36 +00004134 // Make sure the root of the DAG is up-to-date.
4135 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004136}
4137
Nate Begemanf15485a2006-03-27 01:32:24 +00004138void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004139 // Get alias analysis for load/store combining.
4140 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4141
Chris Lattneraf21d552005-10-10 16:47:10 +00004142 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004143 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004144
Bill Wendling832171c2006-12-07 20:04:42 +00004145 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004146 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004147
Chris Lattner1c08c712005-01-07 07:47:53 +00004148 // Second step, hack on the DAG until it only uses operations and types that
4149 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004150 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004151
Bill Wendling832171c2006-12-07 20:04:42 +00004152 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004153 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004154
Chris Lattneraf21d552005-10-10 16:47:10 +00004155 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004156 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004157
Evan Chenga9c20912006-01-21 02:32:06 +00004158 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004159
Chris Lattnera33ef482005-03-30 01:10:47 +00004160 // Third, instruction select all of the operations to machine code, adding the
4161 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004162 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004163
Bill Wendling832171c2006-12-07 20:04:42 +00004164 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004165 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004166}
Chris Lattner1c08c712005-01-07 07:47:53 +00004167
Nate Begemanf15485a2006-03-27 01:32:24 +00004168void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4169 FunctionLoweringInfo &FuncInfo) {
4170 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4171 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004172 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004173 CurDAG = &DAG;
4174
4175 // First step, lower LLVM code to some DAG. This DAG may use operations and
4176 // types that are not supported by the target.
4177 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4178
4179 // Second step, emit the lowered DAG as machine code.
4180 CodeGenAndEmitDAG(DAG);
4181 }
4182
Chris Lattnera33ef482005-03-30 01:10:47 +00004183 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004184 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004185 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004186 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4187 MachineInstr *PHI = PHINodesToUpdate[i].first;
4188 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4189 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004190 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004191 PHI->addMachineBasicBlockOperand(BB);
4192 }
4193 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004194 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004195
Nate Begeman9453eea2006-04-23 06:26:20 +00004196 // If the JumpTable record is filled in, then we need to emit a jump table.
4197 // Updating the PHI nodes is tricky in this case, since we need to determine
4198 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004199 if (JT.Reg) {
4200 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004201 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004202 CurDAG = &SDAG;
4203 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004204 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004205 // Set the current basic block to the mbb we wish to insert the code into
4206 BB = JT.MBB;
4207 SDL.setCurrentBasicBlock(BB);
4208 // Emit the code
4209 SDL.visitJumpTable(JT);
4210 SDAG.setRoot(SDL.getRoot());
4211 CodeGenAndEmitDAG(SDAG);
4212 // Update PHI Nodes
4213 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4214 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4215 MachineBasicBlock *PHIBB = PHI->getParent();
4216 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4217 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004218 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004219 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004220 PHI->addMachineBasicBlockOperand(RangeBB);
4221 }
4222 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004223 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004224 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004225 }
4226 }
4227 return;
4228 }
4229
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004230 // If the switch block involved a branch to one of the actual successors, we
4231 // need to update PHI nodes in that block.
4232 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4233 MachineInstr *PHI = PHINodesToUpdate[i].first;
4234 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4235 "This is not a machine PHI node that we are updating!");
4236 if (BB->isSuccessor(PHI->getParent())) {
4237 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4238 PHI->addMachineBasicBlockOperand(BB);
4239 }
4240 }
4241
Nate Begemanf15485a2006-03-27 01:32:24 +00004242 // If we generated any switch lowering information, build and codegen any
4243 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004244 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004245 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004246 CurDAG = &SDAG;
4247 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004248
Nate Begemanf15485a2006-03-27 01:32:24 +00004249 // Set the current basic block to the mbb we wish to insert the code into
4250 BB = SwitchCases[i].ThisBB;
4251 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004252
Nate Begemanf15485a2006-03-27 01:32:24 +00004253 // Emit the code
4254 SDL.visitSwitchCase(SwitchCases[i]);
4255 SDAG.setRoot(SDL.getRoot());
4256 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004257
4258 // Handle any PHI nodes in successors of this chunk, as if we were coming
4259 // from the original BB before switch expansion. Note that PHI nodes can
4260 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4261 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004262 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004263 for (MachineBasicBlock::iterator Phi = BB->begin();
4264 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4265 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4266 for (unsigned pn = 0; ; ++pn) {
4267 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4268 if (PHINodesToUpdate[pn].first == Phi) {
4269 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4270 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4271 break;
4272 }
4273 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004274 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004275
4276 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004277 if (BB == SwitchCases[i].FalseBB)
4278 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004279
4280 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004281 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004282 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004283 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004284 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004285 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004286}
Evan Chenga9c20912006-01-21 02:32:06 +00004287
Jim Laskey13ec7022006-08-01 14:21:23 +00004288
Evan Chenga9c20912006-01-21 02:32:06 +00004289//===----------------------------------------------------------------------===//
4290/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4291/// target node in the graph.
4292void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4293 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004294
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004295 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004296
4297 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004298 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004299 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004300 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004301
Jim Laskey9ff542f2006-08-01 18:29:48 +00004302 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004303 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004304 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004305}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004306
Chris Lattner03fc53c2006-03-06 00:22:00 +00004307
Jim Laskey9ff542f2006-08-01 18:29:48 +00004308HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4309 return new HazardRecognizer();
4310}
4311
Chris Lattner75548062006-10-11 03:58:02 +00004312//===----------------------------------------------------------------------===//
4313// Helper functions used by the generated instruction selector.
4314//===----------------------------------------------------------------------===//
4315// Calls to these methods are generated by tblgen.
4316
4317/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4318/// the dag combiner simplified the 255, we still want to match. RHS is the
4319/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4320/// specified in the .td file (e.g. 255).
4321bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4322 int64_t DesiredMaskS) {
4323 uint64_t ActualMask = RHS->getValue();
4324 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4325
4326 // If the actual mask exactly matches, success!
4327 if (ActualMask == DesiredMask)
4328 return true;
4329
4330 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4331 if (ActualMask & ~DesiredMask)
4332 return false;
4333
4334 // Otherwise, the DAG Combiner may have proven that the value coming in is
4335 // either already zero or is not demanded. Check for known zero input bits.
4336 uint64_t NeededMask = DesiredMask & ~ActualMask;
4337 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4338 return true;
4339
4340 // TODO: check to see if missing bits are just not demanded.
4341
4342 // Otherwise, this pattern doesn't match.
4343 return false;
4344}
4345
4346/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4347/// the dag combiner simplified the 255, we still want to match. RHS is the
4348/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4349/// specified in the .td file (e.g. 255).
4350bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4351 int64_t DesiredMaskS) {
4352 uint64_t ActualMask = RHS->getValue();
4353 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4354
4355 // If the actual mask exactly matches, success!
4356 if (ActualMask == DesiredMask)
4357 return true;
4358
4359 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4360 if (ActualMask & ~DesiredMask)
4361 return false;
4362
4363 // Otherwise, the DAG Combiner may have proven that the value coming in is
4364 // either already zero or is not demanded. Check for known zero input bits.
4365 uint64_t NeededMask = DesiredMask & ~ActualMask;
4366
4367 uint64_t KnownZero, KnownOne;
4368 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4369
4370 // If all the missing bits in the or are already known to be set, match!
4371 if ((NeededMask & KnownOne) == NeededMask)
4372 return true;
4373
4374 // TODO: check to see if missing bits are just not demanded.
4375
4376 // Otherwise, this pattern doesn't match.
4377 return false;
4378}
4379
Jim Laskey9ff542f2006-08-01 18:29:48 +00004380
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004381/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4382/// by tblgen. Others should not call it.
4383void SelectionDAGISel::
4384SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4385 std::vector<SDOperand> InOps;
4386 std::swap(InOps, Ops);
4387
4388 Ops.push_back(InOps[0]); // input chain.
4389 Ops.push_back(InOps[1]); // input asm string.
4390
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004391 unsigned i = 2, e = InOps.size();
4392 if (InOps[e-1].getValueType() == MVT::Flag)
4393 --e; // Don't process a flag operand if it is here.
4394
4395 while (i != e) {
4396 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4397 if ((Flags & 7) != 4 /*MEM*/) {
4398 // Just skip over this operand, copying the operands verbatim.
4399 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4400 i += (Flags >> 3) + 1;
4401 } else {
4402 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4403 // Otherwise, this is a memory operand. Ask the target to select it.
4404 std::vector<SDOperand> SelOps;
4405 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004406 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004407 exit(1);
4408 }
4409
4410 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004411 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4412 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004413 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4414 i += 2;
4415 }
4416 }
4417
4418 // Add the flag input back if present.
4419 if (e != InOps.size())
4420 Ops.push_back(InOps.back());
4421}