blob: ae7a495bf48665b2e89c5d54fe3c702b7aa7ae63 [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.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000175
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
Chris Lattner0da331f2007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000358
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
Chris Lattner0da331f2007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 }
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);
Chris Lattner0da331f2007-02-04 01:31:47 +0000596 SDOperand N1 = NodeMap[V];
597 assert(N1.Val && "visit didn't populate the ValueMap!");
598 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000599 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
600 return N = DAG.getGlobalAddress(GV, VT);
601 } else if (isa<ConstantPointerNull>(C)) {
602 return N = DAG.getConstant(0, TLI.getPointerTy());
603 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000604 if (!isa<PackedType>(VTy))
605 return N = DAG.getNode(ISD::UNDEF, VT);
606
Chris Lattnerb2827b02006-03-19 00:52:58 +0000607 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000608 const PackedType *PTy = cast<PackedType>(VTy);
609 unsigned NumElements = PTy->getNumElements();
610 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
611
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000612 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000613 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
614
615 // Create a VConstant node with generic Vector type.
616 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
617 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000618 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
619 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000620 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
621 return N = DAG.getConstantFP(CFP->getValue(), VT);
622 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
623 unsigned NumElements = PTy->getNumElements();
624 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000625
626 // Now that we know the number and type of the elements, push a
627 // Constant or ConstantFP node onto the ops list for each element of
628 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000629 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000630 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000631 for (unsigned i = 0; i != NumElements; ++i)
632 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000633 } else {
634 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
635 SDOperand Op;
636 if (MVT::isFloatingPoint(PVT))
637 Op = DAG.getConstantFP(0, PVT);
638 else
639 Op = DAG.getConstant(0, PVT);
640 Ops.assign(NumElements, Op);
641 }
642
Chris Lattnerb2827b02006-03-19 00:52:58 +0000643 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000644 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
645 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000646 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
647 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000648 } else {
649 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000650 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000651 }
652 }
653
654 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
655 std::map<const AllocaInst*, int>::iterator SI =
656 FuncInfo.StaticAllocaMap.find(AI);
657 if (SI != FuncInfo.StaticAllocaMap.end())
658 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
659 }
660
Chris Lattner9f24ad72007-02-04 01:35:11 +0000661 DenseMap<const Value*, unsigned>::iterator VMI =
Chris Lattner199862b2006-03-16 19:57:50 +0000662 FuncInfo.ValueMap.find(V);
663 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
664
665 unsigned InReg = VMI->second;
666
667 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000668 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000669 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000670 // Source must be expanded. This input value is actually coming from the
671 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000672 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
673 unsigned NumVals = TLI.getNumElements(VT);
674 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
675 if (NumVals == 1)
676 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
677 else {
678 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
679 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
680 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
681 }
682 } else {
683 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
684 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
685 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
686 N = MVT::isFloatingPoint(VT)
687 ? DAG.getNode(ISD::FP_ROUND, VT, N)
688 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000689 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000690 } else {
691 // Otherwise, if this is a vector, make it available as a generic vector
692 // here.
693 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000694 const PackedType *PTy = cast<PackedType>(VTy);
695 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000696 PTyLegalElementVT);
697
698 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000699 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000700 if (PTyElementVT == PTyLegalElementVT) {
701 // If the value types are legal, just VBUILD the CopyFromReg nodes.
702 for (unsigned i = 0; i != NE; ++i)
703 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
704 PTyElementVT));
705 } else if (PTyElementVT < PTyLegalElementVT) {
706 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
707 for (unsigned i = 0; i != NE; ++i) {
708 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT);
710 if (MVT::isFloatingPoint(PTyElementVT))
711 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
712 else
713 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
714 Ops.push_back(Op);
715 }
716 } else {
717 // If the register was expanded, use BUILD_PAIR.
718 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
719 for (unsigned i = 0; i != NE/2; ++i) {
720 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
721 PTyElementVT);
722 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
723 PTyElementVT);
724 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
725 }
726 }
727
728 Ops.push_back(DAG.getConstant(NE, MVT::i32));
729 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000730 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000731
732 // Finally, use a VBIT_CONVERT to make this available as the appropriate
733 // vector type.
734 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
735 DAG.getConstant(PTy->getNumElements(),
736 MVT::i32),
737 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000738 }
739
740 return N;
741}
742
743
Chris Lattner1c08c712005-01-07 07:47:53 +0000744void SelectionDAGLowering::visitRet(ReturnInst &I) {
745 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000746 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000747 return;
748 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000749 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000750 NewValues.push_back(getRoot());
751 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
752 SDOperand RetOp = getValue(I.getOperand(i));
753
754 // If this is an integer return value, we need to promote it ourselves to
755 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
756 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000757 // FIXME: C calling convention requires the return type to be promoted to
758 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000759 if (MVT::isInteger(RetOp.getValueType()) &&
760 RetOp.getValueType() < MVT::i64) {
761 MVT::ValueType TmpVT;
762 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
763 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
764 else
765 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000766 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000767 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000768 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
769 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000770 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
771 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000772 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000773 }
774 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000775 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000776 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000777 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
778 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000779}
780
Chris Lattner571e4342006-10-27 21:36:01 +0000781/// ExportFromCurrentBlock - If this condition isn't known to be exported from
782/// the current basic block, add it to ValueMap now so that we'll get a
783/// CopyTo/FromReg.
784void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
785 // No need to export constants.
786 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
787
788 // Already exported?
789 if (FuncInfo.isExportedInst(V)) return;
790
791 unsigned Reg = FuncInfo.InitializeRegForValue(V);
792 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
793}
794
Chris Lattner8c494ab2006-10-27 23:50:33 +0000795bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
796 const BasicBlock *FromBB) {
797 // The operands of the setcc have to be in this block. We don't know
798 // how to export them from some other block.
799 if (Instruction *VI = dyn_cast<Instruction>(V)) {
800 // Can export from current BB.
801 if (VI->getParent() == FromBB)
802 return true;
803
804 // Is already exported, noop.
805 return FuncInfo.isExportedInst(V);
806 }
807
808 // If this is an argument, we can export it if the BB is the entry block or
809 // if it is already exported.
810 if (isa<Argument>(V)) {
811 if (FromBB == &FromBB->getParent()->getEntryBlock())
812 return true;
813
814 // Otherwise, can only export this if it is already exported.
815 return FuncInfo.isExportedInst(V);
816 }
817
818 // Otherwise, constants can always be exported.
819 return true;
820}
821
Chris Lattner6a586c82006-10-29 21:01:20 +0000822static bool InBlock(const Value *V, const BasicBlock *BB) {
823 if (const Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() == BB;
825 return true;
826}
827
Chris Lattner571e4342006-10-27 21:36:01 +0000828/// FindMergedConditions - If Cond is an expression like
829void SelectionDAGLowering::FindMergedConditions(Value *Cond,
830 MachineBasicBlock *TBB,
831 MachineBasicBlock *FBB,
832 MachineBasicBlock *CurBB,
833 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000834 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000835 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000836
Reid Spencere4d87aa2006-12-23 06:05:41 +0000837 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
838 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000839 BOp->getParent() != CurBB->getBasicBlock() ||
840 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
841 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000842 const BasicBlock *BB = CurBB->getBasicBlock();
843
Reid Spencere4d87aa2006-12-23 06:05:41 +0000844 // If the leaf of the tree is a comparison, merge the condition into
845 // the caseblock.
846 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
847 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000848 // how to export them from some other block. If this is the first block
849 // of the sequence, no exporting is needed.
850 (CurBB == CurMBB ||
851 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
852 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000853 BOp = cast<Instruction>(Cond);
854 ISD::CondCode Condition;
855 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
856 switch (IC->getPredicate()) {
857 default: assert(0 && "Unknown icmp predicate opcode!");
858 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
859 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
860 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
861 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
862 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
863 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
864 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
865 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
866 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
867 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
868 }
869 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
870 ISD::CondCode FPC, FOC;
871 switch (FC->getPredicate()) {
872 default: assert(0 && "Unknown fcmp predicate opcode!");
873 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
874 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
875 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
876 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
877 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
878 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
879 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
880 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
881 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
882 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
883 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
884 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
885 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
886 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
887 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
888 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
889 }
890 if (FiniteOnlyFPMath())
891 Condition = FOC;
892 else
893 Condition = FPC;
894 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000895 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000896 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000897 }
898
Chris Lattner571e4342006-10-27 21:36:01 +0000899 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
900 BOp->getOperand(1), TBB, FBB, CurBB);
901 SwitchCases.push_back(CB);
902 return;
903 }
904
905 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000906 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000907 TBB, FBB, CurBB);
908 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000909 return;
910 }
911
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000912
913 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000914 MachineFunction::iterator BBI = CurBB;
915 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
916 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
917
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000918 if (Opc == Instruction::Or) {
919 // Codegen X | Y as:
920 // jmp_if_X TBB
921 // jmp TmpBB
922 // TmpBB:
923 // jmp_if_Y TBB
924 // jmp FBB
925 //
Chris Lattner571e4342006-10-27 21:36:01 +0000926
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000927 // Emit the LHS condition.
928 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
929
930 // Emit the RHS condition into TmpBB.
931 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
932 } else {
933 assert(Opc == Instruction::And && "Unknown merge op!");
934 // Codegen X & Y as:
935 // jmp_if_X TmpBB
936 // jmp FBB
937 // TmpBB:
938 // jmp_if_Y TBB
939 // jmp FBB
940 //
941 // This requires creation of TmpBB after CurBB.
942
943 // Emit the LHS condition.
944 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
945
946 // Emit the RHS condition into TmpBB.
947 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
948 }
Chris Lattner571e4342006-10-27 21:36:01 +0000949}
950
Chris Lattnerdf19f272006-10-31 22:37:42 +0000951/// If the set of cases should be emitted as a series of branches, return true.
952/// If we should emit this as a bunch of and/or'd together conditions, return
953/// false.
954static bool
955ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
956 if (Cases.size() != 2) return true;
957
Chris Lattner0ccb5002006-10-31 23:06:00 +0000958 // If this is two comparisons of the same values or'd or and'd together, they
959 // will get folded into a single comparison, so don't emit two blocks.
960 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
961 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
962 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
963 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
964 return false;
965 }
966
Chris Lattnerdf19f272006-10-31 22:37:42 +0000967 return true;
968}
969
Chris Lattner1c08c712005-01-07 07:47:53 +0000970void SelectionDAGLowering::visitBr(BranchInst &I) {
971 // Update machine-CFG edges.
972 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000973
974 // Figure out which block is immediately after the current one.
975 MachineBasicBlock *NextBlock = 0;
976 MachineFunction::iterator BBI = CurMBB;
977 if (++BBI != CurMBB->getParent()->end())
978 NextBlock = BBI;
979
980 if (I.isUnconditional()) {
981 // If this is not a fall-through branch, emit the branch.
982 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000983 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000984 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000985
Chris Lattner57ab6592006-10-24 17:57:59 +0000986 // Update machine-CFG edges.
987 CurMBB->addSuccessor(Succ0MBB);
988
989 return;
990 }
991
992 // If this condition is one of the special cases we handle, do special stuff
993 // now.
994 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000995 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000996
997 // If this is a series of conditions that are or'd or and'd together, emit
998 // this as a sequence of branches instead of setcc's with and/or operations.
999 // For example, instead of something like:
1000 // cmp A, B
1001 // C = seteq
1002 // cmp D, E
1003 // F = setle
1004 // or C, F
1005 // jnz foo
1006 // Emit:
1007 // cmp A, B
1008 // je foo
1009 // cmp D, E
1010 // jle foo
1011 //
1012 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1013 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001014 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001015 BOp->getOpcode() == Instruction::Or)) {
1016 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001017 // If the compares in later blocks need to use values not currently
1018 // exported from this block, export them now. This block should always
1019 // be the first entry.
1020 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1021
Chris Lattnerdf19f272006-10-31 22:37:42 +00001022 // Allow some cases to be rejected.
1023 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001024 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1025 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1026 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1027 }
1028
1029 // Emit the branch for this block.
1030 visitSwitchCase(SwitchCases[0]);
1031 SwitchCases.erase(SwitchCases.begin());
1032 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001033 }
1034
Chris Lattner0ccb5002006-10-31 23:06:00 +00001035 // Okay, we decided not to do this, remove any inserted MBB's and clear
1036 // SwitchCases.
1037 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1038 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1039
Chris Lattnerdf19f272006-10-31 22:37:42 +00001040 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001041 }
1042 }
Chris Lattner24525952006-10-24 18:07:37 +00001043
1044 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001045 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001046 Succ0MBB, Succ1MBB, CurMBB);
1047 // Use visitSwitchCase to actually insert the fast branch sequence for this
1048 // cond branch.
1049 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001050}
1051
Nate Begemanf15485a2006-03-27 01:32:24 +00001052/// visitSwitchCase - Emits the necessary code to represent a single node in
1053/// the binary search tree resulting from lowering a switch instruction.
1054void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001055 SDOperand Cond;
1056 SDOperand CondLHS = getValue(CB.CmpLHS);
1057
Chris Lattner571e4342006-10-27 21:36:01 +00001058 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1059 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001060 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001061 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001062 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001063 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1064 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1065 } else
1066 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001067
1068 // Set NextBlock to be the MBB immediately after the current one, if any.
1069 // This is used to avoid emitting unnecessary branches to the next block.
1070 MachineBasicBlock *NextBlock = 0;
1071 MachineFunction::iterator BBI = CurMBB;
1072 if (++BBI != CurMBB->getParent()->end())
1073 NextBlock = BBI;
1074
1075 // If the lhs block is the next block, invert the condition so that we can
1076 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001077 if (CB.TrueBB == NextBlock) {
1078 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001079 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1080 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1081 }
1082 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001083 DAG.getBasicBlock(CB.TrueBB));
1084 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001085 DAG.setRoot(BrCond);
1086 else
1087 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001088 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001089 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001090 CurMBB->addSuccessor(CB.TrueBB);
1091 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001092}
1093
Nate Begeman37efe672006-04-22 18:53:45 +00001094void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001095 // Emit the code for the jump table
1096 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001097 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1098 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1099 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1100 Table, Index));
1101 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001102}
1103
Nate Begemanf15485a2006-03-27 01:32:24 +00001104void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1105 // Figure out which block is immediately after the current one.
1106 MachineBasicBlock *NextBlock = 0;
1107 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001108
Nate Begemanf15485a2006-03-27 01:32:24 +00001109 if (++BBI != CurMBB->getParent()->end())
1110 NextBlock = BBI;
1111
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001112 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1113
Nate Begemanf15485a2006-03-27 01:32:24 +00001114 // If there is only the default destination, branch to it if it is not the
1115 // next basic block. Otherwise, just fall through.
1116 if (I.getNumOperands() == 2) {
1117 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001118
Nate Begemanf15485a2006-03-27 01:32:24 +00001119 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001120 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001121 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001122 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001123
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001124 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001125 return;
1126 }
1127
1128 // If there are any non-default case statements, create a vector of Cases
1129 // representing each one, and sort the vector so that we can efficiently
1130 // create a binary search tree from them.
1131 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001132
Nate Begemanf15485a2006-03-27 01:32:24 +00001133 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1134 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1135 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1136 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001137
Nate Begemanf15485a2006-03-27 01:32:24 +00001138 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1139
1140 // Get the Value to be switched on and default basic blocks, which will be
1141 // inserted into CaseBlock records, representing basic blocks in the binary
1142 // search tree.
1143 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001144
1145 // Get the MachineFunction which holds the current MBB. This is used during
1146 // emission of jump tables, and when inserting any additional MBBs necessary
1147 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001148 MachineFunction *CurMF = CurMBB->getParent();
1149 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001150
1151 // If the switch has few cases (two or less) emit a series of specific
1152 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001153 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001154 // TODO: If any two of the cases has the same destination, and if one value
1155 // is the same as the other, but has one bit unset that the other has set,
1156 // use bit manipulation to do two compares at once. For example:
1157 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1158
Chris Lattnerb3543432006-10-23 18:38:22 +00001159 // Rearrange the case blocks so that the last one falls through if possible.
1160 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1161 // The last case block won't fall through into 'NextBlock' if we emit the
1162 // branches in this order. See if rearranging a case value would help.
1163 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1164 if (Cases[i].second == NextBlock) {
1165 std::swap(Cases[i], Cases.back());
1166 break;
1167 }
1168 }
1169 }
1170
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001171 // Create a CaseBlock record representing a conditional branch to
1172 // the Case's target mbb if the value being switched on SV is equal
1173 // to C.
1174 MachineBasicBlock *CurBlock = CurMBB;
1175 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1176 MachineBasicBlock *FallThrough;
1177 if (i != e-1) {
1178 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1179 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1180 } else {
1181 // If the last case doesn't match, go to the default block.
1182 FallThrough = Default;
1183 }
1184
1185 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1186 Cases[i].second, FallThrough, CurBlock);
1187
1188 // If emitting the first comparison, just call visitSwitchCase to emit the
1189 // code into the current block. Otherwise, push the CaseBlock onto the
1190 // vector to be later processed by SDISel, and insert the node's MBB
1191 // before the next MBB.
1192 if (CurBlock == CurMBB)
1193 visitSwitchCase(CB);
1194 else
1195 SwitchCases.push_back(CB);
1196
1197 CurBlock = FallThrough;
1198 }
1199 return;
1200 }
Nate Begeman37efe672006-04-22 18:53:45 +00001201
Nate Begeman17c275f2006-05-08 16:51:36 +00001202 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1203 // target supports indirect branches, then emit a jump table rather than
1204 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001205 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1206 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001207 Cases.size() > 5) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001208 uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1209 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001210 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1211
Nate Begeman17c275f2006-05-08 16:51:36 +00001212 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001213 // Create a new basic block to hold the code for loading the address
1214 // of the jump table, and jumping to it. Update successor information;
1215 // we will either branch to the default case for the switch, or the jump
1216 // table.
1217 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1218 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1219 CurMBB->addSuccessor(Default);
1220 CurMBB->addSuccessor(JumpTableBB);
1221
1222 // Subtract the lowest switch case value from the value being switched on
1223 // and conditional branch to default mbb if the result is greater than the
1224 // difference between smallest and largest cases.
1225 SDOperand SwitchOp = getValue(SV);
1226 MVT::ValueType VT = SwitchOp.getValueType();
1227 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1228 DAG.getConstant(First, VT));
1229
1230 // The SDNode we just created, which holds the value being switched on
1231 // minus the the smallest case value, needs to be copied to a virtual
1232 // register so it can be used as an index into the jump table in a
1233 // subsequent basic block. This value may be smaller or larger than the
1234 // target's pointer type, and therefore require extension or truncating.
1235 if (VT > TLI.getPointerTy())
1236 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1237 else
1238 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001239
Nate Begeman37efe672006-04-22 18:53:45 +00001240 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1241 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1242
1243 // Emit the range check for the jump table, and branch to the default
1244 // block for the switch statement if the value being switched on exceeds
1245 // the largest case in the switch.
1246 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1247 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1248 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1249 DAG.getBasicBlock(Default)));
1250
Nate Begemanf4360a42006-05-03 03:48:02 +00001251 // Build a vector of destination BBs, corresponding to each target
1252 // of the jump table. If the value of the jump table slot corresponds to
1253 // a case statement, push the case's BB onto the vector, otherwise, push
1254 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001255 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001256 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001257 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001258 if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001259 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001260 ++ii;
1261 } else {
1262 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001263 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001264
Chris Lattner8c494ab2006-10-27 23:50:33 +00001265 // Update successor info. Add one edge to each unique successor.
1266 // Vector bool would be better, but vector<bool> is really slow.
1267 std::vector<unsigned char> SuccsHandled;
1268 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1269
Chris Lattnerc66764c2006-09-10 06:36:57 +00001270 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001271 E = DestBBs.end(); I != E; ++I) {
1272 if (!SuccsHandled[(*I)->getNumber()]) {
1273 SuccsHandled[(*I)->getNumber()] = true;
1274 JumpTableBB->addSuccessor(*I);
1275 }
1276 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001277
1278 // Create a jump table index for this jump table, or return an existing
1279 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001280 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1281
1282 // Set the jump table information so that we can codegen it as a second
1283 // MachineBasicBlock
1284 JT.Reg = JumpTableReg;
1285 JT.JTI = JTI;
1286 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001287 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001288 return;
1289 }
1290 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001291
1292 // Push the initial CaseRec onto the worklist
1293 std::vector<CaseRec> CaseVec;
1294 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1295
1296 while (!CaseVec.empty()) {
1297 // Grab a record representing a case range to process off the worklist
1298 CaseRec CR = CaseVec.back();
1299 CaseVec.pop_back();
1300
1301 // Size is the number of Cases represented by this range. If Size is 1,
1302 // then we are processing a leaf of the binary search tree. Otherwise,
1303 // we need to pick a pivot, and push left and right ranges onto the
1304 // worklist.
1305 unsigned Size = CR.Range.second - CR.Range.first;
1306
1307 if (Size == 1) {
1308 // Create a CaseBlock record representing a conditional branch to
1309 // the Case's target mbb if the value being switched on SV is equal
1310 // to C. Otherwise, branch to default.
1311 Constant *C = CR.Range.first->first;
1312 MachineBasicBlock *Target = CR.Range.first->second;
1313 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1314 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001315
Nate Begemanf15485a2006-03-27 01:32:24 +00001316 // If the MBB representing the leaf node is the current MBB, then just
1317 // call visitSwitchCase to emit the code into the current block.
1318 // Otherwise, push the CaseBlock onto the vector to be later processed
1319 // by SDISel, and insert the node's MBB before the next MBB.
1320 if (CR.CaseBB == CurMBB)
1321 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001322 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001323 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001324 } else {
1325 // split case range at pivot
1326 CaseItr Pivot = CR.Range.first + (Size / 2);
1327 CaseRange LHSR(CR.Range.first, Pivot);
1328 CaseRange RHSR(Pivot, CR.Range.second);
1329 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001330 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001331
Nate Begemanf15485a2006-03-27 01:32:24 +00001332 // We know that we branch to the LHS if the Value being switched on is
1333 // less than the Pivot value, C. We use this to optimize our binary
1334 // tree a bit, by recognizing that if SV is greater than or equal to the
1335 // LHS's Case Value, and that Case Value is exactly one less than the
1336 // Pivot's Value, then we can branch directly to the LHS's Target,
1337 // rather than creating a leaf node for it.
1338 if ((LHSR.second - LHSR.first) == 1 &&
1339 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001340 cast<ConstantInt>(C)->getZExtValue() ==
1341 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001342 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001343 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001344 TrueBB = new MachineBasicBlock(LLVMBB);
1345 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1346 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001347 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001348
Nate Begemanf15485a2006-03-27 01:32:24 +00001349 // Similar to the optimization above, if the Value being switched on is
1350 // known to be less than the Constant CR.LT, and the current Case Value
1351 // is CR.LT - 1, then we can branch directly to the target block for
1352 // the current Case Value, rather than emitting a RHS leaf node for it.
1353 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001354 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1355 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001356 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001357 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001358 FalseBB = new MachineBasicBlock(LLVMBB);
1359 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1360 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001361 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001362
Nate Begemanf15485a2006-03-27 01:32:24 +00001363 // Create a CaseBlock record representing a conditional branch to
1364 // the LHS node if the value being switched on SV is less than C.
1365 // Otherwise, branch to LHS.
Reid Spencer8c57dfb2007-01-03 04:25:33 +00001366 ISD::CondCode CC = ISD::SETLT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001367 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001368
Nate Begemanf15485a2006-03-27 01:32:24 +00001369 if (CR.CaseBB == CurMBB)
1370 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001371 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001372 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001373 }
1374 }
1375}
1376
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001377void SelectionDAGLowering::visitSub(User &I) {
1378 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001379 const Type *Ty = I.getType();
1380 if (isa<PackedType>(Ty)) {
1381 visitVectorBinary(I, ISD::VSUB);
1382 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001383 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1384 if (CFP->isExactlyValue(-0.0)) {
1385 SDOperand Op2 = getValue(I.getOperand(1));
1386 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1387 return;
1388 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001389 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001390 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001391 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001392}
1393
Reid Spencer24d6da52007-01-21 00:29:26 +00001394void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001395 SDOperand Op1 = getValue(I.getOperand(0));
1396 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001397
1398 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001399}
1400
Reid Spencer24d6da52007-01-21 00:29:26 +00001401void
1402SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1403 assert(isa<PackedType>(I.getType()));
1404 const PackedType *Ty = cast<PackedType>(I.getType());
1405 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001406
Reid Spencer24d6da52007-01-21 00:29:26 +00001407 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1408 getValue(I.getOperand(0)),
1409 getValue(I.getOperand(1)),
1410 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1411 Typ));
1412}
1413
1414void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1415 unsigned VectorOp) {
1416 if (isa<PackedType>(I.getType()))
1417 visitVectorBinary(I, VectorOp);
1418 else
1419 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001420}
Chris Lattner2c49f272005-01-19 22:31:21 +00001421
Nate Begemane21ea612005-11-18 07:42:56 +00001422void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1423 SDOperand Op1 = getValue(I.getOperand(0));
1424 SDOperand Op2 = getValue(I.getOperand(1));
1425
Reid Spencer832254e2007-02-02 02:16:23 +00001426 if (TLI.getShiftAmountTy() < Op2.getValueType())
1427 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1428 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1429 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001430
Chris Lattner1c08c712005-01-07 07:47:53 +00001431 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1432}
1433
Reid Spencer45fb3f32006-11-20 01:22:35 +00001434void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001435 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1436 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1437 predicate = IC->getPredicate();
1438 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1439 predicate = ICmpInst::Predicate(IC->getPredicate());
1440 SDOperand Op1 = getValue(I.getOperand(0));
1441 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001442 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001443 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001444 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1445 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1446 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1447 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1448 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1449 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1450 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1451 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1452 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1453 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1454 default:
1455 assert(!"Invalid ICmp predicate value");
1456 Opcode = ISD::SETEQ;
1457 break;
1458 }
1459 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1460}
1461
1462void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001463 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1464 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1465 predicate = FC->getPredicate();
1466 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1467 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001468 SDOperand Op1 = getValue(I.getOperand(0));
1469 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001470 ISD::CondCode Condition, FOC, FPC;
1471 switch (predicate) {
1472 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1473 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1474 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1475 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1476 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1477 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1478 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1479 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1480 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1481 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1482 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1483 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1484 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1485 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1486 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1487 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1488 default:
1489 assert(!"Invalid FCmp predicate value");
1490 FOC = FPC = ISD::SETFALSE;
1491 break;
1492 }
1493 if (FiniteOnlyFPMath())
1494 Condition = FOC;
1495 else
1496 Condition = FPC;
1497 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001498}
1499
1500void SelectionDAGLowering::visitSelect(User &I) {
1501 SDOperand Cond = getValue(I.getOperand(0));
1502 SDOperand TrueVal = getValue(I.getOperand(1));
1503 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001504 if (!isa<PackedType>(I.getType())) {
1505 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1506 TrueVal, FalseVal));
1507 } else {
1508 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1509 *(TrueVal.Val->op_end()-2),
1510 *(TrueVal.Val->op_end()-1)));
1511 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001512}
1513
Reid Spencer3da59db2006-11-27 01:05:10 +00001514
1515void SelectionDAGLowering::visitTrunc(User &I) {
1516 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1517 SDOperand N = getValue(I.getOperand(0));
1518 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1519 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1520}
1521
1522void SelectionDAGLowering::visitZExt(User &I) {
1523 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1524 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1525 SDOperand N = getValue(I.getOperand(0));
1526 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1527 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1528}
1529
1530void SelectionDAGLowering::visitSExt(User &I) {
1531 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1532 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1533 SDOperand N = getValue(I.getOperand(0));
1534 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1535 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1536}
1537
1538void SelectionDAGLowering::visitFPTrunc(User &I) {
1539 // FPTrunc is never a no-op cast, no need to check
1540 SDOperand N = getValue(I.getOperand(0));
1541 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1542 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1543}
1544
1545void SelectionDAGLowering::visitFPExt(User &I){
1546 // FPTrunc is never a no-op cast, no need to check
1547 SDOperand N = getValue(I.getOperand(0));
1548 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1549 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1550}
1551
1552void SelectionDAGLowering::visitFPToUI(User &I) {
1553 // FPToUI is never a no-op cast, no need to check
1554 SDOperand N = getValue(I.getOperand(0));
1555 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1556 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1557}
1558
1559void SelectionDAGLowering::visitFPToSI(User &I) {
1560 // FPToSI is never a no-op cast, no need to check
1561 SDOperand N = getValue(I.getOperand(0));
1562 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1563 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1564}
1565
1566void SelectionDAGLowering::visitUIToFP(User &I) {
1567 // UIToFP is never a no-op cast, no need to check
1568 SDOperand N = getValue(I.getOperand(0));
1569 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1570 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1571}
1572
1573void SelectionDAGLowering::visitSIToFP(User &I){
1574 // UIToFP is never a no-op cast, no need to check
1575 SDOperand N = getValue(I.getOperand(0));
1576 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1577 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1578}
1579
1580void SelectionDAGLowering::visitPtrToInt(User &I) {
1581 // What to do depends on the size of the integer and the size of the pointer.
1582 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001583 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001584 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001585 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001586 SDOperand Result;
1587 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1588 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1589 else
1590 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1591 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1592 setValue(&I, Result);
1593}
Chris Lattner1c08c712005-01-07 07:47:53 +00001594
Reid Spencer3da59db2006-11-27 01:05:10 +00001595void SelectionDAGLowering::visitIntToPtr(User &I) {
1596 // What to do depends on the size of the integer and the size of the pointer.
1597 // We can either truncate, zero extend, or no-op, accordingly.
1598 SDOperand N = getValue(I.getOperand(0));
1599 MVT::ValueType SrcVT = N.getValueType();
1600 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1601 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1602 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1603 else
1604 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1605 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1606}
1607
1608void SelectionDAGLowering::visitBitCast(User &I) {
1609 SDOperand N = getValue(I.getOperand(0));
1610 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001611 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001612 // This is a cast to a vector from something else.
1613 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001614 const PackedType *DestTy = cast<PackedType>(I.getType());
1615 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1616 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1617 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1618 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001619 return;
1620 }
1621 MVT::ValueType SrcVT = N.getValueType();
1622 if (SrcVT == MVT::Vector) {
1623 // This is a cast from a vctor to something else.
1624 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001625 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001626 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001627 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001628
1629 // BitCast assures us that source and destination are the same size so this
1630 // is either a BIT_CONVERT or a no-op.
1631 if (DestVT != N.getValueType())
1632 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1633 else
1634 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001635}
1636
Chris Lattner2bbd8102006-03-29 00:11:43 +00001637void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001638 SDOperand InVec = getValue(I.getOperand(0));
1639 SDOperand InVal = getValue(I.getOperand(1));
1640 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1641 getValue(I.getOperand(2)));
1642
Chris Lattner2332b9f2006-03-19 01:17:20 +00001643 SDOperand Num = *(InVec.Val->op_end()-2);
1644 SDOperand Typ = *(InVec.Val->op_end()-1);
1645 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1646 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001647}
1648
Chris Lattner2bbd8102006-03-29 00:11:43 +00001649void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001650 SDOperand InVec = getValue(I.getOperand(0));
1651 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1652 getValue(I.getOperand(1)));
1653 SDOperand Typ = *(InVec.Val->op_end()-1);
1654 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1655 TLI.getValueType(I.getType()), InVec, InIdx));
1656}
Chris Lattnerc7029802006-03-18 01:44:44 +00001657
Chris Lattner3e104b12006-04-08 04:15:24 +00001658void SelectionDAGLowering::visitShuffleVector(User &I) {
1659 SDOperand V1 = getValue(I.getOperand(0));
1660 SDOperand V2 = getValue(I.getOperand(1));
1661 SDOperand Mask = getValue(I.getOperand(2));
1662
1663 SDOperand Num = *(V1.Val->op_end()-2);
1664 SDOperand Typ = *(V2.Val->op_end()-1);
1665 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1666 V1, V2, Mask, Num, Typ));
1667}
1668
1669
Chris Lattner1c08c712005-01-07 07:47:53 +00001670void SelectionDAGLowering::visitGetElementPtr(User &I) {
1671 SDOperand N = getValue(I.getOperand(0));
1672 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001673
1674 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1675 OI != E; ++OI) {
1676 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001677 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001678 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001679 if (Field) {
1680 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001681 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001682 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001683 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001684 }
1685 Ty = StTy->getElementType(Field);
1686 } else {
1687 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001688
Chris Lattner7c0104b2005-11-09 04:45:33 +00001689 // If this is a constant subscript, handle it quickly.
1690 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001691 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001692 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001693 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001694 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1695 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001696 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001697
1698 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001699 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001700 SDOperand IdxN = getValue(Idx);
1701
1702 // If the index is smaller or larger than intptr_t, truncate or extend
1703 // it.
1704 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001705 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001706 } else if (IdxN.getValueType() > N.getValueType())
1707 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1708
1709 // If this is a multiply by a power of two, turn it into a shl
1710 // immediately. This is a very common case.
1711 if (isPowerOf2_64(ElementSize)) {
1712 unsigned Amt = Log2_64(ElementSize);
1713 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001714 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001715 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1716 continue;
1717 }
1718
1719 SDOperand Scale = getIntPtrConstant(ElementSize);
1720 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1721 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001722 }
1723 }
1724 setValue(&I, N);
1725}
1726
1727void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1728 // If this is a fixed sized alloca in the entry block of the function,
1729 // allocate it statically on the stack.
1730 if (FuncInfo.StaticAllocaMap.count(&I))
1731 return; // getValue will auto-populate this.
1732
1733 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001734 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001735 unsigned Align =
1736 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1737 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001738
1739 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001740 MVT::ValueType IntPtr = TLI.getPointerTy();
1741 if (IntPtr < AllocSize.getValueType())
1742 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1743 else if (IntPtr > AllocSize.getValueType())
1744 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001745
Chris Lattner68cd65e2005-01-22 23:04:37 +00001746 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001747 getIntPtrConstant(TySize));
1748
1749 // Handle alignment. If the requested alignment is less than or equal to the
1750 // stack alignment, ignore it and round the size of the allocation up to the
1751 // stack alignment size. If the size is greater than the stack alignment, we
1752 // note this in the DYNAMIC_STACKALLOC node.
1753 unsigned StackAlign =
1754 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1755 if (Align <= StackAlign) {
1756 Align = 0;
1757 // Add SA-1 to the size.
1758 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1759 getIntPtrConstant(StackAlign-1));
1760 // Mask out the low bits for alignment purposes.
1761 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1762 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1763 }
1764
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001765 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001766 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1767 MVT::Other);
1768 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00001769 setValue(&I, DSA);
1770 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001771
1772 // Inform the Frame Information that we have just allocated a variable-sized
1773 // object.
1774 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1775}
1776
Chris Lattner1c08c712005-01-07 07:47:53 +00001777void SelectionDAGLowering::visitLoad(LoadInst &I) {
1778 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001779
Chris Lattnerd3948112005-01-17 22:19:26 +00001780 SDOperand Root;
1781 if (I.isVolatile())
1782 Root = getRoot();
1783 else {
1784 // Do not serialize non-volatile loads against each other.
1785 Root = DAG.getRoot();
1786 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001787
Evan Cheng466685d2006-10-09 20:57:25 +00001788 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001789 Root, I.isVolatile()));
1790}
1791
1792SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001793 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001794 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001795 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001796 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001797 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001798 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1799 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001800 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001801 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001802 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001803
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001804 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001805 DAG.setRoot(L.getValue(1));
1806 else
1807 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001808
1809 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001810}
1811
1812
1813void SelectionDAGLowering::visitStore(StoreInst &I) {
1814 Value *SrcV = I.getOperand(0);
1815 SDOperand Src = getValue(SrcV);
1816 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001817 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001818 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001819}
1820
Chris Lattner0eade312006-03-24 02:22:33 +00001821/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1822/// access memory and has no other side effects at all.
1823static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1824#define GET_NO_MEMORY_INTRINSICS
1825#include "llvm/Intrinsics.gen"
1826#undef GET_NO_MEMORY_INTRINSICS
1827 return false;
1828}
1829
Chris Lattnere58a7802006-04-02 03:41:14 +00001830// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1831// have any side-effects or if it only reads memory.
1832static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1833#define GET_SIDE_EFFECT_INFO
1834#include "llvm/Intrinsics.gen"
1835#undef GET_SIDE_EFFECT_INFO
1836 return false;
1837}
1838
Chris Lattner0eade312006-03-24 02:22:33 +00001839/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1840/// node.
1841void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1842 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001843 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001844 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001845
1846 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001847 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001848 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1849 if (OnlyLoad) {
1850 // We don't need to serialize loads against other loads.
1851 Ops.push_back(DAG.getRoot());
1852 } else {
1853 Ops.push_back(getRoot());
1854 }
1855 }
Chris Lattner0eade312006-03-24 02:22:33 +00001856
1857 // Add the intrinsic ID as an integer operand.
1858 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1859
1860 // Add all operands of the call to the operand list.
1861 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1862 SDOperand Op = getValue(I.getOperand(i));
1863
1864 // If this is a vector type, force it to the right packed type.
1865 if (Op.getValueType() == MVT::Vector) {
1866 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1867 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1868
1869 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1870 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1871 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1872 }
1873
1874 assert(TLI.isTypeLegal(Op.getValueType()) &&
1875 "Intrinsic uses a non-legal type?");
1876 Ops.push_back(Op);
1877 }
1878
1879 std::vector<MVT::ValueType> VTs;
1880 if (I.getType() != Type::VoidTy) {
1881 MVT::ValueType VT = TLI.getValueType(I.getType());
1882 if (VT == MVT::Vector) {
1883 const PackedType *DestTy = cast<PackedType>(I.getType());
1884 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1885
1886 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1887 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1888 }
1889
1890 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1891 VTs.push_back(VT);
1892 }
1893 if (HasChain)
1894 VTs.push_back(MVT::Other);
1895
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001896 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1897
Chris Lattner0eade312006-03-24 02:22:33 +00001898 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001899 SDOperand Result;
1900 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001901 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1902 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001903 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001904 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1905 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001906 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001907 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1908 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001909
Chris Lattnere58a7802006-04-02 03:41:14 +00001910 if (HasChain) {
1911 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1912 if (OnlyLoad)
1913 PendingLoads.push_back(Chain);
1914 else
1915 DAG.setRoot(Chain);
1916 }
Chris Lattner0eade312006-03-24 02:22:33 +00001917 if (I.getType() != Type::VoidTy) {
1918 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1919 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1920 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1921 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1922 DAG.getValueType(EVT));
1923 }
1924 setValue(&I, Result);
1925 }
1926}
1927
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001928/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1929/// we want to emit this as a call to a named external function, return the name
1930/// otherwise lower it and return null.
1931const char *
1932SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1933 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001934 default:
1935 // By default, turn this into a target intrinsic node.
1936 visitTargetIntrinsic(I, Intrinsic);
1937 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001938 case Intrinsic::vastart: visitVAStart(I); return 0;
1939 case Intrinsic::vaend: visitVAEnd(I); return 0;
1940 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00001941 case Intrinsic::returnaddress:
1942 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1943 getValue(I.getOperand(1))));
1944 return 0;
1945 case Intrinsic::frameaddress:
1946 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1947 getValue(I.getOperand(1))));
1948 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001949 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001950 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001951 break;
1952 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001953 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001954 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001955 case Intrinsic::memcpy_i32:
1956 case Intrinsic::memcpy_i64:
1957 visitMemIntrinsic(I, ISD::MEMCPY);
1958 return 0;
1959 case Intrinsic::memset_i32:
1960 case Intrinsic::memset_i64:
1961 visitMemIntrinsic(I, ISD::MEMSET);
1962 return 0;
1963 case Intrinsic::memmove_i32:
1964 case Intrinsic::memmove_i64:
1965 visitMemIntrinsic(I, ISD::MEMMOVE);
1966 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001967
Chris Lattner86cb6432005-12-13 17:40:33 +00001968 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001969 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001970 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001971 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001972 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001973
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001974 Ops[0] = getRoot();
1975 Ops[1] = getValue(SPI.getLineValue());
1976 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001977
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001978 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001979 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001980 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1981
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001982 Ops[3] = DAG.getString(CompileUnit->getFileName());
1983 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001984
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001985 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001986 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001987
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001988 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001989 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001990 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001991 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001992 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00001993 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
1994 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00001995 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001996 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001997 }
1998
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001999 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002000 }
2001 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002002 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002003 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002004 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2005 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002006 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002007 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002008 }
2009
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002010 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002011 }
2012 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002013 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002014 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002015 if (MMI && FSI.getSubprogram() &&
2016 MMI->Verify(FSI.getSubprogram())) {
2017 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002018 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002019 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002020 }
2021
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002022 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002023 }
2024 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002025 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002026 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002027 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002028 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002029 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002030 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002031 }
2032
2033 return 0;
2034 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002035
Reid Spencer0b118202006-01-16 21:12:35 +00002036 case Intrinsic::sqrt_f32:
2037 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002038 setValue(&I, DAG.getNode(ISD::FSQRT,
2039 getValue(I.getOperand(1)).getValueType(),
2040 getValue(I.getOperand(1))));
2041 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002042 case Intrinsic::powi_f32:
2043 case Intrinsic::powi_f64:
2044 setValue(&I, DAG.getNode(ISD::FPOWI,
2045 getValue(I.getOperand(1)).getValueType(),
2046 getValue(I.getOperand(1)),
2047 getValue(I.getOperand(2))));
2048 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002049 case Intrinsic::pcmarker: {
2050 SDOperand Tmp = getValue(I.getOperand(1));
2051 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2052 return 0;
2053 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002054 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002055 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002056 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2057 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2058 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002059 setValue(&I, Tmp);
2060 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002061 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002062 }
Nate Begemand88fc032006-01-14 03:14:10 +00002063 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002064 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002065 case Intrinsic::bswap_i64:
2066 setValue(&I, DAG.getNode(ISD::BSWAP,
2067 getValue(I.getOperand(1)).getValueType(),
2068 getValue(I.getOperand(1))));
2069 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002070 case Intrinsic::cttz_i8:
2071 case Intrinsic::cttz_i16:
2072 case Intrinsic::cttz_i32:
2073 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002074 setValue(&I, DAG.getNode(ISD::CTTZ,
2075 getValue(I.getOperand(1)).getValueType(),
2076 getValue(I.getOperand(1))));
2077 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002078 case Intrinsic::ctlz_i8:
2079 case Intrinsic::ctlz_i16:
2080 case Intrinsic::ctlz_i32:
2081 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002082 setValue(&I, DAG.getNode(ISD::CTLZ,
2083 getValue(I.getOperand(1)).getValueType(),
2084 getValue(I.getOperand(1))));
2085 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002086 case Intrinsic::ctpop_i8:
2087 case Intrinsic::ctpop_i16:
2088 case Intrinsic::ctpop_i32:
2089 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002090 setValue(&I, DAG.getNode(ISD::CTPOP,
2091 getValue(I.getOperand(1)).getValueType(),
2092 getValue(I.getOperand(1))));
2093 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002094 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002095 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002096 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2097 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002098 setValue(&I, Tmp);
2099 DAG.setRoot(Tmp.getValue(1));
2100 return 0;
2101 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002102 case Intrinsic::stackrestore: {
2103 SDOperand Tmp = getValue(I.getOperand(1));
2104 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002105 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002106 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002107 case Intrinsic::prefetch:
2108 // FIXME: Currently discarding prefetches.
2109 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002110 }
2111}
2112
2113
Chris Lattner1c08c712005-01-07 07:47:53 +00002114void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002115 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002116 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002117 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002118 if (unsigned IID = F->getIntrinsicID()) {
2119 RenameFn = visitIntrinsicCall(I, IID);
2120 if (!RenameFn)
2121 return;
2122 } else { // Not an LLVM intrinsic.
2123 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002124 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2125 if (I.getNumOperands() == 3 && // Basic sanity checks.
2126 I.getOperand(1)->getType()->isFloatingPoint() &&
2127 I.getType() == I.getOperand(1)->getType() &&
2128 I.getType() == I.getOperand(2)->getType()) {
2129 SDOperand LHS = getValue(I.getOperand(1));
2130 SDOperand RHS = getValue(I.getOperand(2));
2131 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2132 LHS, RHS));
2133 return;
2134 }
2135 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002136 if (I.getNumOperands() == 2 && // Basic sanity checks.
2137 I.getOperand(1)->getType()->isFloatingPoint() &&
2138 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002139 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002140 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2141 return;
2142 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002143 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002144 if (I.getNumOperands() == 2 && // Basic sanity checks.
2145 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002146 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002147 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002148 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2149 return;
2150 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002151 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002152 if (I.getNumOperands() == 2 && // Basic sanity checks.
2153 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002154 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002155 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002156 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2157 return;
2158 }
2159 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002160 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002161 } else if (isa<InlineAsm>(I.getOperand(0))) {
2162 visitInlineAsm(I);
2163 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002164 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002165
Reid Spencer47857812006-12-31 05:55:36 +00002166 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2167 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2168
Chris Lattner64e14b12005-01-08 22:48:57 +00002169 SDOperand Callee;
2170 if (!RenameFn)
2171 Callee = getValue(I.getOperand(0));
2172 else
2173 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencer47857812006-12-31 05:55:36 +00002174 TargetLowering::ArgListTy Args;
2175 TargetLowering::ArgListEntry Entry;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002176 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002177 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2178 Value *Arg = I.getOperand(i);
2179 SDOperand ArgNode = getValue(Arg);
Reid Spencer47857812006-12-31 05:55:36 +00002180 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2181 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002182 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2183 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
Reid Spencer47857812006-12-31 05:55:36 +00002184 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002185 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002186
Chris Lattnercf5734d2005-01-08 19:26:18 +00002187 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002188 TLI.LowerCallTo(getRoot(), I.getType(),
2189 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2190 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2191 Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002192 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002193 setValue(&I, Result.first);
2194 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002195}
2196
Chris Lattner864635a2006-02-22 22:37:12 +00002197SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002198 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002199 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2200 Chain = Val.getValue(1);
2201 Flag = Val.getValue(2);
2202
2203 // If the result was expanded, copy from the top part.
2204 if (Regs.size() > 1) {
2205 assert(Regs.size() == 2 &&
2206 "Cannot expand to more than 2 elts yet!");
2207 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002208 Chain = Hi.getValue(1);
2209 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002210 if (DAG.getTargetLoweringInfo().isLittleEndian())
2211 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2212 else
2213 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002214 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002215
Chris Lattnercf752aa2006-06-08 18:22:48 +00002216 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002217 // appropriate type.
2218 if (RegVT == ValueVT)
2219 return Val;
2220
Chris Lattnercf752aa2006-06-08 18:22:48 +00002221 if (MVT::isInteger(RegVT)) {
2222 if (ValueVT < RegVT)
2223 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2224 else
2225 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2226 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002227 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002228 }
Chris Lattner864635a2006-02-22 22:37:12 +00002229}
2230
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002231/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2232/// specified value into the registers specified by this object. This uses
2233/// Chain/Flag as the input and updates them for the output Chain/Flag.
2234void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002235 SDOperand &Chain, SDOperand &Flag,
2236 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002237 if (Regs.size() == 1) {
2238 // If there is a single register and the types differ, this must be
2239 // a promotion.
2240 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002241 if (MVT::isInteger(RegVT)) {
2242 if (RegVT < ValueVT)
2243 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2244 else
2245 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2246 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002247 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2248 }
2249 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2250 Flag = Chain.getValue(1);
2251 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002252 std::vector<unsigned> R(Regs);
2253 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2254 std::reverse(R.begin(), R.end());
2255
2256 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002257 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002258 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002259 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002260 Flag = Chain.getValue(1);
2261 }
2262 }
2263}
Chris Lattner864635a2006-02-22 22:37:12 +00002264
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002265/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2266/// operand list. This adds the code marker and includes the number of
2267/// values added into it.
2268void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002269 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002270 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2271 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2272 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2273}
Chris Lattner864635a2006-02-22 22:37:12 +00002274
2275/// isAllocatableRegister - If the specified register is safe to allocate,
2276/// i.e. it isn't a stack pointer or some other special register, return the
2277/// register class for the register. Otherwise, return null.
2278static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002279isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2280 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002281 MVT::ValueType FoundVT = MVT::Other;
2282 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002283 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2284 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002285 MVT::ValueType ThisVT = MVT::Other;
2286
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002287 const TargetRegisterClass *RC = *RCI;
2288 // If none of the the value types for this register class are valid, we
2289 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002290 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2291 I != E; ++I) {
2292 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002293 // If we have already found this register in a different register class,
2294 // choose the one with the largest VT specified. For example, on
2295 // PowerPC, we favor f64 register classes over f32.
2296 if (FoundVT == MVT::Other ||
2297 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2298 ThisVT = *I;
2299 break;
2300 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002301 }
2302 }
2303
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002304 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002305
Chris Lattner864635a2006-02-22 22:37:12 +00002306 // NOTE: This isn't ideal. In particular, this might allocate the
2307 // frame pointer in functions that need it (due to them not being taken
2308 // out of allocation, because a variable sized allocation hasn't been seen
2309 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002310 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2311 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002312 if (*I == Reg) {
2313 // We found a matching register class. Keep looking at others in case
2314 // we find one with larger registers that this physreg is also in.
2315 FoundRC = RC;
2316 FoundVT = ThisVT;
2317 break;
2318 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002319 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002320 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002321}
2322
2323RegsForValue SelectionDAGLowering::
2324GetRegistersForValue(const std::string &ConstrCode,
2325 MVT::ValueType VT, bool isOutReg, bool isInReg,
2326 std::set<unsigned> &OutputRegs,
2327 std::set<unsigned> &InputRegs) {
2328 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2329 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2330 std::vector<unsigned> Regs;
2331
2332 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2333 MVT::ValueType RegVT;
2334 MVT::ValueType ValueVT = VT;
2335
Chris Lattner2a821602006-11-02 01:41:49 +00002336 // If this is a constraint for a specific physical register, like {r17},
2337 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002338 if (PhysReg.first) {
2339 if (VT == MVT::Other)
2340 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002341
2342 // Get the actual register value type. This is important, because the user
2343 // may have asked for (e.g.) the AX register in i32 type. We need to
2344 // remember that AX is actually i16 to get the right extension.
2345 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002346
2347 // This is a explicit reference to a physical register.
2348 Regs.push_back(PhysReg.first);
2349
2350 // If this is an expanded reference, add the rest of the regs to Regs.
2351 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002352 TargetRegisterClass::iterator I = PhysReg.second->begin();
2353 TargetRegisterClass::iterator E = PhysReg.second->end();
2354 for (; *I != PhysReg.first; ++I)
2355 assert(I != E && "Didn't find reg!");
2356
2357 // Already added the first reg.
2358 --NumRegs; ++I;
2359 for (; NumRegs; --NumRegs, ++I) {
2360 assert(I != E && "Ran out of registers to allocate!");
2361 Regs.push_back(*I);
2362 }
2363 }
2364 return RegsForValue(Regs, RegVT, ValueVT);
2365 }
2366
Chris Lattner2a821602006-11-02 01:41:49 +00002367 // Otherwise, if this was a reference to an LLVM register class, create vregs
2368 // for this reference.
2369 std::vector<unsigned> RegClassRegs;
2370 if (PhysReg.second) {
2371 // If this is an early clobber or tied register, our regalloc doesn't know
2372 // how to maintain the constraint. If it isn't, go ahead and create vreg
2373 // and let the regalloc do the right thing.
2374 if (!isOutReg || !isInReg) {
2375 if (VT == MVT::Other)
2376 ValueVT = *PhysReg.second->vt_begin();
2377 RegVT = *PhysReg.second->vt_begin();
2378
2379 // Create the appropriate number of virtual registers.
2380 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2381 for (; NumRegs; --NumRegs)
2382 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2383
2384 return RegsForValue(Regs, RegVT, ValueVT);
2385 }
2386
2387 // Otherwise, we can't allocate it. Let the code below figure out how to
2388 // maintain these constraints.
2389 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2390
2391 } else {
2392 // This is a reference to a register class that doesn't directly correspond
2393 // to an LLVM register class. Allocate NumRegs consecutive, available,
2394 // registers from the class.
2395 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2396 }
Chris Lattner864635a2006-02-22 22:37:12 +00002397
2398 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2399 MachineFunction &MF = *CurMBB->getParent();
2400 unsigned NumAllocated = 0;
2401 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2402 unsigned Reg = RegClassRegs[i];
2403 // See if this register is available.
2404 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2405 (isInReg && InputRegs.count(Reg))) { // Already used.
2406 // Make sure we find consecutive registers.
2407 NumAllocated = 0;
2408 continue;
2409 }
2410
2411 // Check to see if this register is allocatable (i.e. don't give out the
2412 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002413 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002414 if (!RC) {
2415 // Make sure we find consecutive registers.
2416 NumAllocated = 0;
2417 continue;
2418 }
2419
2420 // Okay, this register is good, we can use it.
2421 ++NumAllocated;
2422
2423 // If we allocated enough consecutive
2424 if (NumAllocated == NumRegs) {
2425 unsigned RegStart = (i-NumAllocated)+1;
2426 unsigned RegEnd = i+1;
2427 // Mark all of the allocated registers used.
2428 for (unsigned i = RegStart; i != RegEnd; ++i) {
2429 unsigned Reg = RegClassRegs[i];
2430 Regs.push_back(Reg);
2431 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2432 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2433 }
2434
2435 return RegsForValue(Regs, *RC->vt_begin(), VT);
2436 }
2437 }
2438
2439 // Otherwise, we couldn't allocate enough registers for this.
2440 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002441}
2442
Chris Lattner367f1092007-01-29 23:45:14 +00002443/// getConstraintGenerality - Return an integer indicating how general CT is.
2444static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2445 switch (CT) {
2446 default: assert(0 && "Unknown constraint type!");
2447 case TargetLowering::C_Other:
2448 case TargetLowering::C_Unknown:
2449 return 0;
2450 case TargetLowering::C_Register:
2451 return 1;
2452 case TargetLowering::C_RegisterClass:
2453 return 2;
2454 case TargetLowering::C_Memory:
2455 return 3;
2456 }
2457}
2458
2459static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2460 const TargetLowering &TLI) {
2461 assert(!C.empty() && "Must have at least one constraint");
2462 if (C.size() == 1) return C[0];
2463
2464 std::string *Current = &C[0];
2465 // If we have multiple constraints, try to pick the most general one ahead
2466 // of time. This isn't a wonderful solution, but handles common cases.
2467 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2468 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2469 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2470 if (getConstraintGenerality(ThisFlavor) >
2471 getConstraintGenerality(Flavor)) {
2472 // This constraint letter is more general than the previous one,
2473 // use it.
2474 Flavor = ThisFlavor;
2475 Current = &C[j];
2476 }
2477 }
2478 return *Current;
2479}
2480
Chris Lattner864635a2006-02-22 22:37:12 +00002481
Chris Lattnerce7518c2006-01-26 22:24:51 +00002482/// visitInlineAsm - Handle a call to an InlineAsm object.
2483///
2484void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2485 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2486
2487 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2488 MVT::Other);
2489
Chris Lattner2cc2f662006-02-01 01:28:23 +00002490 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002491 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002492
2493 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2494 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2495 /// if it is a def of that register.
2496 std::vector<SDOperand> AsmNodeOperands;
2497 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2498 AsmNodeOperands.push_back(AsmStr);
2499
2500 SDOperand Chain = getRoot();
2501 SDOperand Flag;
2502
Chris Lattner4e4b5762006-02-01 18:59:47 +00002503 // We fully assign registers here at isel time. This is not optimal, but
2504 // should work. For register classes that correspond to LLVM classes, we
2505 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2506 // over the constraints, collecting fixed registers that we know we can't use.
2507 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002508 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002509 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002510 std::string ConstraintCode =
2511 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002512
Chris Lattner1efa40f2006-02-22 00:56:39 +00002513 MVT::ValueType OpVT;
2514
2515 // Compute the value type for each operand and add it to ConstraintVTs.
2516 switch (Constraints[i].Type) {
2517 case InlineAsm::isOutput:
2518 if (!Constraints[i].isIndirectOutput) {
2519 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2520 OpVT = TLI.getValueType(I.getType());
2521 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002522 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002523 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2524 OpNum++; // Consumes a call operand.
2525 }
2526 break;
2527 case InlineAsm::isInput:
2528 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2529 OpNum++; // Consumes a call operand.
2530 break;
2531 case InlineAsm::isClobber:
2532 OpVT = MVT::Other;
2533 break;
2534 }
2535
2536 ConstraintVTs.push_back(OpVT);
2537
Chris Lattner864635a2006-02-22 22:37:12 +00002538 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2539 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002540
Chris Lattner864635a2006-02-22 22:37:12 +00002541 // Build a list of regs that this operand uses. This always has a single
2542 // element for promoted/expanded operands.
2543 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2544 false, false,
2545 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002546
2547 switch (Constraints[i].Type) {
2548 case InlineAsm::isOutput:
2549 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002550 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002551 // If this is an early-clobber output, it cannot be assigned to the same
2552 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002553 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002554 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002555 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002556 case InlineAsm::isInput:
2557 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002558 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002559 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002560 case InlineAsm::isClobber:
2561 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002562 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2563 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002564 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002565 }
2566 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002567
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002568 // Loop over all of the inputs, copying the operand values into the
2569 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002570 RegsForValue RetValRegs;
2571 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002572 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002573
Chris Lattner6656dd12006-01-31 02:03:41 +00002574 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002575 std::string ConstraintCode =
2576 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002577
Chris Lattner2cc2f662006-02-01 01:28:23 +00002578 switch (Constraints[i].Type) {
2579 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002580 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2581 if (ConstraintCode.size() == 1) // not a physreg name.
2582 CTy = TLI.getConstraintType(ConstraintCode[0]);
2583
2584 if (CTy == TargetLowering::C_Memory) {
2585 // Memory output.
2586 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2587
2588 // Check that the operand (the address to store to) isn't a float.
2589 if (!MVT::isInteger(InOperandVal.getValueType()))
2590 assert(0 && "MATCH FAIL!");
2591
2592 if (!Constraints[i].isIndirectOutput)
2593 assert(0 && "MATCH FAIL!");
2594
2595 OpNum++; // Consumes a call operand.
2596
2597 // Extend/truncate to the right pointer type if needed.
2598 MVT::ValueType PtrType = TLI.getPointerTy();
2599 if (InOperandVal.getValueType() < PtrType)
2600 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2601 else if (InOperandVal.getValueType() > PtrType)
2602 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2603
2604 // Add information to the INLINEASM node to know about this output.
2605 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2606 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2607 AsmNodeOperands.push_back(InOperandVal);
2608 break;
2609 }
2610
2611 // Otherwise, this is a register output.
2612 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2613
Chris Lattner864635a2006-02-22 22:37:12 +00002614 // If this is an early-clobber output, or if there is an input
2615 // constraint that matches this, we need to reserve the input register
2616 // so no other inputs allocate to it.
2617 bool UsesInputRegister = false;
2618 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2619 UsesInputRegister = true;
2620
2621 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002622 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002623 RegsForValue Regs =
2624 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2625 true, UsesInputRegister,
2626 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002627 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002628 cerr << "Couldn't allocate output reg for contraint '"
2629 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002630 exit(1);
2631 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002632
Chris Lattner2cc2f662006-02-01 01:28:23 +00002633 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002634 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002635 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002636 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002637 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002638 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002639 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2640 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002641 OpNum++; // Consumes a call operand.
2642 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002643
2644 // Add information to the INLINEASM node to know that this register is
2645 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002646 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002647 break;
2648 }
2649 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002650 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002651 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002652
Chris Lattner2223aea2006-02-02 00:25:23 +00002653 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2654 // If this is required to match an output register we have already set,
2655 // just use its register.
2656 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002657
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002658 // Scan until we find the definition we already emitted of this operand.
2659 // When we find it, create a RegsForValue operand.
2660 unsigned CurOp = 2; // The first operand.
2661 for (; OperandNo; --OperandNo) {
2662 // Advance to the next operand.
2663 unsigned NumOps =
2664 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002665 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2666 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002667 "Skipped past definitions?");
2668 CurOp += (NumOps>>3)+1;
2669 }
2670
2671 unsigned NumOps =
2672 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00002673 if ((NumOps & 7) == 2 /*REGDEF*/) {
2674 // Add NumOps>>3 registers to MatchedRegs.
2675 RegsForValue MatchedRegs;
2676 MatchedRegs.ValueVT = InOperandVal.getValueType();
2677 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2678 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2679 unsigned Reg =
2680 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2681 MatchedRegs.Regs.push_back(Reg);
2682 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002683
Chris Lattner527fae12007-02-01 01:21:12 +00002684 // Use the produced MatchedRegs object to
2685 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2686 TLI.getPointerTy());
2687 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2688 break;
2689 } else {
2690 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2691 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002692 }
Chris Lattner2223aea2006-02-02 00:25:23 +00002693 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002694
2695 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2696 if (ConstraintCode.size() == 1) // not a physreg name.
2697 CTy = TLI.getConstraintType(ConstraintCode[0]);
2698
2699 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002700 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2701 ConstraintCode[0], DAG);
2702 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002703 cerr << "Invalid operand for inline asm constraint '"
2704 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002705 exit(1);
2706 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002707
2708 // Add information to the INLINEASM node to know about this input.
2709 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2710 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2711 AsmNodeOperands.push_back(InOperandVal);
2712 break;
2713 } else if (CTy == TargetLowering::C_Memory) {
2714 // Memory input.
2715
2716 // Check that the operand isn't a float.
2717 if (!MVT::isInteger(InOperandVal.getValueType()))
2718 assert(0 && "MATCH FAIL!");
2719
2720 // Extend/truncate to the right pointer type if needed.
2721 MVT::ValueType PtrType = TLI.getPointerTy();
2722 if (InOperandVal.getValueType() < PtrType)
2723 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2724 else if (InOperandVal.getValueType() > PtrType)
2725 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2726
2727 // Add information to the INLINEASM node to know about this input.
2728 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2729 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2730 AsmNodeOperands.push_back(InOperandVal);
2731 break;
2732 }
2733
2734 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2735
2736 // Copy the input into the appropriate registers.
2737 RegsForValue InRegs =
2738 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2739 false, true, OutputRegs, InputRegs);
2740 // FIXME: should be match fail.
2741 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2742
Evan Chenga8441262006-06-15 08:11:54 +00002743 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002744
2745 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002746 break;
2747 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002748 case InlineAsm::isClobber: {
2749 RegsForValue ClobberedRegs =
2750 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2751 OutputRegs, InputRegs);
2752 // Add the clobbered value to the operand list, so that the register
2753 // allocator is aware that the physreg got clobbered.
2754 if (!ClobberedRegs.Regs.empty())
2755 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002756 break;
2757 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002758 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002759 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002760
2761 // Finish up input operands.
2762 AsmNodeOperands[0] = Chain;
2763 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2764
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002765 Chain = DAG.getNode(ISD::INLINEASM,
2766 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002767 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002768 Flag = Chain.getValue(1);
2769
Chris Lattner6656dd12006-01-31 02:03:41 +00002770 // If this asm returns a register value, copy the result from that register
2771 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002772 if (!RetValRegs.Regs.empty())
2773 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002774
Chris Lattner6656dd12006-01-31 02:03:41 +00002775 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2776
2777 // Process indirect outputs, first output all of the flagged copies out of
2778 // physregs.
2779 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002780 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002781 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002782 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2783 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002784 }
2785
2786 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002787 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002788 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002789 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002790 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002791 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002792 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002793 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2794 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002795 DAG.setRoot(Chain);
2796}
2797
2798
Chris Lattner1c08c712005-01-07 07:47:53 +00002799void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2800 SDOperand Src = getValue(I.getOperand(0));
2801
2802 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002803
2804 if (IntPtr < Src.getValueType())
2805 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2806 else if (IntPtr > Src.getValueType())
2807 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002808
2809 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002810 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002811 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2812 Src, getIntPtrConstant(ElementSize));
2813
Reid Spencer47857812006-12-31 05:55:36 +00002814 TargetLowering::ArgListTy Args;
2815 TargetLowering::ArgListEntry Entry;
2816 Entry.Node = Src;
2817 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2818 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002819 Entry.isInReg = false;
2820 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002821 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002822
2823 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002824 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002825 DAG.getExternalSymbol("malloc", IntPtr),
2826 Args, DAG);
2827 setValue(&I, Result.first); // Pointers always fit in registers
2828 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002829}
2830
2831void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002832 TargetLowering::ArgListTy Args;
2833 TargetLowering::ArgListEntry Entry;
2834 Entry.Node = getValue(I.getOperand(0));
2835 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2836 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002837 Entry.isInReg = false;
2838 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002839 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002840 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002841 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002842 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002843 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2844 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002845}
2846
Chris Lattner025c39b2005-08-26 20:54:47 +00002847// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2848// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2849// instructions are special in various ways, which require special support to
2850// insert. The specified MachineInstr is created but not inserted into any
2851// basic blocks, and the scheduler passes ownership of it to this method.
2852MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2853 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002854 cerr << "If a target marks an instruction with "
2855 << "'usesCustomDAGSchedInserter', it must implement "
2856 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002857 abort();
2858 return 0;
2859}
2860
Chris Lattner39ae3622005-01-09 00:00:49 +00002861void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002862 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2863 getValue(I.getOperand(1)),
2864 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002865}
2866
2867void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002868 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2869 getValue(I.getOperand(0)),
2870 DAG.getSrcValue(I.getOperand(0)));
2871 setValue(&I, V);
2872 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002873}
2874
2875void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002876 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2877 getValue(I.getOperand(1)),
2878 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002879}
2880
2881void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002882 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2883 getValue(I.getOperand(1)),
2884 getValue(I.getOperand(2)),
2885 DAG.getSrcValue(I.getOperand(1)),
2886 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002887}
2888
Evan Chengb15974a2006-12-12 07:27:38 +00002889/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2890/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2891static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2892 unsigned &i, SelectionDAG &DAG,
2893 TargetLowering &TLI) {
2894 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2895 return SDOperand(Arg, i++);
2896
2897 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2898 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2899 if (NumVals == 1) {
2900 return DAG.getNode(ISD::BIT_CONVERT, VT,
2901 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2902 } else if (NumVals == 2) {
2903 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2904 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2905 if (!TLI.isLittleEndian())
2906 std::swap(Lo, Hi);
2907 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2908 } else {
2909 // Value scalarized into many values. Unimp for now.
2910 assert(0 && "Cannot expand i64 -> i16 yet!");
2911 }
2912 return SDOperand();
2913}
2914
Chris Lattnerfdfded52006-04-12 16:20:43 +00002915/// TargetLowering::LowerArguments - This is the default LowerArguments
2916/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002917/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2918/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002919std::vector<SDOperand>
2920TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002921 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002922 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2923 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002924 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002925 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2926 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2927
2928 // Add one result value for each formal argument.
2929 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00002930 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00002931 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
2932 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002933 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00002934 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002935 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
2936 unsigned Flags = (isInReg << 1) | (isSRet << 2);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002937
2938 switch (getTypeAction(VT)) {
2939 default: assert(0 && "Unknown type action!");
2940 case Legal:
2941 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002942 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002943 break;
2944 case Promote:
2945 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002946 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002947 break;
2948 case Expand:
2949 if (VT != MVT::Vector) {
2950 // If this is a large integer, it needs to be broken up into small
2951 // integers. Figure out what the destination type is and how many small
2952 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00002953 MVT::ValueType NVT = getTypeToExpandTo(VT);
2954 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002955 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002956 RetVals.push_back(NVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002957 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2958 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00002959 } else {
2960 // Otherwise, this is a vector type. We only support legal vectors
2961 // right now.
2962 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2963 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002964
Chris Lattnerfdfded52006-04-12 16:20:43 +00002965 // Figure out if there is a Packed type corresponding to this Vector
2966 // type. If so, convert to the packed type.
2967 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2968 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2969 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002970 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002971 } else {
2972 assert(0 && "Don't support illegal by-val vector arguments yet!");
2973 }
2974 }
2975 break;
2976 }
2977 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002978
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002979 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002980
2981 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002982 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2983 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002984 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002985
2986 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002987
2988 // Set up the return result vector.
2989 Ops.clear();
2990 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00002991 unsigned Idx = 1;
2992 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2993 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002994 MVT::ValueType VT = getValueType(I->getType());
2995
2996 switch (getTypeAction(VT)) {
2997 default: assert(0 && "Unknown type action!");
2998 case Legal:
2999 Ops.push_back(SDOperand(Result, i++));
3000 break;
3001 case Promote: {
3002 SDOperand Op(Result, i++);
3003 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003004 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3005 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3006 DAG.getValueType(VT));
3007 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3008 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3009 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003010 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3011 } else {
3012 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3013 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3014 }
3015 Ops.push_back(Op);
3016 break;
3017 }
3018 case Expand:
3019 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003020 // If this is a large integer or a floating point node that needs to be
3021 // expanded, it needs to be reassembled from small integers. Figure out
3022 // what the source elt type is and how many small integers it is.
3023 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003024 } else {
3025 // Otherwise, this is a vector type. We only support legal vectors
3026 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00003027 const PackedType *PTy = cast<PackedType>(I->getType());
3028 unsigned NumElems = PTy->getNumElements();
3029 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003030
Chris Lattnerfdfded52006-04-12 16:20:43 +00003031 // Figure out if there is a Packed type corresponding to this Vector
3032 // type. If so, convert to the packed type.
3033 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003034 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003035 SDOperand N = SDOperand(Result, i++);
3036 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003037 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3038 DAG.getConstant(NumElems, MVT::i32),
3039 DAG.getValueType(getValueType(EltTy)));
3040 Ops.push_back(N);
3041 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003042 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003043 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003044 }
3045 }
3046 break;
3047 }
3048 }
3049 return Ops;
3050}
3051
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003052
Evan Chengb15974a2006-12-12 07:27:38 +00003053/// ExpandScalarCallArgs - Recursively expand call argument node by
3054/// bit_converting it or extract a pair of elements from the larger node.
3055static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003056 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003057 SmallVector<SDOperand, 32> &Ops,
3058 SelectionDAG &DAG,
3059 TargetLowering &TLI) {
3060 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3061 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003062 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003063 return;
3064 }
3065
3066 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3067 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3068 if (NumVals == 1) {
3069 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003070 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI);
Evan Chengb15974a2006-12-12 07:27:38 +00003071 } else if (NumVals == 2) {
3072 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3073 DAG.getConstant(0, TLI.getPointerTy()));
3074 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3075 DAG.getConstant(1, TLI.getPointerTy()));
3076 if (!TLI.isLittleEndian())
3077 std::swap(Lo, Hi);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003078 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI);
3079 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI);
Evan Chengb15974a2006-12-12 07:27:38 +00003080 } else {
3081 // Value scalarized into many values. Unimp for now.
3082 assert(0 && "Cannot expand i64 -> i16 yet!");
3083 }
3084}
3085
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003086/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3087/// implementation, which just inserts an ISD::CALL node, which is later custom
3088/// lowered by the target to something concrete. FIXME: When all targets are
3089/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3090std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003091TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3092 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003093 unsigned CallingConv, bool isTailCall,
3094 SDOperand Callee,
3095 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003096 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003097 Ops.push_back(Chain); // Op#0 - Chain
3098 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3099 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3100 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3101 Ops.push_back(Callee);
3102
3103 // Handle all of the outgoing arguments.
3104 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003105 MVT::ValueType VT = getValueType(Args[i].Ty);
3106 SDOperand Op = Args[i].Node;
3107 bool isSigned = Args[i].isSigned;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003108 bool isInReg = Args[i].isInReg;
3109 bool isSRet = Args[i].isSRet;
3110 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003111 switch (getTypeAction(VT)) {
3112 default: assert(0 && "Unknown type action!");
3113 case Legal:
3114 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003115 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003116 break;
3117 case Promote:
3118 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003119 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003120 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3121 } else {
3122 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3123 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3124 }
3125 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003126 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003127 break;
3128 case Expand:
3129 if (VT != MVT::Vector) {
3130 // If this is a large integer, it needs to be broken down into small
3131 // integers. Figure out what the source elt type is and how many small
3132 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003133 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003134 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003135 // Otherwise, this is a vector type. We only support legal vectors
3136 // right now.
Reid Spencer47857812006-12-31 05:55:36 +00003137 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003138 unsigned NumElems = PTy->getNumElements();
3139 const Type *EltTy = PTy->getElementType();
3140
3141 // Figure out if there is a Packed type corresponding to this Vector
3142 // type. If so, convert to the packed type.
3143 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003144 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3145 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3146 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3147 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003148 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003149 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003150 assert(0 && "Don't support illegal by-val vector call args yet!");
3151 abort();
3152 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003153 }
3154 break;
3155 }
3156 }
3157
3158 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003159 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003160
3161 if (RetTy != Type::VoidTy) {
3162 MVT::ValueType VT = getValueType(RetTy);
3163 switch (getTypeAction(VT)) {
3164 default: assert(0 && "Unknown type action!");
3165 case Legal:
3166 RetTys.push_back(VT);
3167 break;
3168 case Promote:
3169 RetTys.push_back(getTypeToTransformTo(VT));
3170 break;
3171 case Expand:
3172 if (VT != MVT::Vector) {
3173 // If this is a large integer, it needs to be reassembled from small
3174 // integers. Figure out what the source elt type is and how many small
3175 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003176 MVT::ValueType NVT = getTypeToExpandTo(VT);
3177 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003178 for (unsigned i = 0; i != NumVals; ++i)
3179 RetTys.push_back(NVT);
3180 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003181 // Otherwise, this is a vector type. We only support legal vectors
3182 // right now.
3183 const PackedType *PTy = cast<PackedType>(RetTy);
3184 unsigned NumElems = PTy->getNumElements();
3185 const Type *EltTy = PTy->getElementType();
3186
3187 // Figure out if there is a Packed type corresponding to this Vector
3188 // type. If so, convert to the packed type.
3189 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3190 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3191 RetTys.push_back(TVT);
3192 } else {
3193 assert(0 && "Don't support illegal by-val vector call results yet!");
3194 abort();
3195 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003196 }
3197 }
3198 }
3199
3200 RetTys.push_back(MVT::Other); // Always has a chain.
3201
3202 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003203 SDOperand Res = DAG.getNode(ISD::CALL,
3204 DAG.getVTList(&RetTys[0], RetTys.size()),
3205 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003206
3207 // This returns a pair of operands. The first element is the
3208 // return value for the function (if RetTy is not VoidTy). The second
3209 // element is the outgoing token chain.
3210 SDOperand ResVal;
3211 if (RetTys.size() != 1) {
3212 MVT::ValueType VT = getValueType(RetTy);
3213 if (RetTys.size() == 2) {
3214 ResVal = Res;
3215
3216 // If this value was promoted, truncate it down.
3217 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003218 if (VT == MVT::Vector) {
3219 // Insert a VBITCONVERT to convert from the packed result type to the
3220 // MVT::Vector type.
3221 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3222 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3223
3224 // Figure out if there is a Packed type corresponding to this Vector
3225 // type. If so, convert to the packed type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003226 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003227 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003228 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3229 // "N x PTyElementVT" MVT::Vector type.
3230 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003231 DAG.getConstant(NumElems, MVT::i32),
3232 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003233 } else {
3234 abort();
3235 }
3236 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003237 unsigned AssertOp = ISD::AssertSext;
3238 if (!RetTyIsSigned)
3239 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003240 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3241 DAG.getValueType(VT));
3242 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3243 } else {
3244 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003245 if (getTypeAction(VT) == Expand)
3246 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3247 else
3248 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003249 }
3250 }
3251 } else if (RetTys.size() == 3) {
3252 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3253 Res.getValue(0), Res.getValue(1));
3254
3255 } else {
3256 assert(0 && "Case not handled yet!");
3257 }
3258 }
3259
3260 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3261}
3262
Chris Lattner50381b62005-05-14 05:50:48 +00003263SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003264 assert(0 && "LowerOperation not implemented for this target!");
3265 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003266 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003267}
3268
Nate Begeman0aed7842006-01-28 03:14:31 +00003269SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3270 SelectionDAG &DAG) {
3271 assert(0 && "CustomPromoteOperation not implemented for this target!");
3272 abort();
3273 return SDOperand();
3274}
3275
Evan Cheng74d0aa92006-02-15 21:59:04 +00003276/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003277/// operand.
3278static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003279 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003280 MVT::ValueType CurVT = VT;
3281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3282 uint64_t Val = C->getValue() & 255;
3283 unsigned Shift = 8;
3284 while (CurVT != MVT::i8) {
3285 Val = (Val << Shift) | Val;
3286 Shift <<= 1;
3287 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003288 }
3289 return DAG.getConstant(Val, VT);
3290 } else {
3291 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3292 unsigned Shift = 8;
3293 while (CurVT != MVT::i8) {
3294 Value =
3295 DAG.getNode(ISD::OR, VT,
3296 DAG.getNode(ISD::SHL, VT, Value,
3297 DAG.getConstant(Shift, MVT::i8)), Value);
3298 Shift <<= 1;
3299 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003300 }
3301
3302 return Value;
3303 }
3304}
3305
Evan Cheng74d0aa92006-02-15 21:59:04 +00003306/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3307/// used when a memcpy is turned into a memset when the source is a constant
3308/// string ptr.
3309static SDOperand getMemsetStringVal(MVT::ValueType VT,
3310 SelectionDAG &DAG, TargetLowering &TLI,
3311 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003312 uint64_t Val = 0;
3313 unsigned MSB = getSizeInBits(VT) / 8;
3314 if (TLI.isLittleEndian())
3315 Offset = Offset + MSB - 1;
3316 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003317 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003318 Offset += TLI.isLittleEndian() ? -1 : 1;
3319 }
3320 return DAG.getConstant(Val, VT);
3321}
3322
Evan Cheng1db92f92006-02-14 08:22:34 +00003323/// getMemBasePlusOffset - Returns base and offset node for the
3324static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3325 SelectionDAG &DAG, TargetLowering &TLI) {
3326 MVT::ValueType VT = Base.getValueType();
3327 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3328}
3329
Evan Chengc4f8eee2006-02-14 20:12:38 +00003330/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003331/// to replace the memset / memcpy is below the threshold. It also returns the
3332/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003333static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3334 unsigned Limit, uint64_t Size,
3335 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003336 MVT::ValueType VT;
3337
3338 if (TLI.allowsUnalignedMemoryAccesses()) {
3339 VT = MVT::i64;
3340 } else {
3341 switch (Align & 7) {
3342 case 0:
3343 VT = MVT::i64;
3344 break;
3345 case 4:
3346 VT = MVT::i32;
3347 break;
3348 case 2:
3349 VT = MVT::i16;
3350 break;
3351 default:
3352 VT = MVT::i8;
3353 break;
3354 }
3355 }
3356
Evan Cheng80e89d72006-02-14 09:11:59 +00003357 MVT::ValueType LVT = MVT::i64;
3358 while (!TLI.isTypeLegal(LVT))
3359 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3360 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003361
Evan Cheng80e89d72006-02-14 09:11:59 +00003362 if (VT > LVT)
3363 VT = LVT;
3364
Evan Chengdea72452006-02-14 23:05:54 +00003365 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003366 while (Size != 0) {
3367 unsigned VTSize = getSizeInBits(VT) / 8;
3368 while (VTSize > Size) {
3369 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003370 VTSize >>= 1;
3371 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003372 assert(MVT::isInteger(VT));
3373
3374 if (++NumMemOps > Limit)
3375 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003376 MemOps.push_back(VT);
3377 Size -= VTSize;
3378 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003379
3380 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003381}
3382
Chris Lattner7041ee32005-01-11 05:56:49 +00003383void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003384 SDOperand Op1 = getValue(I.getOperand(1));
3385 SDOperand Op2 = getValue(I.getOperand(2));
3386 SDOperand Op3 = getValue(I.getOperand(3));
3387 SDOperand Op4 = getValue(I.getOperand(4));
3388 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3389 if (Align == 0) Align = 1;
3390
3391 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3392 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003393
3394 // Expand memset / memcpy to a series of load / store ops
3395 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003396 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003397 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003398 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003399 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003400 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3401 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003402 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003403 unsigned Offset = 0;
3404 for (unsigned i = 0; i < NumMemOps; i++) {
3405 MVT::ValueType VT = MemOps[i];
3406 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003407 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003408 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003409 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003410 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003411 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003412 Offset += VTSize;
3413 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003414 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003415 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003416 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003417 case ISD::MEMCPY: {
3418 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3419 Size->getValue(), Align, TLI)) {
3420 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003421 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003422 GlobalAddressSDNode *G = NULL;
3423 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003424 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003425
3426 if (Op2.getOpcode() == ISD::GlobalAddress)
3427 G = cast<GlobalAddressSDNode>(Op2);
3428 else if (Op2.getOpcode() == ISD::ADD &&
3429 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3430 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3431 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003432 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003433 }
3434 if (G) {
3435 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003436 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003437 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003438 if (!Str.empty()) {
3439 CopyFromStr = true;
3440 SrcOff += SrcDelta;
3441 }
3442 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003443 }
3444
Evan Chengc080d6f2006-02-15 01:54:51 +00003445 for (unsigned i = 0; i < NumMemOps; i++) {
3446 MVT::ValueType VT = MemOps[i];
3447 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003448 SDOperand Value, Chain, Store;
3449
Evan Chengcffbb512006-02-16 23:11:42 +00003450 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003451 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3452 Chain = getRoot();
3453 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003454 DAG.getStore(Chain, Value,
3455 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003456 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003457 } else {
3458 Value = DAG.getLoad(VT, getRoot(),
3459 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003460 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003461 Chain = Value.getValue(1);
3462 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003463 DAG.getStore(Chain, Value,
3464 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003465 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003466 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003467 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003468 SrcOff += VTSize;
3469 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003470 }
3471 }
3472 break;
3473 }
3474 }
3475
3476 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003477 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3478 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003479 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003480 }
3481 }
3482
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003483 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003484}
3485
Chris Lattner7041ee32005-01-11 05:56:49 +00003486//===----------------------------------------------------------------------===//
3487// SelectionDAGISel code
3488//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003489
3490unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3491 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3492}
3493
Chris Lattner495a0b52005-08-17 06:37:43 +00003494void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003495 // FIXME: we only modify the CFG to split critical edges. This
3496 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003497 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003498}
Chris Lattner1c08c712005-01-07 07:47:53 +00003499
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003500
Chris Lattner90323642006-05-05 21:17:49 +00003501/// OptimizeNoopCopyExpression - We have determined that the specified cast
3502/// instruction is a noop copy (e.g. it's casting from one pointer type to
3503/// another, int->uint, or int->sbyte on PPC.
3504///
3505/// Return true if any changes are made.
3506static bool OptimizeNoopCopyExpression(CastInst *CI) {
3507 BasicBlock *DefBB = CI->getParent();
3508
3509 /// InsertedCasts - Only insert a cast in each block once.
3510 std::map<BasicBlock*, CastInst*> InsertedCasts;
3511
3512 bool MadeChange = false;
3513 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3514 UI != E; ) {
3515 Use &TheUse = UI.getUse();
3516 Instruction *User = cast<Instruction>(*UI);
3517
3518 // Figure out which BB this cast is used in. For PHI's this is the
3519 // appropriate predecessor block.
3520 BasicBlock *UserBB = User->getParent();
3521 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3522 unsigned OpVal = UI.getOperandNo()/2;
3523 UserBB = PN->getIncomingBlock(OpVal);
3524 }
3525
3526 // Preincrement use iterator so we don't invalidate it.
3527 ++UI;
3528
3529 // If this user is in the same block as the cast, don't change the cast.
3530 if (UserBB == DefBB) continue;
3531
3532 // If we have already inserted a cast into this block, use it.
3533 CastInst *&InsertedCast = InsertedCasts[UserBB];
3534
3535 if (!InsertedCast) {
3536 BasicBlock::iterator InsertPt = UserBB->begin();
3537 while (isa<PHINode>(InsertPt)) ++InsertPt;
3538
3539 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003540 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3541 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003542 MadeChange = true;
3543 }
3544
3545 // Replace a use of the cast with a use of the new casat.
3546 TheUse = InsertedCast;
3547 }
3548
3549 // If we removed all uses, nuke the cast.
3550 if (CI->use_empty())
3551 CI->eraseFromParent();
3552
3553 return MadeChange;
3554}
3555
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003556/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3557/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003558static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3559 Instruction *GEPI, Value *Ptr,
3560 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003561 if (V) return V; // Already computed.
3562
Reid Spencer3da59db2006-11-27 01:05:10 +00003563 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003564 BasicBlock::iterator InsertPt;
3565 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003566 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003567 InsertPt = GEPI;
3568 ++InsertPt;
3569 } else {
3570 // Otherwise, insert at the top of BB, after any PHI nodes
3571 InsertPt = BB->begin();
3572 while (isa<PHINode>(InsertPt)) ++InsertPt;
3573 }
3574
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003575 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3576 // BB so that there is only one value live across basic blocks (the cast
3577 // operand).
3578 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3579 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003580 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3581 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003582
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003583 // Add the offset, cast it to the right type.
3584 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003585 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3586 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3587 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003588}
3589
Chris Lattner90323642006-05-05 21:17:49 +00003590/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3591/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3592/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3593/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3594/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3595/// the constant add into a load or store instruction. Additionally, if a user
3596/// is a pointer-pointer cast, we look through it to find its users.
3597static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3598 Constant *PtrOffset, BasicBlock *DefBB,
3599 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003600 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003601 while (!RepPtr->use_empty()) {
3602 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003603
Reid Spencer3da59db2006-11-27 01:05:10 +00003604 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3605 // used for a Pointer-Pointer cast.
3606 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003607 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003608
Chris Lattner90323642006-05-05 21:17:49 +00003609 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3610 // could invalidate an iterator.
3611 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3612 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003613 }
3614
Chris Lattner90323642006-05-05 21:17:49 +00003615 // If this is a load of the pointer, or a store through the pointer, emit
3616 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003617 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003618 if (isa<LoadInst>(User) ||
3619 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3620 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3621 User->getParent(), GEPI,
3622 Ptr, PtrOffset);
3623 } else {
3624 // If this use is not foldable into the addressing mode, use a version
3625 // emitted in the GEP block.
3626 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3627 Ptr, PtrOffset);
3628 }
3629
Chris Lattnerf0df8822006-05-06 09:10:37 +00003630 if (GEPI->getType() != RepPtr->getType()) {
3631 BasicBlock::iterator IP = NewVal;
3632 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003633 // NewVal must be a GEP which must be pointer type, so BitCast
3634 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003635 }
Chris Lattner90323642006-05-05 21:17:49 +00003636 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003637 }
3638}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003639
Chris Lattner90323642006-05-05 21:17:49 +00003640
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003641/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3642/// selection, we want to be a bit careful about some things. In particular, if
3643/// we have a GEP instruction that is used in a different block than it is
3644/// defined, the addressing expression of the GEP cannot be folded into loads or
3645/// stores that use it. In this case, decompose the GEP and move constant
3646/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003647static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003648 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003649 // If this GEP is only used inside the block it is defined in, there is no
3650 // need to rewrite it.
3651 bool isUsedOutsideDefBB = false;
3652 BasicBlock *DefBB = GEPI->getParent();
3653 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3654 UI != E; ++UI) {
3655 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3656 isUsedOutsideDefBB = true;
3657 break;
3658 }
3659 }
Chris Lattner90323642006-05-05 21:17:49 +00003660 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003661
3662 // If this GEP has no non-zero constant indices, there is nothing we can do,
3663 // ignore it.
3664 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003665 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003666 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3667 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003668 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003669 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003670 hasConstantIndex = true;
3671 break;
3672 }
Chris Lattner90323642006-05-05 21:17:49 +00003673 } else {
3674 hasVariableIndex = true;
3675 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003676 }
Chris Lattner90323642006-05-05 21:17:49 +00003677
3678 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3679 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003680 /// The GEP operand must be a pointer, so must its result -> BitCast
3681 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003682 GEPI->getName(), GEPI);
3683 GEPI->replaceAllUsesWith(NC);
3684 GEPI->eraseFromParent();
3685 return true;
3686 }
3687
Chris Lattner3802c252005-12-11 09:05:13 +00003688 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003689 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3690 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003691
3692 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3693 // constant offset (which we now know is non-zero) and deal with it later.
3694 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003695 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003696 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003697 const Type *Ty = GEPI->getOperand(0)->getType();
3698
3699 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3700 E = GEPI->op_end(); OI != E; ++OI) {
3701 Value *Idx = *OI;
3702 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003703 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003704 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003705 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003706 Ty = StTy->getElementType(Field);
3707 } else {
3708 Ty = cast<SequentialType>(Ty)->getElementType();
3709
3710 // Handle constant subscripts.
3711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003712 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003713 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003714 continue;
3715 }
3716
3717 // Ptr = Ptr + Idx * ElementSize;
3718
3719 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003720 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003721
Owen Andersona69571c2006-05-03 01:29:57 +00003722 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003723 // Mask off bits that should not be set.
3724 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003725 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003726
3727 // Multiply by the element size and add to the base.
3728 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3729 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3730 }
3731 }
3732
3733 // Make sure that the offset fits in uintptr_t.
3734 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003735 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003736
3737 // Okay, we have now emitted all of the variable index parts to the BB that
3738 // the GEP is defined in. Loop over all of the using instructions, inserting
3739 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003740 // instruction to use the newly computed value, making GEPI dead. When the
3741 // user is a load or store instruction address, we emit the add into the user
3742 // block, otherwise we use a canonical version right next to the gep (these
3743 // won't be foldable as addresses, so we might as well share the computation).
3744
Chris Lattnerf0df8822006-05-06 09:10:37 +00003745 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003746 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003747
3748 // Finally, the GEP is dead, remove it.
3749 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003750
3751 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003752}
3753
Chris Lattnerbad7f482006-10-28 19:22:10 +00003754
3755/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3756/// successor if it will improve codegen. We only do this if the successor has
3757/// phi nodes (otherwise critical edges are ok). If there is already another
3758/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3759/// instead of introducing a new block.
3760static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3761 BasicBlock *TIBB = TI->getParent();
3762 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3763 assert(isa<PHINode>(Dest->begin()) &&
3764 "This should only be called if Dest has a PHI!");
3765
3766 /// TIPHIValues - This array is lazily computed to determine the values of
3767 /// PHIs in Dest that TI would provide.
3768 std::vector<Value*> TIPHIValues;
3769
3770 // Check to see if Dest has any blocks that can be used as a split edge for
3771 // this terminator.
3772 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3773 BasicBlock *Pred = *PI;
3774 // To be usable, the pred has to end with an uncond branch to the dest.
3775 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3776 if (!PredBr || !PredBr->isUnconditional() ||
3777 // Must be empty other than the branch.
3778 &Pred->front() != PredBr)
3779 continue;
3780
3781 // Finally, since we know that Dest has phi nodes in it, we have to make
3782 // sure that jumping to Pred will have the same affect as going to Dest in
3783 // terms of PHI values.
3784 PHINode *PN;
3785 unsigned PHINo = 0;
3786 bool FoundMatch = true;
3787 for (BasicBlock::iterator I = Dest->begin();
3788 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3789 if (PHINo == TIPHIValues.size())
3790 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3791
3792 // If the PHI entry doesn't work, we can't use this pred.
3793 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3794 FoundMatch = false;
3795 break;
3796 }
3797 }
3798
3799 // If we found a workable predecessor, change TI to branch to Succ.
3800 if (FoundMatch) {
3801 Dest->removePredecessor(TIBB);
3802 TI->setSuccessor(SuccNum, Pred);
3803 return;
3804 }
3805 }
3806
3807 SplitCriticalEdge(TI, SuccNum, P, true);
3808}
3809
3810
Chris Lattner1c08c712005-01-07 07:47:53 +00003811bool SelectionDAGISel::runOnFunction(Function &Fn) {
3812 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3813 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003814 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003815
Chris Lattner47e32e62006-10-28 17:04:37 +00003816 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003817 //
Chris Lattner7e598092006-05-05 01:04:50 +00003818 // In this pass we also look for GEP and cast instructions that are used
3819 // across basic blocks and rewrite them to improve basic-block-at-a-time
3820 // selection.
3821 //
Chris Lattner90323642006-05-05 21:17:49 +00003822 bool MadeChange = true;
3823 while (MadeChange) {
3824 MadeChange = false;
Evan Cheng15699fc2007-02-10 01:08:18 +00003825 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003826 // Split all critical edges where the dest block has a PHI.
Evan Cheng15699fc2007-02-10 01:08:18 +00003827 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner47e32e62006-10-28 17:04:37 +00003828 if (BBTI->getNumSuccessors() > 1) {
3829 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003830 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3831 isCriticalEdge(BBTI, i, true))
3832 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003833 }
3834
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003835
Evan Cheng15699fc2007-02-10 01:08:18 +00003836 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003837 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003838
3839 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3840 // If we found an inline asm expession, and if the target knows how to
3841 // lower it to normal LLVM code, do so now.
3842 if (isa<InlineAsm>(CI->getCalledValue()))
3843 if (const TargetAsmInfo *TAI =
3844 TLI.getTargetMachine().getTargetAsmInfo()) {
3845 if (TAI->ExpandInlineAsm(CI))
Evan Cheng15699fc2007-02-10 01:08:18 +00003846 BBI = FNI->begin();
Chris Lattner3f7927c2006-11-29 01:12:32 +00003847 }
3848 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003849 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003850 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003851 // If the source of the cast is a constant, then this should have
3852 // already been constant folded. The only reason NOT to constant fold
3853 // it is if something (e.g. LSR) was careful to place the constant
3854 // evaluation in a block other than then one that uses it (e.g. to hoist
3855 // the address of globals out of a loop). If this is the case, we don't
3856 // want to forward-subst the cast.
3857 if (isa<Constant>(CI->getOperand(0)))
3858 continue;
3859
Chris Lattner7e598092006-05-05 01:04:50 +00003860 // If this is a noop copy, sink it into user blocks to reduce the number
3861 // of virtual registers that must be created and coallesced.
3862 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3863 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3864
3865 // This is an fp<->int conversion?
3866 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3867 continue;
3868
3869 // If this is an extension, it will be a zero or sign extension, which
3870 // isn't a noop.
3871 if (SrcVT < DstVT) continue;
3872
3873 // If these values will be promoted, find out what they will be promoted
3874 // to. This helps us consider truncates on PPC as noop copies when they
3875 // are.
3876 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3877 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3878 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3879 DstVT = TLI.getTypeToTransformTo(DstVT);
3880
3881 // If, after promotion, these are the same types, this is a noop copy.
3882 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003883 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003884 }
3885 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003886 }
Chris Lattner90323642006-05-05 21:17:49 +00003887 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003888
Chris Lattner1c08c712005-01-07 07:47:53 +00003889 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3890
3891 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3892 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003893
Evan Chengad2070c2007-02-10 02:43:39 +00003894 // Add function live-ins to entry block live-in set.
3895 BasicBlock *EntryBB = &Fn.getEntryBlock();
3896 BB = FuncInfo.MBBMap[EntryBB];
3897 if (!MF.livein_empty())
3898 for (MachineFunction::livein_iterator I = MF.livein_begin(),
3899 E = MF.livein_end(); I != E; ++I)
3900 BB->addLiveIn(I->first);
3901
Chris Lattner1c08c712005-01-07 07:47:53 +00003902 return true;
3903}
3904
Chris Lattner571e4342006-10-27 21:36:01 +00003905SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3906 unsigned Reg) {
3907 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003908 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003909 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003910 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003911
3912 // If this type is not legal, we must make sure to not create an invalid
3913 // register use.
3914 MVT::ValueType SrcVT = Op.getValueType();
3915 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003916 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003917 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003918 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003919 // Handle copies from generic vectors to registers.
3920 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3921 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3922 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003923
Chris Lattner70c2a612006-03-31 02:06:56 +00003924 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3925 // MVT::Vector type.
3926 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3927 DAG.getConstant(NE, MVT::i32),
3928 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003929
Chris Lattner70c2a612006-03-31 02:06:56 +00003930 // Loop over all of the elements of the resultant vector,
3931 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3932 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003933 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003934 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003935 for (unsigned i = 0; i != NE; ++i) {
3936 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003937 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003938 if (PTyElementVT == PTyLegalElementVT) {
3939 // Elements are legal.
3940 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3941 } else if (PTyLegalElementVT > PTyElementVT) {
3942 // Elements are promoted.
3943 if (MVT::isFloatingPoint(PTyLegalElementVT))
3944 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3945 else
3946 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3947 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3948 } else {
3949 // Elements are expanded.
3950 // The src value is expanded into multiple registers.
3951 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003952 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003953 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003954 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003955 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3956 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3957 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003958 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003959 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3960 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00003961 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003962 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003963 if (MVT::isFloatingPoint(SrcVT))
3964 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3965 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003966 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003967 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003968 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00003969 DestVT = TLI.getTypeToExpandTo(SrcVT);
3970 unsigned NumVals = TLI.getNumElements(SrcVT);
3971 if (NumVals == 1)
3972 return DAG.getCopyToReg(getRoot(), Reg,
3973 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3974 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003975 // The src value is expanded into multiple registers.
3976 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003977 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003978 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003979 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003980 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003981 return DAG.getCopyToReg(Op, Reg+1, Hi);
3982 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003983}
3984
Chris Lattner068a81e2005-01-17 17:15:02 +00003985void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00003986LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00003987 std::vector<SDOperand> &UnorderedChains) {
3988 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00003989 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003990 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003991 SDOperand OldRoot = SDL.DAG.getRoot();
3992 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003993
Chris Lattnerbf209482005-10-30 19:42:35 +00003994 unsigned a = 0;
3995 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3996 AI != E; ++AI, ++a)
3997 if (!AI->use_empty()) {
3998 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003999
Chris Lattnerbf209482005-10-30 19:42:35 +00004000 // If this argument is live outside of the entry block, insert a copy from
4001 // whereever we got it to the vreg that other BB's will reference it as.
4002 if (FuncInfo.ValueMap.count(AI)) {
4003 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00004004 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00004005 UnorderedChains.push_back(Copy);
4006 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004007 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004008
Chris Lattnerbf209482005-10-30 19:42:35 +00004009 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004010 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004011 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004012}
4013
Chris Lattner1c08c712005-01-07 07:47:53 +00004014void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4015 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004016 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004017 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004018
4019 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004020
Chris Lattnerbf209482005-10-30 19:42:35 +00004021 // Lower any arguments needed in this block if this is the entry block.
4022 if (LLVMBB == &LLVMBB->getParent()->front())
4023 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004024
4025 BB = FuncInfo.MBBMap[LLVMBB];
4026 SDL.setCurrentBasicBlock(BB);
4027
4028 // Lower all of the non-terminator instructions.
4029 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4030 I != E; ++I)
4031 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00004032
Chris Lattner1c08c712005-01-07 07:47:53 +00004033 // Ensure that all instructions which are used outside of their defining
4034 // blocks are available as virtual registers.
4035 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004036 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004037 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004038 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004039 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004040 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004041 }
4042
4043 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4044 // ensure constants are generated when needed. Remember the virtual registers
4045 // that need to be added to the Machine PHI nodes as input. We cannot just
4046 // directly add them, because expansion might result in multiple MBB's for one
4047 // BB. As such, the start of the BB might correspond to a different MBB than
4048 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004049 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004050 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004051
4052 // Emit constants only once even if used by multiple PHI nodes.
4053 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004054
Chris Lattner8c494ab2006-10-27 23:50:33 +00004055 // Vector bool would be better, but vector<bool> is really slow.
4056 std::vector<unsigned char> SuccsHandled;
4057 if (TI->getNumSuccessors())
4058 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4059
Chris Lattner1c08c712005-01-07 07:47:53 +00004060 // Check successor nodes PHI nodes that expect a constant to be available from
4061 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004062 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4063 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004064 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004065 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004066
Chris Lattner8c494ab2006-10-27 23:50:33 +00004067 // If this terminator has multiple identical successors (common for
4068 // switches), only handle each succ once.
4069 unsigned SuccMBBNo = SuccMBB->getNumber();
4070 if (SuccsHandled[SuccMBBNo]) continue;
4071 SuccsHandled[SuccMBBNo] = true;
4072
4073 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004074 PHINode *PN;
4075
4076 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4077 // nodes and Machine PHI nodes, but the incoming operands have not been
4078 // emitted yet.
4079 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004080 (PN = dyn_cast<PHINode>(I)); ++I) {
4081 // Ignore dead phi's.
4082 if (PN->use_empty()) continue;
4083
4084 unsigned Reg;
4085 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004086
Chris Lattner8c494ab2006-10-27 23:50:33 +00004087 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4088 unsigned &RegOut = ConstantsOut[C];
4089 if (RegOut == 0) {
4090 RegOut = FuncInfo.CreateRegForValue(C);
4091 UnorderedChains.push_back(
4092 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004093 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004094 Reg = RegOut;
4095 } else {
4096 Reg = FuncInfo.ValueMap[PHIOp];
4097 if (Reg == 0) {
4098 assert(isa<AllocaInst>(PHIOp) &&
4099 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4100 "Didn't codegen value into a register!??");
4101 Reg = FuncInfo.CreateRegForValue(PHIOp);
4102 UnorderedChains.push_back(
4103 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004104 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004105 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004106
4107 // Remember that this register needs to added to the machine PHI node as
4108 // the input for this MBB.
4109 MVT::ValueType VT = TLI.getValueType(PN->getType());
4110 unsigned NumElements;
4111 if (VT != MVT::Vector)
4112 NumElements = TLI.getNumElements(VT);
4113 else {
4114 MVT::ValueType VT1,VT2;
4115 NumElements =
4116 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4117 VT1, VT2);
4118 }
4119 for (unsigned i = 0, e = NumElements; i != e; ++i)
4120 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4121 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004122 }
4123 ConstantsOut.clear();
4124
Chris Lattnerddb870b2005-01-13 17:59:43 +00004125 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004126 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004127 SDOperand Root = SDL.getRoot();
4128 if (Root.getOpcode() != ISD::EntryToken) {
4129 unsigned i = 0, e = UnorderedChains.size();
4130 for (; i != e; ++i) {
4131 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4132 if (UnorderedChains[i].Val->getOperand(0) == Root)
4133 break; // Don't add the root if we already indirectly depend on it.
4134 }
4135
4136 if (i == e)
4137 UnorderedChains.push_back(Root);
4138 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004139 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4140 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004141 }
4142
Chris Lattner1c08c712005-01-07 07:47:53 +00004143 // Lower the terminator after the copies are emitted.
4144 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004145
Nate Begemanf15485a2006-03-27 01:32:24 +00004146 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004147 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004148 SwitchCases.clear();
4149 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004150 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004151
Chris Lattnera651cf62005-01-17 19:43:36 +00004152 // Make sure the root of the DAG is up-to-date.
4153 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004154}
4155
Nate Begemanf15485a2006-03-27 01:32:24 +00004156void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004157 // Get alias analysis for load/store combining.
4158 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4159
Chris Lattneraf21d552005-10-10 16:47:10 +00004160 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004161 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004162
Bill Wendling832171c2006-12-07 20:04:42 +00004163 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004164 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004165
Chris Lattner1c08c712005-01-07 07:47:53 +00004166 // Second step, hack on the DAG until it only uses operations and types that
4167 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004168 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004169
Bill Wendling832171c2006-12-07 20:04:42 +00004170 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004171 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004172
Chris Lattneraf21d552005-10-10 16:47:10 +00004173 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004174 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004175
Evan Chenga9c20912006-01-21 02:32:06 +00004176 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004177
Chris Lattnera33ef482005-03-30 01:10:47 +00004178 // Third, instruction select all of the operations to machine code, adding the
4179 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004180 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004181
Bill Wendling832171c2006-12-07 20:04:42 +00004182 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004183 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004184}
Chris Lattner1c08c712005-01-07 07:47:53 +00004185
Nate Begemanf15485a2006-03-27 01:32:24 +00004186void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4187 FunctionLoweringInfo &FuncInfo) {
4188 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4189 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004190 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004191 CurDAG = &DAG;
4192
4193 // First step, lower LLVM code to some DAG. This DAG may use operations and
4194 // types that are not supported by the target.
4195 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4196
4197 // Second step, emit the lowered DAG as machine code.
4198 CodeGenAndEmitDAG(DAG);
4199 }
4200
Chris Lattnera33ef482005-03-30 01:10:47 +00004201 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004202 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004203 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004204 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4205 MachineInstr *PHI = PHINodesToUpdate[i].first;
4206 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4207 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004208 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004209 PHI->addMachineBasicBlockOperand(BB);
4210 }
4211 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004212 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004213
Nate Begeman9453eea2006-04-23 06:26:20 +00004214 // If the JumpTable record is filled in, then we need to emit a jump table.
4215 // Updating the PHI nodes is tricky in this case, since we need to determine
4216 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004217 if (JT.Reg) {
4218 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004219 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004220 CurDAG = &SDAG;
4221 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004222 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004223 // Set the current basic block to the mbb we wish to insert the code into
4224 BB = JT.MBB;
4225 SDL.setCurrentBasicBlock(BB);
4226 // Emit the code
4227 SDL.visitJumpTable(JT);
4228 SDAG.setRoot(SDL.getRoot());
4229 CodeGenAndEmitDAG(SDAG);
4230 // Update PHI Nodes
4231 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4232 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4233 MachineBasicBlock *PHIBB = PHI->getParent();
4234 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4235 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004236 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004237 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004238 PHI->addMachineBasicBlockOperand(RangeBB);
4239 }
4240 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004241 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004242 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004243 }
4244 }
4245 return;
4246 }
4247
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004248 // If the switch block involved a branch to one of the actual successors, we
4249 // need to update PHI nodes in that block.
4250 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4251 MachineInstr *PHI = PHINodesToUpdate[i].first;
4252 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4253 "This is not a machine PHI node that we are updating!");
4254 if (BB->isSuccessor(PHI->getParent())) {
4255 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4256 PHI->addMachineBasicBlockOperand(BB);
4257 }
4258 }
4259
Nate Begemanf15485a2006-03-27 01:32:24 +00004260 // If we generated any switch lowering information, build and codegen any
4261 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004262 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004263 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004264 CurDAG = &SDAG;
4265 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004266
Nate Begemanf15485a2006-03-27 01:32:24 +00004267 // Set the current basic block to the mbb we wish to insert the code into
4268 BB = SwitchCases[i].ThisBB;
4269 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004270
Nate Begemanf15485a2006-03-27 01:32:24 +00004271 // Emit the code
4272 SDL.visitSwitchCase(SwitchCases[i]);
4273 SDAG.setRoot(SDL.getRoot());
4274 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004275
4276 // Handle any PHI nodes in successors of this chunk, as if we were coming
4277 // from the original BB before switch expansion. Note that PHI nodes can
4278 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4279 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004280 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004281 for (MachineBasicBlock::iterator Phi = BB->begin();
4282 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4283 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4284 for (unsigned pn = 0; ; ++pn) {
4285 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4286 if (PHINodesToUpdate[pn].first == Phi) {
4287 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4288 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4289 break;
4290 }
4291 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004292 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004293
4294 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004295 if (BB == SwitchCases[i].FalseBB)
4296 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004297
4298 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004299 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004300 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004301 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004302 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004303 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004304}
Evan Chenga9c20912006-01-21 02:32:06 +00004305
Jim Laskey13ec7022006-08-01 14:21:23 +00004306
Evan Chenga9c20912006-01-21 02:32:06 +00004307//===----------------------------------------------------------------------===//
4308/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4309/// target node in the graph.
4310void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4311 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004312
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004313 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004314
4315 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004316 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004317 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004318 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004319
Jim Laskey9ff542f2006-08-01 18:29:48 +00004320 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004321 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004322 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004323}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004324
Chris Lattner03fc53c2006-03-06 00:22:00 +00004325
Jim Laskey9ff542f2006-08-01 18:29:48 +00004326HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4327 return new HazardRecognizer();
4328}
4329
Chris Lattner75548062006-10-11 03:58:02 +00004330//===----------------------------------------------------------------------===//
4331// Helper functions used by the generated instruction selector.
4332//===----------------------------------------------------------------------===//
4333// Calls to these methods are generated by tblgen.
4334
4335/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4336/// the dag combiner simplified the 255, we still want to match. RHS is the
4337/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4338/// specified in the .td file (e.g. 255).
4339bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4340 int64_t DesiredMaskS) {
4341 uint64_t ActualMask = RHS->getValue();
4342 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4343
4344 // If the actual mask exactly matches, success!
4345 if (ActualMask == DesiredMask)
4346 return true;
4347
4348 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4349 if (ActualMask & ~DesiredMask)
4350 return false;
4351
4352 // Otherwise, the DAG Combiner may have proven that the value coming in is
4353 // either already zero or is not demanded. Check for known zero input bits.
4354 uint64_t NeededMask = DesiredMask & ~ActualMask;
4355 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4356 return true;
4357
4358 // TODO: check to see if missing bits are just not demanded.
4359
4360 // Otherwise, this pattern doesn't match.
4361 return false;
4362}
4363
4364/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4365/// the dag combiner simplified the 255, we still want to match. RHS is the
4366/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4367/// specified in the .td file (e.g. 255).
4368bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4369 int64_t DesiredMaskS) {
4370 uint64_t ActualMask = RHS->getValue();
4371 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4372
4373 // If the actual mask exactly matches, success!
4374 if (ActualMask == DesiredMask)
4375 return true;
4376
4377 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4378 if (ActualMask & ~DesiredMask)
4379 return false;
4380
4381 // Otherwise, the DAG Combiner may have proven that the value coming in is
4382 // either already zero or is not demanded. Check for known zero input bits.
4383 uint64_t NeededMask = DesiredMask & ~ActualMask;
4384
4385 uint64_t KnownZero, KnownOne;
4386 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4387
4388 // If all the missing bits in the or are already known to be set, match!
4389 if ((NeededMask & KnownOne) == NeededMask)
4390 return true;
4391
4392 // TODO: check to see if missing bits are just not demanded.
4393
4394 // Otherwise, this pattern doesn't match.
4395 return false;
4396}
4397
Jim Laskey9ff542f2006-08-01 18:29:48 +00004398
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004399/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4400/// by tblgen. Others should not call it.
4401void SelectionDAGISel::
4402SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4403 std::vector<SDOperand> InOps;
4404 std::swap(InOps, Ops);
4405
4406 Ops.push_back(InOps[0]); // input chain.
4407 Ops.push_back(InOps[1]); // input asm string.
4408
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004409 unsigned i = 2, e = InOps.size();
4410 if (InOps[e-1].getValueType() == MVT::Flag)
4411 --e; // Don't process a flag operand if it is here.
4412
4413 while (i != e) {
4414 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4415 if ((Flags & 7) != 4 /*MEM*/) {
4416 // Just skip over this operand, copying the operands verbatim.
4417 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4418 i += (Flags >> 3) + 1;
4419 } else {
4420 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4421 // Otherwise, this is a memory operand. Ask the target to select it.
4422 std::vector<SDOperand> SelOps;
4423 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004424 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004425 exit(1);
4426 }
4427
4428 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004429 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4430 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004431 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4432 i += 2;
4433 }
4434 }
4435
4436 // Add the flag input back if present.
4437 if (e != InOps.size())
4438 Ops.push_back(InOps.back());
4439}