blob: cb408e18a3b5e303e29ff815a5b088000c373c1a [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 Laskeyb2efb852006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000074namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey9ff542f2006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner864635a2006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000134 };
135}
Evan Cheng4ef10862006-01-23 07:01:07 +0000136
Chris Lattner1c08c712005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattner571e4342006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000190
Chris Lattner3c384492006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattnerbf209482005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner1c08c712005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000246 unsigned Align =
Owen Andersona69571c2006-05-03 01:29:57 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(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 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000254 //
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000258 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 }
263
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
270
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
276 MBBMap[BB] = MBB;
277 MF.getBasicBlockList().push_back(MBB);
278
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
280 // appropriate.
281 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
284
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
289 else {
290 MVT::ValueType VT1,VT2;
291 NumElements =
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
293 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000294 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000297 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000298 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000299 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000300 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000301 }
302}
303
Chris Lattner3c384492006-03-16 19:51:18 +0000304/// CreateRegForValue - Allocate the appropriate number of virtual registers of
305/// the correctly promoted or expanded types. Assign these registers
306/// consecutive vreg numbers and return the first assigned number.
307unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308 MVT::ValueType VT = TLI.getValueType(V->getType());
309
310 // The number of multiples of registers that we need, to, e.g., split up
311 // a <2 x int64> -> 4 x i32 registers.
312 unsigned NumVectorRegs = 1;
313
314 // If this is a packed type, figure out what type it will decompose into
315 // and how many of the elements it will use.
316 if (VT == MVT::Vector) {
317 const PackedType *PTy = cast<PackedType>(V->getType());
318 unsigned NumElts = PTy->getNumElements();
319 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
323 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
324 NumElts >>= 1;
325 NumVectorRegs <<= 1;
326 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000327 if (NumElts == 1)
328 VT = EltTy;
329 else
330 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000331 }
332
333 // The common case is that we will only create one register for this
334 // value. If we have that case, create and return the virtual register.
335 unsigned NV = TLI.getNumElements(VT);
336 if (NV == 1) {
337 // If we are promoting this value, pick the next largest supported type.
338 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339 unsigned Reg = MakeReg(PromotedType);
340 // If this is a vector of supported or promoted types (e.g. 4 x i16),
341 // create all of the registers.
342 for (unsigned i = 1; i != NumVectorRegs; ++i)
343 MakeReg(PromotedType);
344 return Reg;
345 }
346
347 // If this value is represented with multiple target registers, make sure
348 // to create enough consecutive registers of the right (smaller) type.
349 unsigned NT = VT-1; // Find the type to use.
350 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
351 --NT;
352
353 unsigned R = MakeReg((MVT::ValueType)NT);
354 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
355 MakeReg((MVT::ValueType)NT);
356 return R;
357}
Chris Lattner1c08c712005-01-07 07:47:53 +0000358
359//===----------------------------------------------------------------------===//
360/// SelectionDAGLowering - This is the common target-independent lowering
361/// implementation that is parameterized by a TargetLowering object.
362/// Also, targets can overload any lowering method.
363///
364namespace llvm {
365class SelectionDAGLowering {
366 MachineBasicBlock *CurMBB;
367
368 std::map<const Value*, SDOperand> NodeMap;
369
Chris Lattnerd3948112005-01-17 22:19:26 +0000370 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
371 /// them up and then emit token factor nodes when possible. This allows us to
372 /// get simple disambiguation between loads without worrying about alias
373 /// analysis.
374 std::vector<SDOperand> PendingLoads;
375
Nate Begemanf15485a2006-03-27 01:32:24 +0000376 /// Case - A pair of values to record the Value for a switch case, and the
377 /// case's target basic block.
378 typedef std::pair<Constant*, MachineBasicBlock*> Case;
379 typedef std::vector<Case>::iterator CaseItr;
380 typedef std::pair<CaseItr, CaseItr> CaseRange;
381
382 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
383 /// of conditional branches.
384 struct CaseRec {
385 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
386 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
387
388 /// CaseBB - The MBB in which to emit the compare and branch
389 MachineBasicBlock *CaseBB;
390 /// LT, GE - If nonzero, we know the current case value must be less-than or
391 /// greater-than-or-equal-to these Constants.
392 Constant *LT;
393 Constant *GE;
394 /// Range - A pair of iterators representing the range of case values to be
395 /// processed at this point in the binary search tree.
396 CaseRange Range;
397 };
398
399 /// The comparison function for sorting Case values.
400 struct CaseCmp {
401 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000402 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
403 if (I1->getType()->isUnsigned())
404 return I1->getZExtValue() <
405 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000406
Reid Spencerb83eb642006-10-20 07:07:24 +0000407 return cast<const ConstantInt>(C1.first)->getSExtValue() <
408 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000409 }
410 };
411
Chris Lattner1c08c712005-01-07 07:47:53 +0000412public:
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
416 TargetLowering &TLI;
417 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000418 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000419
Nate Begemanf15485a2006-03-27 01:32:24 +0000420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000423 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000424
Chris Lattner1c08c712005-01-07 07:47:53 +0000425 /// FuncInfo - Information about the function as a whole.
426 ///
427 FunctionLoweringInfo &FuncInfo;
428
429 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000430 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000432 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 }
434
Chris Lattnera651cf62005-01-17 19:43:36 +0000435 /// getRoot - Return the current virtual root of the Selection DAG.
436 ///
437 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000438 if (PendingLoads.empty())
439 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000440
Chris Lattnerd3948112005-01-17 22:19:26 +0000441 if (PendingLoads.size() == 1) {
442 SDOperand Root = PendingLoads[0];
443 DAG.setRoot(Root);
444 PendingLoads.clear();
445 return Root;
446 }
447
448 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000449 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
450 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000451 PendingLoads.clear();
452 DAG.setRoot(Root);
453 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000454 }
455
Chris Lattner571e4342006-10-27 21:36:01 +0000456 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457
Chris Lattner1c08c712005-01-07 07:47:53 +0000458 void visit(Instruction &I) { visit(I.getOpcode(), I); }
459
460 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000461 // Note: this doesn't use InstVisitor, because it has to work with
462 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000463 switch (Opcode) {
464 default: assert(0 && "Unknown instruction type encountered!");
465 abort();
466 // Build the switch statement using the Instruction.def file.
467#define HANDLE_INST(NUM, OPCODE, CLASS) \
468 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
469#include "llvm/Instruction.def"
470 }
471 }
472
473 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000475 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000476 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000477 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000478
479 SDOperand getIntPtrConstant(uint64_t Val) {
480 return DAG.getConstant(Val, TLI.getPointerTy());
481 }
482
Chris Lattner199862b2006-03-16 19:57:50 +0000483 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000484
485 const SDOperand &setValue(const Value *V, SDOperand NewN) {
486 SDOperand &N = NodeMap[V];
487 assert(N.Val == 0 && "Already set a value for this node!");
488 return N = NewN;
489 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000490
Chris Lattner864635a2006-02-22 22:37:12 +0000491 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 MVT::ValueType VT,
493 bool OutReg, bool InReg,
494 std::set<unsigned> &OutputRegs,
495 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000496
Chris Lattner571e4342006-10-27 21:36:01 +0000497 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
498 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000500 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000501 void ExportFromCurrentBlock(Value *V);
502
Chris Lattner1c08c712005-01-07 07:47:53 +0000503 // Terminator instructions.
504 void visitRet(ReturnInst &I);
505 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000506 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000507 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508
Nate Begemanf15485a2006-03-27 01:32:24 +0000509 // Helper for visitSwitch
510 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000511 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000512
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000514 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
515 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
516
Reid Spencer1628cec2006-10-26 06:15:43 +0000517 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
518 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000519 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000520 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000521 if (I.getType()->isFloatingPoint())
522 visitFPBinary(I, ISD::FADD, ISD::VADD);
523 else
524 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000525 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000526 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000527 void visitMul(User &I) {
528 if (I.getType()->isFloatingPoint())
529 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
530 else
531 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000532 }
Reid Spencer0a783f72006-11-02 01:53:59 +0000533 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
534 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
535 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000536 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
537 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer0a783f72006-11-02 01:53:59 +0000538 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000539 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
540 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
541 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000542 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000543 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
544 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000545 void visitICmp(User &I);
546 void visitFCmp(User &I);
Evan Chengf6f95812006-05-23 06:40:47 +0000547 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
548 ISD::CondCode FPOpc);
549 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
550 ISD::SETOEQ); }
551 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
552 ISD::SETUNE); }
553 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
554 ISD::SETOLE); }
555 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
556 ISD::SETOGE); }
557 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
558 ISD::SETOLT); }
559 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
560 ISD::SETOGT); }
Reid Spencer3da59db2006-11-27 01:05:10 +0000561 // Visit the conversion instructions
562 void visitTrunc(User &I);
563 void visitZExt(User &I);
564 void visitSExt(User &I);
565 void visitFPTrunc(User &I);
566 void visitFPExt(User &I);
567 void visitFPToUI(User &I);
568 void visitFPToSI(User &I);
569 void visitUIToFP(User &I);
570 void visitSIToFP(User &I);
571 void visitPtrToInt(User &I);
572 void visitIntToPtr(User &I);
573 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000574
Chris Lattner2bbd8102006-03-29 00:11:43 +0000575 void visitExtractElement(User &I);
576 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000577 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000578
Chris Lattner1c08c712005-01-07 07:47:53 +0000579 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000581
582 void visitMalloc(MallocInst &I);
583 void visitFree(FreeInst &I);
584 void visitAlloca(AllocaInst &I);
585 void visitLoad(LoadInst &I);
586 void visitStore(StoreInst &I);
587 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
588 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000589 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000590 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000591 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000592
Chris Lattner1c08c712005-01-07 07:47:53 +0000593 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000594 void visitVAArg(VAArgInst &I);
595 void visitVAEnd(CallInst &I);
596 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000597 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000598
Chris Lattner7041ee32005-01-11 05:56:49 +0000599 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
601 void visitUserOp1(Instruction &I) {
602 assert(0 && "UserOp1 should not exist at instruction selection time!");
603 abort();
604 }
605 void visitUserOp2(Instruction &I) {
606 assert(0 && "UserOp2 should not exist at instruction selection time!");
607 abort();
608 }
609};
610} // end namespace llvm
611
Chris Lattner199862b2006-03-16 19:57:50 +0000612SDOperand SelectionDAGLowering::getValue(const Value *V) {
613 SDOperand &N = NodeMap[V];
614 if (N.Val) return N;
615
616 const Type *VTy = V->getType();
617 MVT::ValueType VT = TLI.getValueType(VTy);
618 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
619 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
620 visit(CE->getOpcode(), *CE);
621 assert(N.Val && "visit didn't populate the ValueMap!");
622 return N;
623 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
624 return N = DAG.getGlobalAddress(GV, VT);
625 } else if (isa<ConstantPointerNull>(C)) {
626 return N = DAG.getConstant(0, TLI.getPointerTy());
627 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000628 if (!isa<PackedType>(VTy))
629 return N = DAG.getNode(ISD::UNDEF, VT);
630
Chris Lattnerb2827b02006-03-19 00:52:58 +0000631 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000632 const PackedType *PTy = cast<PackedType>(VTy);
633 unsigned NumElements = PTy->getNumElements();
634 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
635
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000636 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000637 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
638
639 // Create a VConstant node with generic Vector type.
640 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
641 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000642 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
643 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000644 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
645 return N = DAG.getConstantFP(CFP->getValue(), VT);
646 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
647 unsigned NumElements = PTy->getNumElements();
648 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000649
650 // Now that we know the number and type of the elements, push a
651 // Constant or ConstantFP node onto the ops list for each element of
652 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000653 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000654 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000655 for (unsigned i = 0; i != NumElements; ++i)
656 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000657 } else {
658 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
659 SDOperand Op;
660 if (MVT::isFloatingPoint(PVT))
661 Op = DAG.getConstantFP(0, PVT);
662 else
663 Op = DAG.getConstant(0, PVT);
664 Ops.assign(NumElements, Op);
665 }
666
Chris Lattnerb2827b02006-03-19 00:52:58 +0000667 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000668 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
669 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000670 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000671 } else {
672 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000673 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000674 }
675 }
676
677 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
678 std::map<const AllocaInst*, int>::iterator SI =
679 FuncInfo.StaticAllocaMap.find(AI);
680 if (SI != FuncInfo.StaticAllocaMap.end())
681 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
682 }
683
684 std::map<const Value*, unsigned>::const_iterator VMI =
685 FuncInfo.ValueMap.find(V);
686 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
687
688 unsigned InReg = VMI->second;
689
690 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000691 if (VT != MVT::Vector) {
692 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000693
Chris Lattner70c2a612006-03-31 02:06:56 +0000694 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
695 if (DestVT < VT) {
696 // Source must be expanded. This input value is actually coming from the
697 // register pair VMI->second and VMI->second+1.
698 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
699 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
700 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000701 if (MVT::isFloatingPoint(VT))
702 N = DAG.getNode(ISD::FP_ROUND, VT, N);
703 else
704 N = DAG.getNode(ISD::TRUNCATE, VT, N);
705 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000706 } else {
707 // Otherwise, if this is a vector, make it available as a generic vector
708 // here.
709 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000710 const PackedType *PTy = cast<PackedType>(VTy);
711 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000712 PTyLegalElementVT);
713
714 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000715 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000716 if (PTyElementVT == PTyLegalElementVT) {
717 // If the value types are legal, just VBUILD the CopyFromReg nodes.
718 for (unsigned i = 0; i != NE; ++i)
719 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
720 PTyElementVT));
721 } else if (PTyElementVT < PTyLegalElementVT) {
722 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
723 for (unsigned i = 0; i != NE; ++i) {
724 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
725 PTyElementVT);
726 if (MVT::isFloatingPoint(PTyElementVT))
727 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
728 else
729 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
730 Ops.push_back(Op);
731 }
732 } else {
733 // If the register was expanded, use BUILD_PAIR.
734 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
735 for (unsigned i = 0; i != NE/2; ++i) {
736 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
737 PTyElementVT);
738 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
739 PTyElementVT);
740 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
741 }
742 }
743
744 Ops.push_back(DAG.getConstant(NE, MVT::i32));
745 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000746 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000747
748 // Finally, use a VBIT_CONVERT to make this available as the appropriate
749 // vector type.
750 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
751 DAG.getConstant(PTy->getNumElements(),
752 MVT::i32),
753 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000754 }
755
756 return N;
757}
758
759
Chris Lattner1c08c712005-01-07 07:47:53 +0000760void SelectionDAGLowering::visitRet(ReturnInst &I) {
761 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000762 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000763 return;
764 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000765 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000766 NewValues.push_back(getRoot());
767 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
768 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000769 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000770
771 // If this is an integer return value, we need to promote it ourselves to
772 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
773 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000774 // FIXME: C calling convention requires the return type to be promoted to
775 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000776 if (MVT::isInteger(RetOp.getValueType()) &&
777 RetOp.getValueType() < MVT::i64) {
778 MVT::ValueType TmpVT;
779 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
780 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
781 else
782 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000783
Evan Cheng8e7d0562006-05-26 23:09:09 +0000784 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000785 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
786 else
787 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
788 }
789 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000790 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000791 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000792 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
793 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000794}
795
Chris Lattner571e4342006-10-27 21:36:01 +0000796/// ExportFromCurrentBlock - If this condition isn't known to be exported from
797/// the current basic block, add it to ValueMap now so that we'll get a
798/// CopyTo/FromReg.
799void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
800 // No need to export constants.
801 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
802
803 // Already exported?
804 if (FuncInfo.isExportedInst(V)) return;
805
806 unsigned Reg = FuncInfo.InitializeRegForValue(V);
807 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
808}
809
Chris Lattner8c494ab2006-10-27 23:50:33 +0000810bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
811 const BasicBlock *FromBB) {
812 // The operands of the setcc have to be in this block. We don't know
813 // how to export them from some other block.
814 if (Instruction *VI = dyn_cast<Instruction>(V)) {
815 // Can export from current BB.
816 if (VI->getParent() == FromBB)
817 return true;
818
819 // Is already exported, noop.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // If this is an argument, we can export it if the BB is the entry block or
824 // if it is already exported.
825 if (isa<Argument>(V)) {
826 if (FromBB == &FromBB->getParent()->getEntryBlock())
827 return true;
828
829 // Otherwise, can only export this if it is already exported.
830 return FuncInfo.isExportedInst(V);
831 }
832
833 // Otherwise, constants can always be exported.
834 return true;
835}
836
Chris Lattner6a586c82006-10-29 21:01:20 +0000837static bool InBlock(const Value *V, const BasicBlock *BB) {
838 if (const Instruction *I = dyn_cast<Instruction>(V))
839 return I->getParent() == BB;
840 return true;
841}
842
Chris Lattner571e4342006-10-27 21:36:01 +0000843/// FindMergedConditions - If Cond is an expression like
844void SelectionDAGLowering::FindMergedConditions(Value *Cond,
845 MachineBasicBlock *TBB,
846 MachineBasicBlock *FBB,
847 MachineBasicBlock *CurBB,
848 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000849 // If this node is not part of the or/and tree, emit it as a branch.
850 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
851
852 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000853 BOp->getParent() != CurBB->getBasicBlock() ||
854 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
855 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000856 const BasicBlock *BB = CurBB->getBasicBlock();
857
Chris Lattnerdf19f272006-10-31 22:37:42 +0000858 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
859 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
860 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
861 // The operands of the setcc have to be in this block. We don't know
862 // how to export them from some other block. If this is the first
863 // block of the sequence, no exporting is needed.
864 (CurBB == CurMBB ||
865 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
866 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
867 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
868 II->getOperand(2), TBB, FBB, CurBB);
869 SwitchCases.push_back(CB);
870 return;
871 }
872
873
Chris Lattner571e4342006-10-27 21:36:01 +0000874 // If the leaf of the tree is a setcond inst, merge the condition into the
875 // caseblock.
876 if (BOp && isa<SetCondInst>(BOp) &&
877 // The operands of the setcc have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000878 // how to export them from some other block. If this is the first block
879 // of the sequence, no exporting is needed.
880 (CurBB == CurMBB ||
881 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
882 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Chris Lattner571e4342006-10-27 21:36:01 +0000883 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
884 switch (BOp->getOpcode()) {
885 default: assert(0 && "Unknown setcc opcode!");
886 case Instruction::SetEQ:
887 SignCond = ISD::SETEQ;
888 UnsCond = ISD::SETEQ;
889 FPCond = ISD::SETOEQ;
890 break;
891 case Instruction::SetNE:
892 SignCond = ISD::SETNE;
893 UnsCond = ISD::SETNE;
894 FPCond = ISD::SETUNE;
895 break;
896 case Instruction::SetLE:
897 SignCond = ISD::SETLE;
898 UnsCond = ISD::SETULE;
899 FPCond = ISD::SETOLE;
900 break;
901 case Instruction::SetGE:
902 SignCond = ISD::SETGE;
903 UnsCond = ISD::SETUGE;
904 FPCond = ISD::SETOGE;
905 break;
906 case Instruction::SetLT:
907 SignCond = ISD::SETLT;
908 UnsCond = ISD::SETULT;
909 FPCond = ISD::SETOLT;
910 break;
911 case Instruction::SetGT:
912 SignCond = ISD::SETGT;
913 UnsCond = ISD::SETUGT;
914 FPCond = ISD::SETOGT;
915 break;
916 }
917
918 const Type *OpType = BOp->getOperand(0)->getType();
919 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
920 OpType = PTy->getElementType();
921
922 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
923 Condition = FPCond;
924 else if (OpType->isUnsigned())
925 Condition = UnsCond;
926 else
927 Condition = SignCond;
928
929 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
930 BOp->getOperand(1), TBB, FBB, CurBB);
931 SwitchCases.push_back(CB);
932 return;
933 }
934
935 // Create a CaseBlock record representing this branch.
936 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
937 TBB, FBB, CurBB);
938 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000939 return;
940 }
941
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000942
943 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000944 MachineFunction::iterator BBI = CurBB;
945 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
946 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
947
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000948 if (Opc == Instruction::Or) {
949 // Codegen X | Y as:
950 // jmp_if_X TBB
951 // jmp TmpBB
952 // TmpBB:
953 // jmp_if_Y TBB
954 // jmp FBB
955 //
Chris Lattner571e4342006-10-27 21:36:01 +0000956
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000957 // Emit the LHS condition.
958 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
959
960 // Emit the RHS condition into TmpBB.
961 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
962 } else {
963 assert(Opc == Instruction::And && "Unknown merge op!");
964 // Codegen X & Y as:
965 // jmp_if_X TmpBB
966 // jmp FBB
967 // TmpBB:
968 // jmp_if_Y TBB
969 // jmp FBB
970 //
971 // This requires creation of TmpBB after CurBB.
972
973 // Emit the LHS condition.
974 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
975
976 // Emit the RHS condition into TmpBB.
977 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
978 }
Chris Lattner571e4342006-10-27 21:36:01 +0000979}
980
Chris Lattnerdf19f272006-10-31 22:37:42 +0000981/// If the set of cases should be emitted as a series of branches, return true.
982/// If we should emit this as a bunch of and/or'd together conditions, return
983/// false.
984static bool
985ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
986 if (Cases.size() != 2) return true;
987
Chris Lattner0ccb5002006-10-31 23:06:00 +0000988 // If this is two comparisons of the same values or'd or and'd together, they
989 // will get folded into a single comparison, so don't emit two blocks.
990 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
991 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
992 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
993 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
994 return false;
995 }
996
Chris Lattnerdf19f272006-10-31 22:37:42 +0000997 return true;
998}
999
Chris Lattner1c08c712005-01-07 07:47:53 +00001000void SelectionDAGLowering::visitBr(BranchInst &I) {
1001 // Update machine-CFG edges.
1002 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001003
1004 // Figure out which block is immediately after the current one.
1005 MachineBasicBlock *NextBlock = 0;
1006 MachineFunction::iterator BBI = CurMBB;
1007 if (++BBI != CurMBB->getParent()->end())
1008 NextBlock = BBI;
1009
1010 if (I.isUnconditional()) {
1011 // If this is not a fall-through branch, emit the branch.
1012 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001013 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001014 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001015
Chris Lattner57ab6592006-10-24 17:57:59 +00001016 // Update machine-CFG edges.
1017 CurMBB->addSuccessor(Succ0MBB);
1018
1019 return;
1020 }
1021
1022 // If this condition is one of the special cases we handle, do special stuff
1023 // now.
1024 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001025 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001026
1027 // If this is a series of conditions that are or'd or and'd together, emit
1028 // this as a sequence of branches instead of setcc's with and/or operations.
1029 // For example, instead of something like:
1030 // cmp A, B
1031 // C = seteq
1032 // cmp D, E
1033 // F = setle
1034 // or C, F
1035 // jnz foo
1036 // Emit:
1037 // cmp A, B
1038 // je foo
1039 // cmp D, E
1040 // jle foo
1041 //
1042 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1043 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001044 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001045 BOp->getOpcode() == Instruction::Or)) {
1046 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001047 // If the compares in later blocks need to use values not currently
1048 // exported from this block, export them now. This block should always
1049 // be the first entry.
1050 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1051
Chris Lattnerdf19f272006-10-31 22:37:42 +00001052 // Allow some cases to be rejected.
1053 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001054 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1055 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1056 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1057 }
1058
1059 // Emit the branch for this block.
1060 visitSwitchCase(SwitchCases[0]);
1061 SwitchCases.erase(SwitchCases.begin());
1062 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001063 }
1064
Chris Lattner0ccb5002006-10-31 23:06:00 +00001065 // Okay, we decided not to do this, remove any inserted MBB's and clear
1066 // SwitchCases.
1067 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1068 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1069
Chris Lattnerdf19f272006-10-31 22:37:42 +00001070 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001071 }
1072 }
Chris Lattner24525952006-10-24 18:07:37 +00001073
1074 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +00001075 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001076 Succ0MBB, Succ1MBB, CurMBB);
1077 // Use visitSwitchCase to actually insert the fast branch sequence for this
1078 // cond branch.
1079 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001080}
1081
Nate Begemanf15485a2006-03-27 01:32:24 +00001082/// visitSwitchCase - Emits the necessary code to represent a single node in
1083/// the binary search tree resulting from lowering a switch instruction.
1084void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001085 SDOperand Cond;
1086 SDOperand CondLHS = getValue(CB.CmpLHS);
1087
Chris Lattner571e4342006-10-27 21:36:01 +00001088 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1089 // handle common cases produced by branch lowering.
1090 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001091 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +00001092 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1093 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1094 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1095 } else
1096 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001097
1098 // Set NextBlock to be the MBB immediately after the current one, if any.
1099 // This is used to avoid emitting unnecessary branches to the next block.
1100 MachineBasicBlock *NextBlock = 0;
1101 MachineFunction::iterator BBI = CurMBB;
1102 if (++BBI != CurMBB->getParent()->end())
1103 NextBlock = BBI;
1104
1105 // If the lhs block is the next block, invert the condition so that we can
1106 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001107 if (CB.TrueBB == NextBlock) {
1108 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001109 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1110 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1111 }
1112 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001113 DAG.getBasicBlock(CB.TrueBB));
1114 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001115 DAG.setRoot(BrCond);
1116 else
1117 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001118 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001119 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001120 CurMBB->addSuccessor(CB.TrueBB);
1121 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001122}
1123
Nate Begeman37efe672006-04-22 18:53:45 +00001124void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001125 // Emit the code for the jump table
1126 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001127 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1128 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1129 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1130 Table, Index));
1131 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001132}
1133
Nate Begemanf15485a2006-03-27 01:32:24 +00001134void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1135 // Figure out which block is immediately after the current one.
1136 MachineBasicBlock *NextBlock = 0;
1137 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001138
Nate Begemanf15485a2006-03-27 01:32:24 +00001139 if (++BBI != CurMBB->getParent()->end())
1140 NextBlock = BBI;
1141
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001142 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1143
Nate Begemanf15485a2006-03-27 01:32:24 +00001144 // If there is only the default destination, branch to it if it is not the
1145 // next basic block. Otherwise, just fall through.
1146 if (I.getNumOperands() == 2) {
1147 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001148
Nate Begemanf15485a2006-03-27 01:32:24 +00001149 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001150 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001151 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001152 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001153
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001154 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001155 return;
1156 }
1157
1158 // If there are any non-default case statements, create a vector of Cases
1159 // representing each one, and sort the vector so that we can efficiently
1160 // create a binary search tree from them.
1161 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001162
Nate Begemanf15485a2006-03-27 01:32:24 +00001163 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1164 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1165 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1166 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001167
Nate Begemanf15485a2006-03-27 01:32:24 +00001168 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1169
1170 // Get the Value to be switched on and default basic blocks, which will be
1171 // inserted into CaseBlock records, representing basic blocks in the binary
1172 // search tree.
1173 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001174
1175 // Get the MachineFunction which holds the current MBB. This is used during
1176 // emission of jump tables, and when inserting any additional MBBs necessary
1177 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001178 MachineFunction *CurMF = CurMBB->getParent();
1179 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001180
1181 // If the switch has few cases (two or less) emit a series of specific
1182 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001183 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001184 // TODO: If any two of the cases has the same destination, and if one value
1185 // is the same as the other, but has one bit unset that the other has set,
1186 // use bit manipulation to do two compares at once. For example:
1187 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1188
Chris Lattnerb3543432006-10-23 18:38:22 +00001189 // Rearrange the case blocks so that the last one falls through if possible.
1190 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1191 // The last case block won't fall through into 'NextBlock' if we emit the
1192 // branches in this order. See if rearranging a case value would help.
1193 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1194 if (Cases[i].second == NextBlock) {
1195 std::swap(Cases[i], Cases.back());
1196 break;
1197 }
1198 }
1199 }
1200
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001201 // Create a CaseBlock record representing a conditional branch to
1202 // the Case's target mbb if the value being switched on SV is equal
1203 // to C.
1204 MachineBasicBlock *CurBlock = CurMBB;
1205 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1206 MachineBasicBlock *FallThrough;
1207 if (i != e-1) {
1208 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1209 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1210 } else {
1211 // If the last case doesn't match, go to the default block.
1212 FallThrough = Default;
1213 }
1214
1215 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1216 Cases[i].second, FallThrough, CurBlock);
1217
1218 // If emitting the first comparison, just call visitSwitchCase to emit the
1219 // code into the current block. Otherwise, push the CaseBlock onto the
1220 // vector to be later processed by SDISel, and insert the node's MBB
1221 // before the next MBB.
1222 if (CurBlock == CurMBB)
1223 visitSwitchCase(CB);
1224 else
1225 SwitchCases.push_back(CB);
1226
1227 CurBlock = FallThrough;
1228 }
1229 return;
1230 }
Nate Begeman37efe672006-04-22 18:53:45 +00001231
Nate Begeman17c275f2006-05-08 16:51:36 +00001232 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1233 // target supports indirect branches, then emit a jump table rather than
1234 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001235 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1236 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001237 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001238 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1239 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001240 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1241
Nate Begeman17c275f2006-05-08 16:51:36 +00001242 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001243 // Create a new basic block to hold the code for loading the address
1244 // of the jump table, and jumping to it. Update successor information;
1245 // we will either branch to the default case for the switch, or the jump
1246 // table.
1247 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1248 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1249 CurMBB->addSuccessor(Default);
1250 CurMBB->addSuccessor(JumpTableBB);
1251
1252 // Subtract the lowest switch case value from the value being switched on
1253 // and conditional branch to default mbb if the result is greater than the
1254 // difference between smallest and largest cases.
1255 SDOperand SwitchOp = getValue(SV);
1256 MVT::ValueType VT = SwitchOp.getValueType();
1257 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1258 DAG.getConstant(First, VT));
1259
1260 // The SDNode we just created, which holds the value being switched on
1261 // minus the the smallest case value, needs to be copied to a virtual
1262 // register so it can be used as an index into the jump table in a
1263 // subsequent basic block. This value may be smaller or larger than the
1264 // target's pointer type, and therefore require extension or truncating.
1265 if (VT > TLI.getPointerTy())
1266 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1267 else
1268 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001269
Nate Begeman37efe672006-04-22 18:53:45 +00001270 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1271 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1272
1273 // Emit the range check for the jump table, and branch to the default
1274 // block for the switch statement if the value being switched on exceeds
1275 // the largest case in the switch.
1276 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1277 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1278 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1279 DAG.getBasicBlock(Default)));
1280
Nate Begemanf4360a42006-05-03 03:48:02 +00001281 // Build a vector of destination BBs, corresponding to each target
1282 // of the jump table. If the value of the jump table slot corresponds to
1283 // a case statement, push the case's BB onto the vector, otherwise, push
1284 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001285 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001286 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001287 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001288 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001289 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001290 ++ii;
1291 } else {
1292 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001293 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001294
Chris Lattner8c494ab2006-10-27 23:50:33 +00001295 // Update successor info. Add one edge to each unique successor.
1296 // Vector bool would be better, but vector<bool> is really slow.
1297 std::vector<unsigned char> SuccsHandled;
1298 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1299
Chris Lattnerc66764c2006-09-10 06:36:57 +00001300 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001301 E = DestBBs.end(); I != E; ++I) {
1302 if (!SuccsHandled[(*I)->getNumber()]) {
1303 SuccsHandled[(*I)->getNumber()] = true;
1304 JumpTableBB->addSuccessor(*I);
1305 }
1306 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001307
1308 // Create a jump table index for this jump table, or return an existing
1309 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001310 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1311
1312 // Set the jump table information so that we can codegen it as a second
1313 // MachineBasicBlock
1314 JT.Reg = JumpTableReg;
1315 JT.JTI = JTI;
1316 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001317 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001318 return;
1319 }
1320 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001321
1322 // Push the initial CaseRec onto the worklist
1323 std::vector<CaseRec> CaseVec;
1324 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1325
1326 while (!CaseVec.empty()) {
1327 // Grab a record representing a case range to process off the worklist
1328 CaseRec CR = CaseVec.back();
1329 CaseVec.pop_back();
1330
1331 // Size is the number of Cases represented by this range. If Size is 1,
1332 // then we are processing a leaf of the binary search tree. Otherwise,
1333 // we need to pick a pivot, and push left and right ranges onto the
1334 // worklist.
1335 unsigned Size = CR.Range.second - CR.Range.first;
1336
1337 if (Size == 1) {
1338 // Create a CaseBlock record representing a conditional branch to
1339 // the Case's target mbb if the value being switched on SV is equal
1340 // to C. Otherwise, branch to default.
1341 Constant *C = CR.Range.first->first;
1342 MachineBasicBlock *Target = CR.Range.first->second;
1343 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1344 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001345
Nate Begemanf15485a2006-03-27 01:32:24 +00001346 // If the MBB representing the leaf node is the current MBB, then just
1347 // call visitSwitchCase to emit the code into the current block.
1348 // Otherwise, push the CaseBlock onto the vector to be later processed
1349 // by SDISel, and insert the node's MBB before the next MBB.
1350 if (CR.CaseBB == CurMBB)
1351 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001352 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001353 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001354 } else {
1355 // split case range at pivot
1356 CaseItr Pivot = CR.Range.first + (Size / 2);
1357 CaseRange LHSR(CR.Range.first, Pivot);
1358 CaseRange RHSR(Pivot, CR.Range.second);
1359 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001360 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001361
Nate Begemanf15485a2006-03-27 01:32:24 +00001362 // We know that we branch to the LHS if the Value being switched on is
1363 // less than the Pivot value, C. We use this to optimize our binary
1364 // tree a bit, by recognizing that if SV is greater than or equal to the
1365 // LHS's Case Value, and that Case Value is exactly one less than the
1366 // Pivot's Value, then we can branch directly to the LHS's Target,
1367 // rather than creating a leaf node for it.
1368 if ((LHSR.second - LHSR.first) == 1 &&
1369 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001370 cast<ConstantIntegral>(C)->getZExtValue() ==
1371 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001372 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001373 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001374 TrueBB = new MachineBasicBlock(LLVMBB);
1375 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1376 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001377 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001378
Nate Begemanf15485a2006-03-27 01:32:24 +00001379 // Similar to the optimization above, if the Value being switched on is
1380 // known to be less than the Constant CR.LT, and the current Case Value
1381 // is CR.LT - 1, then we can branch directly to the target block for
1382 // the current Case Value, rather than emitting a RHS leaf node for it.
1383 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001384 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1385 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001386 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001387 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001388 FalseBB = new MachineBasicBlock(LLVMBB);
1389 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1390 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001391 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001392
Nate Begemanf15485a2006-03-27 01:32:24 +00001393 // Create a CaseBlock record representing a conditional branch to
1394 // the LHS node if the value being switched on SV is less than C.
1395 // Otherwise, branch to LHS.
1396 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001397 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001398
Nate Begemanf15485a2006-03-27 01:32:24 +00001399 if (CR.CaseBB == CurMBB)
1400 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001401 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001402 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001403 }
1404 }
1405}
1406
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001407void SelectionDAGLowering::visitSub(User &I) {
1408 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001409 if (I.getType()->isFloatingPoint()) {
1410 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1411 if (CFP->isExactlyValue(-0.0)) {
1412 SDOperand Op2 = getValue(I.getOperand(1));
1413 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1414 return;
1415 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001416 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1417 } else
1418 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001419}
1420
Reid Spencer1628cec2006-10-26 06:15:43 +00001421void
1422SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001423 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001424 SDOperand Op1 = getValue(I.getOperand(0));
1425 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001426
Reid Spencer1628cec2006-10-26 06:15:43 +00001427 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001428 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1429 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1430 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001431 } else {
1432 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1433 }
1434}
1435
1436void
1437SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1438 const Type *Ty = I.getType();
1439 SDOperand Op1 = getValue(I.getOperand(0));
1440 SDOperand Op2 = getValue(I.getOperand(1));
1441
1442 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1443 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1444 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1445 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1446 } else {
1447 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001448 }
Nate Begemane21ea612005-11-18 07:42:56 +00001449}
Chris Lattner2c49f272005-01-19 22:31:21 +00001450
Nate Begemane21ea612005-11-18 07:42:56 +00001451void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1452 SDOperand Op1 = getValue(I.getOperand(0));
1453 SDOperand Op2 = getValue(I.getOperand(1));
1454
1455 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1456
Chris Lattner1c08c712005-01-07 07:47:53 +00001457 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1458}
1459
Reid Spencer45fb3f32006-11-20 01:22:35 +00001460void SelectionDAGLowering::visitICmp(User &I) {
1461 ICmpInst *IC = cast<ICmpInst>(&I);
1462 SDOperand Op1 = getValue(IC->getOperand(0));
1463 SDOperand Op2 = getValue(IC->getOperand(1));
1464 ISD::CondCode Opcode;
1465 switch (IC->getPredicate()) {
1466 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1467 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1468 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1469 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1470 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1471 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1472 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1473 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1474 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1475 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1476 default:
1477 assert(!"Invalid ICmp predicate value");
1478 Opcode = ISD::SETEQ;
1479 break;
1480 }
1481 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1482}
1483
1484void SelectionDAGLowering::visitFCmp(User &I) {
1485 FCmpInst *FC = cast<FCmpInst>(&I);
1486 SDOperand Op1 = getValue(FC->getOperand(0));
1487 SDOperand Op2 = getValue(FC->getOperand(1));
1488 ISD::CondCode Opcode;
1489 switch (FC->getPredicate()) {
1490 case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
1491 case FCmpInst::FCMP_OEQ : Opcode = ISD::SETOEQ;
1492 case FCmpInst::FCMP_OGT : Opcode = ISD::SETOGT;
1493 case FCmpInst::FCMP_OGE : Opcode = ISD::SETOGE;
1494 case FCmpInst::FCMP_OLT : Opcode = ISD::SETOLT;
1495 case FCmpInst::FCMP_OLE : Opcode = ISD::SETOLE;
1496 case FCmpInst::FCMP_ONE : Opcode = ISD::SETONE;
1497 case FCmpInst::FCMP_ORD : Opcode = ISD::SETO;
1498 case FCmpInst::FCMP_UNO : Opcode = ISD::SETUO;
1499 case FCmpInst::FCMP_UEQ : Opcode = ISD::SETUEQ;
1500 case FCmpInst::FCMP_UGT : Opcode = ISD::SETUGT;
1501 case FCmpInst::FCMP_UGE : Opcode = ISD::SETUGE;
1502 case FCmpInst::FCMP_ULT : Opcode = ISD::SETULT;
1503 case FCmpInst::FCMP_ULE : Opcode = ISD::SETULE;
1504 case FCmpInst::FCMP_UNE : Opcode = ISD::SETUNE;
1505 case FCmpInst::FCMP_TRUE : Opcode = ISD::SETTRUE;
1506 default:
1507 assert(!"Invalid FCmp predicate value");
1508 Opcode = ISD::SETFALSE;
1509 break;
1510 }
1511 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1512}
1513
Chris Lattner1c08c712005-01-07 07:47:53 +00001514void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001515 ISD::CondCode UnsignedOpcode,
1516 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001517 SDOperand Op1 = getValue(I.getOperand(0));
1518 SDOperand Op2 = getValue(I.getOperand(1));
1519 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001520 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001521 Opcode = FPOpcode;
1522 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001523 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001524 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001525}
1526
1527void SelectionDAGLowering::visitSelect(User &I) {
1528 SDOperand Cond = getValue(I.getOperand(0));
1529 SDOperand TrueVal = getValue(I.getOperand(1));
1530 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001531 if (!isa<PackedType>(I.getType())) {
1532 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1533 TrueVal, FalseVal));
1534 } else {
1535 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1536 *(TrueVal.Val->op_end()-2),
1537 *(TrueVal.Val->op_end()-1)));
1538 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001539}
1540
Reid Spencer3da59db2006-11-27 01:05:10 +00001541
1542void SelectionDAGLowering::visitTrunc(User &I) {
1543 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1544 SDOperand N = getValue(I.getOperand(0));
1545 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1546 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1547}
1548
1549void SelectionDAGLowering::visitZExt(User &I) {
1550 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1551 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1552 SDOperand N = getValue(I.getOperand(0));
1553 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1554 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1555}
1556
1557void SelectionDAGLowering::visitSExt(User &I) {
1558 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1559 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1560 SDOperand N = getValue(I.getOperand(0));
1561 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1562 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1563}
1564
1565void SelectionDAGLowering::visitFPTrunc(User &I) {
1566 // FPTrunc is never a no-op cast, no need to check
1567 SDOperand N = getValue(I.getOperand(0));
1568 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1569 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1570}
1571
1572void SelectionDAGLowering::visitFPExt(User &I){
1573 // FPTrunc is never a no-op cast, no need to check
1574 SDOperand N = getValue(I.getOperand(0));
1575 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1576 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1577}
1578
1579void SelectionDAGLowering::visitFPToUI(User &I) {
1580 // FPToUI is never a no-op cast, no need to check
1581 SDOperand N = getValue(I.getOperand(0));
1582 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1583 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1584}
1585
1586void SelectionDAGLowering::visitFPToSI(User &I) {
1587 // FPToSI is never a no-op cast, no need to check
1588 SDOperand N = getValue(I.getOperand(0));
1589 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1590 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1591}
1592
1593void SelectionDAGLowering::visitUIToFP(User &I) {
1594 // UIToFP is never a no-op cast, no need to check
1595 SDOperand N = getValue(I.getOperand(0));
1596 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1597 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1598}
1599
1600void SelectionDAGLowering::visitSIToFP(User &I){
1601 // UIToFP is never a no-op cast, no need to check
1602 SDOperand N = getValue(I.getOperand(0));
1603 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1604 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1605}
1606
1607void SelectionDAGLowering::visitPtrToInt(User &I) {
1608 // What to do depends on the size of the integer and the size of the pointer.
1609 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001610 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001611 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001612 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001613 SDOperand Result;
1614 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1615 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1616 else
1617 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1618 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1619 setValue(&I, Result);
1620}
Chris Lattner1c08c712005-01-07 07:47:53 +00001621
Reid Spencer3da59db2006-11-27 01:05:10 +00001622void SelectionDAGLowering::visitIntToPtr(User &I) {
1623 // What to do depends on the size of the integer and the size of the pointer.
1624 // We can either truncate, zero extend, or no-op, accordingly.
1625 SDOperand N = getValue(I.getOperand(0));
1626 MVT::ValueType SrcVT = N.getValueType();
1627 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1628 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1629 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1630 else
1631 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1632 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1633}
1634
1635void SelectionDAGLowering::visitBitCast(User &I) {
1636 SDOperand N = getValue(I.getOperand(0));
1637 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001638 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001639 // This is a cast to a vector from something else.
1640 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001641 const PackedType *DestTy = cast<PackedType>(I.getType());
1642 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1643 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1644 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1645 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001646 return;
1647 }
1648 MVT::ValueType SrcVT = N.getValueType();
1649 if (SrcVT == MVT::Vector) {
1650 // This is a cast from a vctor to something else.
1651 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001652 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001653 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001654 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001655
1656 // BitCast assures us that source and destination are the same size so this
1657 // is either a BIT_CONVERT or a no-op.
1658 if (DestVT != N.getValueType())
1659 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1660 else
1661 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001662}
1663
Chris Lattner2bbd8102006-03-29 00:11:43 +00001664void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001665 SDOperand InVec = getValue(I.getOperand(0));
1666 SDOperand InVal = getValue(I.getOperand(1));
1667 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1668 getValue(I.getOperand(2)));
1669
Chris Lattner2332b9f2006-03-19 01:17:20 +00001670 SDOperand Num = *(InVec.Val->op_end()-2);
1671 SDOperand Typ = *(InVec.Val->op_end()-1);
1672 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1673 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001674}
1675
Chris Lattner2bbd8102006-03-29 00:11:43 +00001676void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001677 SDOperand InVec = getValue(I.getOperand(0));
1678 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1679 getValue(I.getOperand(1)));
1680 SDOperand Typ = *(InVec.Val->op_end()-1);
1681 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1682 TLI.getValueType(I.getType()), InVec, InIdx));
1683}
Chris Lattnerc7029802006-03-18 01:44:44 +00001684
Chris Lattner3e104b12006-04-08 04:15:24 +00001685void SelectionDAGLowering::visitShuffleVector(User &I) {
1686 SDOperand V1 = getValue(I.getOperand(0));
1687 SDOperand V2 = getValue(I.getOperand(1));
1688 SDOperand Mask = getValue(I.getOperand(2));
1689
1690 SDOperand Num = *(V1.Val->op_end()-2);
1691 SDOperand Typ = *(V2.Val->op_end()-1);
1692 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1693 V1, V2, Mask, Num, Typ));
1694}
1695
1696
Chris Lattner1c08c712005-01-07 07:47:53 +00001697void SelectionDAGLowering::visitGetElementPtr(User &I) {
1698 SDOperand N = getValue(I.getOperand(0));
1699 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001700
1701 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1702 OI != E; ++OI) {
1703 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001704 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001705 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001706 if (Field) {
1707 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001708 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001709 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001710 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001711 }
1712 Ty = StTy->getElementType(Field);
1713 } else {
1714 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001715
Chris Lattner7c0104b2005-11-09 04:45:33 +00001716 // If this is a constant subscript, handle it quickly.
1717 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001718 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001719 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001720 if (CI->getType()->isSigned())
1721 Offs = (int64_t)
1722 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001723 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001724 Offs =
1725 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001726 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1727 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001728 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001729
1730 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001731 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001732 SDOperand IdxN = getValue(Idx);
1733
1734 // If the index is smaller or larger than intptr_t, truncate or extend
1735 // it.
1736 if (IdxN.getValueType() < N.getValueType()) {
1737 if (Idx->getType()->isSigned())
1738 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1739 else
1740 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1741 } else if (IdxN.getValueType() > N.getValueType())
1742 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1743
1744 // If this is a multiply by a power of two, turn it into a shl
1745 // immediately. This is a very common case.
1746 if (isPowerOf2_64(ElementSize)) {
1747 unsigned Amt = Log2_64(ElementSize);
1748 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001749 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001750 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1751 continue;
1752 }
1753
1754 SDOperand Scale = getIntPtrConstant(ElementSize);
1755 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1756 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001757 }
1758 }
1759 setValue(&I, N);
1760}
1761
1762void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1763 // If this is a fixed sized alloca in the entry block of the function,
1764 // allocate it statically on the stack.
1765 if (FuncInfo.StaticAllocaMap.count(&I))
1766 return; // getValue will auto-populate this.
1767
1768 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001769 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1770 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001771 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001772
1773 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001774 MVT::ValueType IntPtr = TLI.getPointerTy();
1775 if (IntPtr < AllocSize.getValueType())
1776 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1777 else if (IntPtr > AllocSize.getValueType())
1778 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001779
Chris Lattner68cd65e2005-01-22 23:04:37 +00001780 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001781 getIntPtrConstant(TySize));
1782
1783 // Handle alignment. If the requested alignment is less than or equal to the
1784 // stack alignment, ignore it and round the size of the allocation up to the
1785 // stack alignment size. If the size is greater than the stack alignment, we
1786 // note this in the DYNAMIC_STACKALLOC node.
1787 unsigned StackAlign =
1788 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1789 if (Align <= StackAlign) {
1790 Align = 0;
1791 // Add SA-1 to the size.
1792 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1793 getIntPtrConstant(StackAlign-1));
1794 // Mask out the low bits for alignment purposes.
1795 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1796 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1797 }
1798
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001799 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001800 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1801 MVT::Other);
1802 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001803 DAG.setRoot(setValue(&I, DSA).getValue(1));
1804
1805 // Inform the Frame Information that we have just allocated a variable-sized
1806 // object.
1807 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1808}
1809
Chris Lattner1c08c712005-01-07 07:47:53 +00001810void SelectionDAGLowering::visitLoad(LoadInst &I) {
1811 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001812
Chris Lattnerd3948112005-01-17 22:19:26 +00001813 SDOperand Root;
1814 if (I.isVolatile())
1815 Root = getRoot();
1816 else {
1817 // Do not serialize non-volatile loads against each other.
1818 Root = DAG.getRoot();
1819 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001820
Evan Cheng466685d2006-10-09 20:57:25 +00001821 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001822 Root, I.isVolatile()));
1823}
1824
1825SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001826 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001827 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001828 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001829 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001830 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001831 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1832 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001833 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001834 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001835 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001836
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001837 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001838 DAG.setRoot(L.getValue(1));
1839 else
1840 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001841
1842 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001843}
1844
1845
1846void SelectionDAGLowering::visitStore(StoreInst &I) {
1847 Value *SrcV = I.getOperand(0);
1848 SDOperand Src = getValue(SrcV);
1849 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001850 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1851 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001852}
1853
Chris Lattner0eade312006-03-24 02:22:33 +00001854/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1855/// access memory and has no other side effects at all.
1856static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1857#define GET_NO_MEMORY_INTRINSICS
1858#include "llvm/Intrinsics.gen"
1859#undef GET_NO_MEMORY_INTRINSICS
1860 return false;
1861}
1862
Chris Lattnere58a7802006-04-02 03:41:14 +00001863// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1864// have any side-effects or if it only reads memory.
1865static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1866#define GET_SIDE_EFFECT_INFO
1867#include "llvm/Intrinsics.gen"
1868#undef GET_SIDE_EFFECT_INFO
1869 return false;
1870}
1871
Chris Lattner0eade312006-03-24 02:22:33 +00001872/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1873/// node.
1874void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1875 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001876 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001877 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001878
1879 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001880 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001881 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1882 if (OnlyLoad) {
1883 // We don't need to serialize loads against other loads.
1884 Ops.push_back(DAG.getRoot());
1885 } else {
1886 Ops.push_back(getRoot());
1887 }
1888 }
Chris Lattner0eade312006-03-24 02:22:33 +00001889
1890 // Add the intrinsic ID as an integer operand.
1891 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1892
1893 // Add all operands of the call to the operand list.
1894 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1895 SDOperand Op = getValue(I.getOperand(i));
1896
1897 // If this is a vector type, force it to the right packed type.
1898 if (Op.getValueType() == MVT::Vector) {
1899 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1900 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1901
1902 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1903 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1904 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1905 }
1906
1907 assert(TLI.isTypeLegal(Op.getValueType()) &&
1908 "Intrinsic uses a non-legal type?");
1909 Ops.push_back(Op);
1910 }
1911
1912 std::vector<MVT::ValueType> VTs;
1913 if (I.getType() != Type::VoidTy) {
1914 MVT::ValueType VT = TLI.getValueType(I.getType());
1915 if (VT == MVT::Vector) {
1916 const PackedType *DestTy = cast<PackedType>(I.getType());
1917 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1918
1919 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1920 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1921 }
1922
1923 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1924 VTs.push_back(VT);
1925 }
1926 if (HasChain)
1927 VTs.push_back(MVT::Other);
1928
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001929 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1930
Chris Lattner0eade312006-03-24 02:22:33 +00001931 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001932 SDOperand Result;
1933 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001934 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1935 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001936 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001937 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1938 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001939 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001940 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1941 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001942
Chris Lattnere58a7802006-04-02 03:41:14 +00001943 if (HasChain) {
1944 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1945 if (OnlyLoad)
1946 PendingLoads.push_back(Chain);
1947 else
1948 DAG.setRoot(Chain);
1949 }
Chris Lattner0eade312006-03-24 02:22:33 +00001950 if (I.getType() != Type::VoidTy) {
1951 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1952 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1953 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1954 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1955 DAG.getValueType(EVT));
1956 }
1957 setValue(&I, Result);
1958 }
1959}
1960
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001961/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1962/// we want to emit this as a call to a named external function, return the name
1963/// otherwise lower it and return null.
1964const char *
1965SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1966 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001967 default:
1968 // By default, turn this into a target intrinsic node.
1969 visitTargetIntrinsic(I, Intrinsic);
1970 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001971 case Intrinsic::vastart: visitVAStart(I); return 0;
1972 case Intrinsic::vaend: visitVAEnd(I); return 0;
1973 case Intrinsic::vacopy: visitVACopy(I); return 0;
1974 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1975 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1976 case Intrinsic::setjmp:
1977 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1978 break;
1979 case Intrinsic::longjmp:
1980 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1981 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001982 case Intrinsic::memcpy_i32:
1983 case Intrinsic::memcpy_i64:
1984 visitMemIntrinsic(I, ISD::MEMCPY);
1985 return 0;
1986 case Intrinsic::memset_i32:
1987 case Intrinsic::memset_i64:
1988 visitMemIntrinsic(I, ISD::MEMSET);
1989 return 0;
1990 case Intrinsic::memmove_i32:
1991 case Intrinsic::memmove_i64:
1992 visitMemIntrinsic(I, ISD::MEMMOVE);
1993 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001994
Chris Lattner86cb6432005-12-13 17:40:33 +00001995 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001996 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001997 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001998 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001999 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002000
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002001 Ops[0] = getRoot();
2002 Ops[1] = getValue(SPI.getLineValue());
2003 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002004
Jim Laskey43970fe2006-03-23 18:06:46 +00002005 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002006 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002007 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2008
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002009 Ops[3] = DAG.getString(CompileUnit->getFileName());
2010 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002011
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002012 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002013 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002014
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002015 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002016 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002017 case Intrinsic::dbg_region_start: {
2018 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2019 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002020 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002021 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002022 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
2023 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002024 }
2025
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002026 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002027 }
2028 case Intrinsic::dbg_region_end: {
2029 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2030 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002031 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002032 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002033 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2034 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002035 }
2036
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002037 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002038 }
2039 case Intrinsic::dbg_func_start: {
2040 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2041 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002042 if (DebugInfo && FSI.getSubprogram() &&
2043 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002044 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002045 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2046 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002047 }
2048
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002049 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002050 }
2051 case Intrinsic::dbg_declare: {
2052 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2053 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00002054 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002055 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002056 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00002057 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002058 }
2059
2060 return 0;
2061 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002062
Reid Spencer0b118202006-01-16 21:12:35 +00002063 case Intrinsic::isunordered_f32:
2064 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002065 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2066 getValue(I.getOperand(2)), ISD::SETUO));
2067 return 0;
2068
Reid Spencer0b118202006-01-16 21:12:35 +00002069 case Intrinsic::sqrt_f32:
2070 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002071 setValue(&I, DAG.getNode(ISD::FSQRT,
2072 getValue(I.getOperand(1)).getValueType(),
2073 getValue(I.getOperand(1))));
2074 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002075 case Intrinsic::powi_f32:
2076 case Intrinsic::powi_f64:
2077 setValue(&I, DAG.getNode(ISD::FPOWI,
2078 getValue(I.getOperand(1)).getValueType(),
2079 getValue(I.getOperand(1)),
2080 getValue(I.getOperand(2))));
2081 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002082 case Intrinsic::pcmarker: {
2083 SDOperand Tmp = getValue(I.getOperand(1));
2084 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2085 return 0;
2086 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002087 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002088 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002089 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2090 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2091 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002092 setValue(&I, Tmp);
2093 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002094 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002095 }
Nate Begemand88fc032006-01-14 03:14:10 +00002096 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002097 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002098 case Intrinsic::bswap_i64:
2099 setValue(&I, DAG.getNode(ISD::BSWAP,
2100 getValue(I.getOperand(1)).getValueType(),
2101 getValue(I.getOperand(1))));
2102 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002103 case Intrinsic::cttz_i8:
2104 case Intrinsic::cttz_i16:
2105 case Intrinsic::cttz_i32:
2106 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002107 setValue(&I, DAG.getNode(ISD::CTTZ,
2108 getValue(I.getOperand(1)).getValueType(),
2109 getValue(I.getOperand(1))));
2110 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002111 case Intrinsic::ctlz_i8:
2112 case Intrinsic::ctlz_i16:
2113 case Intrinsic::ctlz_i32:
2114 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002115 setValue(&I, DAG.getNode(ISD::CTLZ,
2116 getValue(I.getOperand(1)).getValueType(),
2117 getValue(I.getOperand(1))));
2118 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002119 case Intrinsic::ctpop_i8:
2120 case Intrinsic::ctpop_i16:
2121 case Intrinsic::ctpop_i32:
2122 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002123 setValue(&I, DAG.getNode(ISD::CTPOP,
2124 getValue(I.getOperand(1)).getValueType(),
2125 getValue(I.getOperand(1))));
2126 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002127 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002128 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002129 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2130 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002131 setValue(&I, Tmp);
2132 DAG.setRoot(Tmp.getValue(1));
2133 return 0;
2134 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002135 case Intrinsic::stackrestore: {
2136 SDOperand Tmp = getValue(I.getOperand(1));
2137 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002138 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002139 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002140 case Intrinsic::prefetch:
2141 // FIXME: Currently discarding prefetches.
2142 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002143 }
2144}
2145
2146
Chris Lattner1c08c712005-01-07 07:47:53 +00002147void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002148 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002149 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002150 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002151 if (unsigned IID = F->getIntrinsicID()) {
2152 RenameFn = visitIntrinsicCall(I, IID);
2153 if (!RenameFn)
2154 return;
2155 } else { // Not an LLVM intrinsic.
2156 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002157 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2158 if (I.getNumOperands() == 3 && // Basic sanity checks.
2159 I.getOperand(1)->getType()->isFloatingPoint() &&
2160 I.getType() == I.getOperand(1)->getType() &&
2161 I.getType() == I.getOperand(2)->getType()) {
2162 SDOperand LHS = getValue(I.getOperand(1));
2163 SDOperand RHS = getValue(I.getOperand(2));
2164 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2165 LHS, RHS));
2166 return;
2167 }
2168 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002169 if (I.getNumOperands() == 2 && // Basic sanity checks.
2170 I.getOperand(1)->getType()->isFloatingPoint() &&
2171 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002172 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002173 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2174 return;
2175 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002176 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002177 if (I.getNumOperands() == 2 && // Basic sanity checks.
2178 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002179 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002180 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002181 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2182 return;
2183 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002184 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002185 if (I.getNumOperands() == 2 && // Basic sanity checks.
2186 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002187 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002188 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002189 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2190 return;
2191 }
2192 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002193 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002194 } else if (isa<InlineAsm>(I.getOperand(0))) {
2195 visitInlineAsm(I);
2196 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002197 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002198
Chris Lattner64e14b12005-01-08 22:48:57 +00002199 SDOperand Callee;
2200 if (!RenameFn)
2201 Callee = getValue(I.getOperand(0));
2202 else
2203 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00002204 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002205 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002206 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2207 Value *Arg = I.getOperand(i);
2208 SDOperand ArgNode = getValue(Arg);
2209 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2210 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002211
Nate Begeman8e21e712005-03-26 01:29:23 +00002212 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2213 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00002214
Chris Lattnercf5734d2005-01-08 19:26:18 +00002215 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00002216 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00002217 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002218 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002219 setValue(&I, Result.first);
2220 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002221}
2222
Chris Lattner864635a2006-02-22 22:37:12 +00002223SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002224 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002225 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2226 Chain = Val.getValue(1);
2227 Flag = Val.getValue(2);
2228
2229 // If the result was expanded, copy from the top part.
2230 if (Regs.size() > 1) {
2231 assert(Regs.size() == 2 &&
2232 "Cannot expand to more than 2 elts yet!");
2233 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002234 Chain = Hi.getValue(1);
2235 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002236 if (DAG.getTargetLoweringInfo().isLittleEndian())
2237 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2238 else
2239 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002240 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002241
Chris Lattnercf752aa2006-06-08 18:22:48 +00002242 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002243 // appropriate type.
2244 if (RegVT == ValueVT)
2245 return Val;
2246
Chris Lattnercf752aa2006-06-08 18:22:48 +00002247 if (MVT::isInteger(RegVT)) {
2248 if (ValueVT < RegVT)
2249 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2250 else
2251 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2252 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002253 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002254 }
Chris Lattner864635a2006-02-22 22:37:12 +00002255}
2256
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002257/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2258/// specified value into the registers specified by this object. This uses
2259/// Chain/Flag as the input and updates them for the output Chain/Flag.
2260void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002261 SDOperand &Chain, SDOperand &Flag,
2262 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002263 if (Regs.size() == 1) {
2264 // If there is a single register and the types differ, this must be
2265 // a promotion.
2266 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002267 if (MVT::isInteger(RegVT)) {
2268 if (RegVT < ValueVT)
2269 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2270 else
2271 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2272 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002273 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2274 }
2275 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2276 Flag = Chain.getValue(1);
2277 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002278 std::vector<unsigned> R(Regs);
2279 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2280 std::reverse(R.begin(), R.end());
2281
2282 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002283 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002284 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002285 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002286 Flag = Chain.getValue(1);
2287 }
2288 }
2289}
Chris Lattner864635a2006-02-22 22:37:12 +00002290
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002291/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2292/// operand list. This adds the code marker and includes the number of
2293/// values added into it.
2294void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002295 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002296 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2297 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2298 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2299}
Chris Lattner864635a2006-02-22 22:37:12 +00002300
2301/// isAllocatableRegister - If the specified register is safe to allocate,
2302/// i.e. it isn't a stack pointer or some other special register, return the
2303/// register class for the register. Otherwise, return null.
2304static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002305isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2306 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002307 MVT::ValueType FoundVT = MVT::Other;
2308 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002309 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2310 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002311 MVT::ValueType ThisVT = MVT::Other;
2312
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002313 const TargetRegisterClass *RC = *RCI;
2314 // If none of the the value types for this register class are valid, we
2315 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002316 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2317 I != E; ++I) {
2318 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002319 // If we have already found this register in a different register class,
2320 // choose the one with the largest VT specified. For example, on
2321 // PowerPC, we favor f64 register classes over f32.
2322 if (FoundVT == MVT::Other ||
2323 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2324 ThisVT = *I;
2325 break;
2326 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002327 }
2328 }
2329
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002330 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002331
Chris Lattner864635a2006-02-22 22:37:12 +00002332 // NOTE: This isn't ideal. In particular, this might allocate the
2333 // frame pointer in functions that need it (due to them not being taken
2334 // out of allocation, because a variable sized allocation hasn't been seen
2335 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002336 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2337 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002338 if (*I == Reg) {
2339 // We found a matching register class. Keep looking at others in case
2340 // we find one with larger registers that this physreg is also in.
2341 FoundRC = RC;
2342 FoundVT = ThisVT;
2343 break;
2344 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002345 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002346 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002347}
2348
2349RegsForValue SelectionDAGLowering::
2350GetRegistersForValue(const std::string &ConstrCode,
2351 MVT::ValueType VT, bool isOutReg, bool isInReg,
2352 std::set<unsigned> &OutputRegs,
2353 std::set<unsigned> &InputRegs) {
2354 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2355 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2356 std::vector<unsigned> Regs;
2357
2358 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2359 MVT::ValueType RegVT;
2360 MVT::ValueType ValueVT = VT;
2361
Chris Lattner2a821602006-11-02 01:41:49 +00002362 // If this is a constraint for a specific physical register, like {r17},
2363 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002364 if (PhysReg.first) {
2365 if (VT == MVT::Other)
2366 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002367
2368 // Get the actual register value type. This is important, because the user
2369 // may have asked for (e.g.) the AX register in i32 type. We need to
2370 // remember that AX is actually i16 to get the right extension.
2371 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002372
2373 // This is a explicit reference to a physical register.
2374 Regs.push_back(PhysReg.first);
2375
2376 // If this is an expanded reference, add the rest of the regs to Regs.
2377 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002378 TargetRegisterClass::iterator I = PhysReg.second->begin();
2379 TargetRegisterClass::iterator E = PhysReg.second->end();
2380 for (; *I != PhysReg.first; ++I)
2381 assert(I != E && "Didn't find reg!");
2382
2383 // Already added the first reg.
2384 --NumRegs; ++I;
2385 for (; NumRegs; --NumRegs, ++I) {
2386 assert(I != E && "Ran out of registers to allocate!");
2387 Regs.push_back(*I);
2388 }
2389 }
2390 return RegsForValue(Regs, RegVT, ValueVT);
2391 }
2392
Chris Lattner2a821602006-11-02 01:41:49 +00002393 // Otherwise, if this was a reference to an LLVM register class, create vregs
2394 // for this reference.
2395 std::vector<unsigned> RegClassRegs;
2396 if (PhysReg.second) {
2397 // If this is an early clobber or tied register, our regalloc doesn't know
2398 // how to maintain the constraint. If it isn't, go ahead and create vreg
2399 // and let the regalloc do the right thing.
2400 if (!isOutReg || !isInReg) {
2401 if (VT == MVT::Other)
2402 ValueVT = *PhysReg.second->vt_begin();
2403 RegVT = *PhysReg.second->vt_begin();
2404
2405 // Create the appropriate number of virtual registers.
2406 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2407 for (; NumRegs; --NumRegs)
2408 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2409
2410 return RegsForValue(Regs, RegVT, ValueVT);
2411 }
2412
2413 // Otherwise, we can't allocate it. Let the code below figure out how to
2414 // maintain these constraints.
2415 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2416
2417 } else {
2418 // This is a reference to a register class that doesn't directly correspond
2419 // to an LLVM register class. Allocate NumRegs consecutive, available,
2420 // registers from the class.
2421 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2422 }
Chris Lattner864635a2006-02-22 22:37:12 +00002423
2424 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2425 MachineFunction &MF = *CurMBB->getParent();
2426 unsigned NumAllocated = 0;
2427 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2428 unsigned Reg = RegClassRegs[i];
2429 // See if this register is available.
2430 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2431 (isInReg && InputRegs.count(Reg))) { // Already used.
2432 // Make sure we find consecutive registers.
2433 NumAllocated = 0;
2434 continue;
2435 }
2436
2437 // Check to see if this register is allocatable (i.e. don't give out the
2438 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002439 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002440 if (!RC) {
2441 // Make sure we find consecutive registers.
2442 NumAllocated = 0;
2443 continue;
2444 }
2445
2446 // Okay, this register is good, we can use it.
2447 ++NumAllocated;
2448
2449 // If we allocated enough consecutive
2450 if (NumAllocated == NumRegs) {
2451 unsigned RegStart = (i-NumAllocated)+1;
2452 unsigned RegEnd = i+1;
2453 // Mark all of the allocated registers used.
2454 for (unsigned i = RegStart; i != RegEnd; ++i) {
2455 unsigned Reg = RegClassRegs[i];
2456 Regs.push_back(Reg);
2457 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2458 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2459 }
2460
2461 return RegsForValue(Regs, *RC->vt_begin(), VT);
2462 }
2463 }
2464
2465 // Otherwise, we couldn't allocate enough registers for this.
2466 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002467}
2468
Chris Lattner864635a2006-02-22 22:37:12 +00002469
Chris Lattnerce7518c2006-01-26 22:24:51 +00002470/// visitInlineAsm - Handle a call to an InlineAsm object.
2471///
2472void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2473 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2474
2475 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2476 MVT::Other);
2477
Chris Lattner2cc2f662006-02-01 01:28:23 +00002478 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002479 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002480
2481 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2482 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2483 /// if it is a def of that register.
2484 std::vector<SDOperand> AsmNodeOperands;
2485 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2486 AsmNodeOperands.push_back(AsmStr);
2487
2488 SDOperand Chain = getRoot();
2489 SDOperand Flag;
2490
Chris Lattner4e4b5762006-02-01 18:59:47 +00002491 // We fully assign registers here at isel time. This is not optimal, but
2492 // should work. For register classes that correspond to LLVM classes, we
2493 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2494 // over the constraints, collecting fixed registers that we know we can't use.
2495 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002496 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002497 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2498 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2499 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002500
Chris Lattner1efa40f2006-02-22 00:56:39 +00002501 MVT::ValueType OpVT;
2502
2503 // Compute the value type for each operand and add it to ConstraintVTs.
2504 switch (Constraints[i].Type) {
2505 case InlineAsm::isOutput:
2506 if (!Constraints[i].isIndirectOutput) {
2507 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2508 OpVT = TLI.getValueType(I.getType());
2509 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002510 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002511 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2512 OpNum++; // Consumes a call operand.
2513 }
2514 break;
2515 case InlineAsm::isInput:
2516 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2517 OpNum++; // Consumes a call operand.
2518 break;
2519 case InlineAsm::isClobber:
2520 OpVT = MVT::Other;
2521 break;
2522 }
2523
2524 ConstraintVTs.push_back(OpVT);
2525
Chris Lattner864635a2006-02-22 22:37:12 +00002526 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2527 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002528
Chris Lattner864635a2006-02-22 22:37:12 +00002529 // Build a list of regs that this operand uses. This always has a single
2530 // element for promoted/expanded operands.
2531 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2532 false, false,
2533 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002534
2535 switch (Constraints[i].Type) {
2536 case InlineAsm::isOutput:
2537 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002538 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002539 // If this is an early-clobber output, it cannot be assigned to the same
2540 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002541 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002542 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002543 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002544 case InlineAsm::isInput:
2545 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002546 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002547 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002548 case InlineAsm::isClobber:
2549 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002550 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2551 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002552 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002553 }
2554 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002555
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002556 // Loop over all of the inputs, copying the operand values into the
2557 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002558 RegsForValue RetValRegs;
2559 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002560 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002561
Chris Lattner6656dd12006-01-31 02:03:41 +00002562 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002563 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2564 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002565
Chris Lattner2cc2f662006-02-01 01:28:23 +00002566 switch (Constraints[i].Type) {
2567 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002568 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2569 if (ConstraintCode.size() == 1) // not a physreg name.
2570 CTy = TLI.getConstraintType(ConstraintCode[0]);
2571
2572 if (CTy == TargetLowering::C_Memory) {
2573 // Memory output.
2574 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2575
2576 // Check that the operand (the address to store to) isn't a float.
2577 if (!MVT::isInteger(InOperandVal.getValueType()))
2578 assert(0 && "MATCH FAIL!");
2579
2580 if (!Constraints[i].isIndirectOutput)
2581 assert(0 && "MATCH FAIL!");
2582
2583 OpNum++; // Consumes a call operand.
2584
2585 // Extend/truncate to the right pointer type if needed.
2586 MVT::ValueType PtrType = TLI.getPointerTy();
2587 if (InOperandVal.getValueType() < PtrType)
2588 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2589 else if (InOperandVal.getValueType() > PtrType)
2590 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2591
2592 // Add information to the INLINEASM node to know about this output.
2593 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2594 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2595 AsmNodeOperands.push_back(InOperandVal);
2596 break;
2597 }
2598
2599 // Otherwise, this is a register output.
2600 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2601
Chris Lattner864635a2006-02-22 22:37:12 +00002602 // If this is an early-clobber output, or if there is an input
2603 // constraint that matches this, we need to reserve the input register
2604 // so no other inputs allocate to it.
2605 bool UsesInputRegister = false;
2606 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2607 UsesInputRegister = true;
2608
2609 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002610 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002611 RegsForValue Regs =
2612 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2613 true, UsesInputRegister,
2614 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002615 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002616 cerr << "Couldn't allocate output reg for contraint '"
2617 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002618 exit(1);
2619 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002620
Chris Lattner2cc2f662006-02-01 01:28:23 +00002621 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002622 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002623 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002624 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002625 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002626 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002627 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2628 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002629 OpNum++; // Consumes a call operand.
2630 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002631
2632 // Add information to the INLINEASM node to know that this register is
2633 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002634 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002635 break;
2636 }
2637 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002638 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002639 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002640
Chris Lattner2223aea2006-02-02 00:25:23 +00002641 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2642 // If this is required to match an output register we have already set,
2643 // just use its register.
2644 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002645
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002646 // Scan until we find the definition we already emitted of this operand.
2647 // When we find it, create a RegsForValue operand.
2648 unsigned CurOp = 2; // The first operand.
2649 for (; OperandNo; --OperandNo) {
2650 // Advance to the next operand.
2651 unsigned NumOps =
2652 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002653 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2654 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002655 "Skipped past definitions?");
2656 CurOp += (NumOps>>3)+1;
2657 }
2658
2659 unsigned NumOps =
2660 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2661 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2662 "Skipped past definitions?");
2663
2664 // Add NumOps>>3 registers to MatchedRegs.
2665 RegsForValue MatchedRegs;
2666 MatchedRegs.ValueVT = InOperandVal.getValueType();
2667 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2668 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2669 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2670 MatchedRegs.Regs.push_back(Reg);
2671 }
2672
2673 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002674 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2675 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002676 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002677 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002678 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002679
2680 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2681 if (ConstraintCode.size() == 1) // not a physreg name.
2682 CTy = TLI.getConstraintType(ConstraintCode[0]);
2683
2684 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002685 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2686 ConstraintCode[0], DAG);
2687 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002688 cerr << "Invalid operand for inline asm constraint '"
2689 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002690 exit(1);
2691 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002692
2693 // Add information to the INLINEASM node to know about this input.
2694 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2695 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2696 AsmNodeOperands.push_back(InOperandVal);
2697 break;
2698 } else if (CTy == TargetLowering::C_Memory) {
2699 // Memory input.
2700
2701 // Check that the operand isn't a float.
2702 if (!MVT::isInteger(InOperandVal.getValueType()))
2703 assert(0 && "MATCH FAIL!");
2704
2705 // Extend/truncate to the right pointer type if needed.
2706 MVT::ValueType PtrType = TLI.getPointerTy();
2707 if (InOperandVal.getValueType() < PtrType)
2708 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2709 else if (InOperandVal.getValueType() > PtrType)
2710 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2711
2712 // Add information to the INLINEASM node to know about this input.
2713 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2714 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2715 AsmNodeOperands.push_back(InOperandVal);
2716 break;
2717 }
2718
2719 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2720
2721 // Copy the input into the appropriate registers.
2722 RegsForValue InRegs =
2723 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2724 false, true, OutputRegs, InputRegs);
2725 // FIXME: should be match fail.
2726 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2727
Evan Chenga8441262006-06-15 08:11:54 +00002728 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002729
2730 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002731 break;
2732 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002733 case InlineAsm::isClobber: {
2734 RegsForValue ClobberedRegs =
2735 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2736 OutputRegs, InputRegs);
2737 // Add the clobbered value to the operand list, so that the register
2738 // allocator is aware that the physreg got clobbered.
2739 if (!ClobberedRegs.Regs.empty())
2740 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002741 break;
2742 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002743 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002744 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002745
2746 // Finish up input operands.
2747 AsmNodeOperands[0] = Chain;
2748 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2749
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002750 Chain = DAG.getNode(ISD::INLINEASM,
2751 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002752 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002753 Flag = Chain.getValue(1);
2754
Chris Lattner6656dd12006-01-31 02:03:41 +00002755 // If this asm returns a register value, copy the result from that register
2756 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002757 if (!RetValRegs.Regs.empty())
2758 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002759
Chris Lattner6656dd12006-01-31 02:03:41 +00002760 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2761
2762 // Process indirect outputs, first output all of the flagged copies out of
2763 // physregs.
2764 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002765 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002766 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002767 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2768 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002769 }
2770
2771 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002772 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002773 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002774 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002775 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002776 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002777 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002778 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2779 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002780 DAG.setRoot(Chain);
2781}
2782
2783
Chris Lattner1c08c712005-01-07 07:47:53 +00002784void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2785 SDOperand Src = getValue(I.getOperand(0));
2786
2787 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002788
2789 if (IntPtr < Src.getValueType())
2790 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2791 else if (IntPtr > Src.getValueType())
2792 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002793
2794 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002795 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002796 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2797 Src, getIntPtrConstant(ElementSize));
2798
2799 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002800 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002801
2802 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002803 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002804 DAG.getExternalSymbol("malloc", IntPtr),
2805 Args, DAG);
2806 setValue(&I, Result.first); // Pointers always fit in registers
2807 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002808}
2809
2810void SelectionDAGLowering::visitFree(FreeInst &I) {
2811 std::vector<std::pair<SDOperand, const Type*> > Args;
2812 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002813 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002814 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002815 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002816 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002817 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2818 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002819}
2820
Chris Lattner025c39b2005-08-26 20:54:47 +00002821// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2822// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2823// instructions are special in various ways, which require special support to
2824// insert. The specified MachineInstr is created but not inserted into any
2825// basic blocks, and the scheduler passes ownership of it to this method.
2826MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2827 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002828 cerr << "If a target marks an instruction with "
2829 << "'usesCustomDAGSchedInserter', it must implement "
2830 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002831 abort();
2832 return 0;
2833}
2834
Chris Lattner39ae3622005-01-09 00:00:49 +00002835void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002836 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2837 getValue(I.getOperand(1)),
2838 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002839}
2840
2841void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002842 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2843 getValue(I.getOperand(0)),
2844 DAG.getSrcValue(I.getOperand(0)));
2845 setValue(&I, V);
2846 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002847}
2848
2849void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002850 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2851 getValue(I.getOperand(1)),
2852 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002853}
2854
2855void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002856 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2857 getValue(I.getOperand(1)),
2858 getValue(I.getOperand(2)),
2859 DAG.getSrcValue(I.getOperand(1)),
2860 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002861}
2862
Chris Lattnerfdfded52006-04-12 16:20:43 +00002863/// TargetLowering::LowerArguments - This is the default LowerArguments
2864/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002865/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2866/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002867std::vector<SDOperand>
2868TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2869 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2870 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002871 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002872 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2873 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2874
2875 // Add one result value for each formal argument.
2876 std::vector<MVT::ValueType> RetVals;
2877 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2878 MVT::ValueType VT = getValueType(I->getType());
2879
2880 switch (getTypeAction(VT)) {
2881 default: assert(0 && "Unknown type action!");
2882 case Legal:
2883 RetVals.push_back(VT);
2884 break;
2885 case Promote:
2886 RetVals.push_back(getTypeToTransformTo(VT));
2887 break;
2888 case Expand:
2889 if (VT != MVT::Vector) {
2890 // If this is a large integer, it needs to be broken up into small
2891 // integers. Figure out what the destination type is and how many small
2892 // integers it turns into.
2893 MVT::ValueType NVT = getTypeToTransformTo(VT);
2894 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2895 for (unsigned i = 0; i != NumVals; ++i)
2896 RetVals.push_back(NVT);
2897 } else {
2898 // Otherwise, this is a vector type. We only support legal vectors
2899 // right now.
2900 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2901 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002902
Chris Lattnerfdfded52006-04-12 16:20:43 +00002903 // Figure out if there is a Packed type corresponding to this Vector
2904 // type. If so, convert to the packed type.
2905 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2906 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2907 RetVals.push_back(TVT);
2908 } else {
2909 assert(0 && "Don't support illegal by-val vector arguments yet!");
2910 }
2911 }
2912 break;
2913 }
2914 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002915
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002916 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002917
2918 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002919 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2920 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002921 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002922
2923 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002924
2925 // Set up the return result vector.
2926 Ops.clear();
2927 unsigned i = 0;
2928 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2929 MVT::ValueType VT = getValueType(I->getType());
2930
2931 switch (getTypeAction(VT)) {
2932 default: assert(0 && "Unknown type action!");
2933 case Legal:
2934 Ops.push_back(SDOperand(Result, i++));
2935 break;
2936 case Promote: {
2937 SDOperand Op(Result, i++);
2938 if (MVT::isInteger(VT)) {
2939 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2940 : ISD::AssertZext;
2941 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2942 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2943 } else {
2944 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2945 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2946 }
2947 Ops.push_back(Op);
2948 break;
2949 }
2950 case Expand:
2951 if (VT != MVT::Vector) {
2952 // If this is a large integer, it needs to be reassembled from small
2953 // integers. Figure out what the source elt type is and how many small
2954 // integers it is.
2955 MVT::ValueType NVT = getTypeToTransformTo(VT);
2956 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00002957 if (NumVals == 1) {
2958 SDOperand Tmp = SDOperand(Result, i++);
2959 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp));
2960 } else if (NumVals == 2) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002961 SDOperand Lo = SDOperand(Result, i++);
2962 SDOperand Hi = SDOperand(Result, i++);
2963
2964 if (!isLittleEndian())
2965 std::swap(Lo, Hi);
2966
2967 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2968 } else {
2969 // Value scalarized into many values. Unimp for now.
2970 assert(0 && "Cannot expand i64 -> i16 yet!");
2971 }
2972 } else {
2973 // Otherwise, this is a vector type. We only support legal vectors
2974 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002975 const PackedType *PTy = cast<PackedType>(I->getType());
2976 unsigned NumElems = PTy->getNumElements();
2977 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002978
Chris Lattnerfdfded52006-04-12 16:20:43 +00002979 // Figure out if there is a Packed type corresponding to this Vector
2980 // type. If so, convert to the packed type.
2981 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002982 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002983 SDOperand N = SDOperand(Result, i++);
2984 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002985 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2986 DAG.getConstant(NumElems, MVT::i32),
2987 DAG.getValueType(getValueType(EltTy)));
2988 Ops.push_back(N);
2989 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002990 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002991 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002992 }
2993 }
2994 break;
2995 }
2996 }
2997 return Ops;
2998}
2999
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003000
3001/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3002/// implementation, which just inserts an ISD::CALL node, which is later custom
3003/// lowered by the target to something concrete. FIXME: When all targets are
3004/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3005std::pair<SDOperand, SDOperand>
3006TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
3007 unsigned CallingConv, bool isTailCall,
3008 SDOperand Callee,
3009 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003010 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003011 Ops.push_back(Chain); // Op#0 - Chain
3012 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3013 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3014 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3015 Ops.push_back(Callee);
3016
3017 // Handle all of the outgoing arguments.
3018 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3019 MVT::ValueType VT = getValueType(Args[i].second);
3020 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00003021 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003022 switch (getTypeAction(VT)) {
3023 default: assert(0 && "Unknown type action!");
3024 case Legal:
3025 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003026 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003027 break;
3028 case Promote:
3029 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003030 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003031 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3032 } else {
3033 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3034 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3035 }
3036 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003037 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003038 break;
3039 case Expand:
3040 if (VT != MVT::Vector) {
3041 // If this is a large integer, it needs to be broken down into small
3042 // integers. Figure out what the source elt type is and how many small
3043 // integers it is.
3044 MVT::ValueType NVT = getTypeToTransformTo(VT);
3045 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003046 if (NumVals == 1) {
3047 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, VT, Op));
3048 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3049 } else if (NumVals == 2) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003050 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3051 DAG.getConstant(0, getPointerTy()));
3052 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3053 DAG.getConstant(1, getPointerTy()));
3054 if (!isLittleEndian())
3055 std::swap(Lo, Hi);
3056
3057 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00003058 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003059 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00003060 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003061 } else {
3062 // Value scalarized into many values. Unimp for now.
3063 assert(0 && "Cannot expand i64 -> i16 yet!");
3064 }
3065 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003066 // Otherwise, this is a vector type. We only support legal vectors
3067 // right now.
3068 const PackedType *PTy = cast<PackedType>(Args[i].second);
3069 unsigned NumElems = PTy->getNumElements();
3070 const Type *EltTy = PTy->getElementType();
3071
3072 // Figure out if there is a Packed type corresponding to this Vector
3073 // type. If so, convert to the packed type.
3074 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003075 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3076 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3077 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3078 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003079 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003080 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003081 assert(0 && "Don't support illegal by-val vector call args yet!");
3082 abort();
3083 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003084 }
3085 break;
3086 }
3087 }
3088
3089 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003090 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003091
3092 if (RetTy != Type::VoidTy) {
3093 MVT::ValueType VT = getValueType(RetTy);
3094 switch (getTypeAction(VT)) {
3095 default: assert(0 && "Unknown type action!");
3096 case Legal:
3097 RetTys.push_back(VT);
3098 break;
3099 case Promote:
3100 RetTys.push_back(getTypeToTransformTo(VT));
3101 break;
3102 case Expand:
3103 if (VT != MVT::Vector) {
3104 // If this is a large integer, it needs to be reassembled from small
3105 // integers. Figure out what the source elt type is and how many small
3106 // integers it is.
3107 MVT::ValueType NVT = getTypeToTransformTo(VT);
3108 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3109 for (unsigned i = 0; i != NumVals; ++i)
3110 RetTys.push_back(NVT);
3111 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003112 // Otherwise, this is a vector type. We only support legal vectors
3113 // right now.
3114 const PackedType *PTy = cast<PackedType>(RetTy);
3115 unsigned NumElems = PTy->getNumElements();
3116 const Type *EltTy = PTy->getElementType();
3117
3118 // Figure out if there is a Packed type corresponding to this Vector
3119 // type. If so, convert to the packed type.
3120 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3121 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3122 RetTys.push_back(TVT);
3123 } else {
3124 assert(0 && "Don't support illegal by-val vector call results yet!");
3125 abort();
3126 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003127 }
3128 }
3129 }
3130
3131 RetTys.push_back(MVT::Other); // Always has a chain.
3132
3133 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003134 SDOperand Res = DAG.getNode(ISD::CALL,
3135 DAG.getVTList(&RetTys[0], RetTys.size()),
3136 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003137
3138 // This returns a pair of operands. The first element is the
3139 // return value for the function (if RetTy is not VoidTy). The second
3140 // element is the outgoing token chain.
3141 SDOperand ResVal;
3142 if (RetTys.size() != 1) {
3143 MVT::ValueType VT = getValueType(RetTy);
3144 if (RetTys.size() == 2) {
3145 ResVal = Res;
3146
3147 // If this value was promoted, truncate it down.
3148 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003149 if (VT == MVT::Vector) {
3150 // Insert a VBITCONVERT to convert from the packed result type to the
3151 // MVT::Vector type.
3152 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3153 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3154
3155 // Figure out if there is a Packed type corresponding to this Vector
3156 // type. If so, convert to the packed type.
3157 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3158 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003159 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3160 // "N x PTyElementVT" MVT::Vector type.
3161 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003162 DAG.getConstant(NumElems, MVT::i32),
3163 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003164 } else {
3165 abort();
3166 }
3167 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003168 unsigned AssertOp = RetTy->isSigned() ?
3169 ISD::AssertSext : ISD::AssertZext;
3170 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3171 DAG.getValueType(VT));
3172 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3173 } else {
3174 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003175 if (getTypeAction(VT) == Expand)
3176 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3177 else
3178 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003179 }
3180 }
3181 } else if (RetTys.size() == 3) {
3182 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3183 Res.getValue(0), Res.getValue(1));
3184
3185 } else {
3186 assert(0 && "Case not handled yet!");
3187 }
3188 }
3189
3190 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3191}
3192
3193
3194
Chris Lattner39ae3622005-01-09 00:00:49 +00003195// It is always conservatively correct for llvm.returnaddress and
3196// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003197//
3198// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3199// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00003200std::pair<SDOperand, SDOperand>
3201TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3202 unsigned Depth, SelectionDAG &DAG) {
3203 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00003204}
3205
Chris Lattner50381b62005-05-14 05:50:48 +00003206SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003207 assert(0 && "LowerOperation not implemented for this target!");
3208 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003209 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003210}
3211
Nate Begeman0aed7842006-01-28 03:14:31 +00003212SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3213 SelectionDAG &DAG) {
3214 assert(0 && "CustomPromoteOperation not implemented for this target!");
3215 abort();
3216 return SDOperand();
3217}
3218
Chris Lattner39ae3622005-01-09 00:00:49 +00003219void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003220 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003221 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003222 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003223 setValue(&I, Result.first);
3224 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003225}
3226
Evan Cheng74d0aa92006-02-15 21:59:04 +00003227/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003228/// operand.
3229static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003230 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003231 MVT::ValueType CurVT = VT;
3232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3233 uint64_t Val = C->getValue() & 255;
3234 unsigned Shift = 8;
3235 while (CurVT != MVT::i8) {
3236 Val = (Val << Shift) | Val;
3237 Shift <<= 1;
3238 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003239 }
3240 return DAG.getConstant(Val, VT);
3241 } else {
3242 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3243 unsigned Shift = 8;
3244 while (CurVT != MVT::i8) {
3245 Value =
3246 DAG.getNode(ISD::OR, VT,
3247 DAG.getNode(ISD::SHL, VT, Value,
3248 DAG.getConstant(Shift, MVT::i8)), Value);
3249 Shift <<= 1;
3250 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003251 }
3252
3253 return Value;
3254 }
3255}
3256
Evan Cheng74d0aa92006-02-15 21:59:04 +00003257/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3258/// used when a memcpy is turned into a memset when the source is a constant
3259/// string ptr.
3260static SDOperand getMemsetStringVal(MVT::ValueType VT,
3261 SelectionDAG &DAG, TargetLowering &TLI,
3262 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003263 uint64_t Val = 0;
3264 unsigned MSB = getSizeInBits(VT) / 8;
3265 if (TLI.isLittleEndian())
3266 Offset = Offset + MSB - 1;
3267 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003268 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003269 Offset += TLI.isLittleEndian() ? -1 : 1;
3270 }
3271 return DAG.getConstant(Val, VT);
3272}
3273
Evan Cheng1db92f92006-02-14 08:22:34 +00003274/// getMemBasePlusOffset - Returns base and offset node for the
3275static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3276 SelectionDAG &DAG, TargetLowering &TLI) {
3277 MVT::ValueType VT = Base.getValueType();
3278 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3279}
3280
Evan Chengc4f8eee2006-02-14 20:12:38 +00003281/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003282/// to replace the memset / memcpy is below the threshold. It also returns the
3283/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003284static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3285 unsigned Limit, uint64_t Size,
3286 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003287 MVT::ValueType VT;
3288
3289 if (TLI.allowsUnalignedMemoryAccesses()) {
3290 VT = MVT::i64;
3291 } else {
3292 switch (Align & 7) {
3293 case 0:
3294 VT = MVT::i64;
3295 break;
3296 case 4:
3297 VT = MVT::i32;
3298 break;
3299 case 2:
3300 VT = MVT::i16;
3301 break;
3302 default:
3303 VT = MVT::i8;
3304 break;
3305 }
3306 }
3307
Evan Cheng80e89d72006-02-14 09:11:59 +00003308 MVT::ValueType LVT = MVT::i64;
3309 while (!TLI.isTypeLegal(LVT))
3310 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3311 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003312
Evan Cheng80e89d72006-02-14 09:11:59 +00003313 if (VT > LVT)
3314 VT = LVT;
3315
Evan Chengdea72452006-02-14 23:05:54 +00003316 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003317 while (Size != 0) {
3318 unsigned VTSize = getSizeInBits(VT) / 8;
3319 while (VTSize > Size) {
3320 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003321 VTSize >>= 1;
3322 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003323 assert(MVT::isInteger(VT));
3324
3325 if (++NumMemOps > Limit)
3326 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003327 MemOps.push_back(VT);
3328 Size -= VTSize;
3329 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003330
3331 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003332}
3333
Chris Lattner7041ee32005-01-11 05:56:49 +00003334void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003335 SDOperand Op1 = getValue(I.getOperand(1));
3336 SDOperand Op2 = getValue(I.getOperand(2));
3337 SDOperand Op3 = getValue(I.getOperand(3));
3338 SDOperand Op4 = getValue(I.getOperand(4));
3339 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3340 if (Align == 0) Align = 1;
3341
3342 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3343 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003344
3345 // Expand memset / memcpy to a series of load / store ops
3346 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003347 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003348 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003349 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003350 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003351 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3352 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003353 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003354 unsigned Offset = 0;
3355 for (unsigned i = 0; i < NumMemOps; i++) {
3356 MVT::ValueType VT = MemOps[i];
3357 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003358 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003359 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003360 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003361 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003362 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003363 Offset += VTSize;
3364 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003365 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003366 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003367 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003368 case ISD::MEMCPY: {
3369 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3370 Size->getValue(), Align, TLI)) {
3371 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003372 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003373 GlobalAddressSDNode *G = NULL;
3374 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003375 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003376
3377 if (Op2.getOpcode() == ISD::GlobalAddress)
3378 G = cast<GlobalAddressSDNode>(Op2);
3379 else if (Op2.getOpcode() == ISD::ADD &&
3380 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3381 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3382 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003383 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003384 }
3385 if (G) {
3386 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003387 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003388 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003389 if (!Str.empty()) {
3390 CopyFromStr = true;
3391 SrcOff += SrcDelta;
3392 }
3393 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003394 }
3395
Evan Chengc080d6f2006-02-15 01:54:51 +00003396 for (unsigned i = 0; i < NumMemOps; i++) {
3397 MVT::ValueType VT = MemOps[i];
3398 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003399 SDOperand Value, Chain, Store;
3400
Evan Chengcffbb512006-02-16 23:11:42 +00003401 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003402 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3403 Chain = getRoot();
3404 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003405 DAG.getStore(Chain, Value,
3406 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003407 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003408 } else {
3409 Value = DAG.getLoad(VT, getRoot(),
3410 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003411 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003412 Chain = Value.getValue(1);
3413 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003414 DAG.getStore(Chain, Value,
3415 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003416 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003417 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003418 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003419 SrcOff += VTSize;
3420 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003421 }
3422 }
3423 break;
3424 }
3425 }
3426
3427 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003428 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3429 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003430 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003431 }
3432 }
3433
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003434 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003435}
3436
Chris Lattner7041ee32005-01-11 05:56:49 +00003437//===----------------------------------------------------------------------===//
3438// SelectionDAGISel code
3439//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003440
3441unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3442 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3443}
3444
Chris Lattner495a0b52005-08-17 06:37:43 +00003445void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003446 // FIXME: we only modify the CFG to split critical edges. This
3447 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003448 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003449}
Chris Lattner1c08c712005-01-07 07:47:53 +00003450
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003451
Chris Lattner90323642006-05-05 21:17:49 +00003452/// OptimizeNoopCopyExpression - We have determined that the specified cast
3453/// instruction is a noop copy (e.g. it's casting from one pointer type to
3454/// another, int->uint, or int->sbyte on PPC.
3455///
3456/// Return true if any changes are made.
3457static bool OptimizeNoopCopyExpression(CastInst *CI) {
3458 BasicBlock *DefBB = CI->getParent();
3459
3460 /// InsertedCasts - Only insert a cast in each block once.
3461 std::map<BasicBlock*, CastInst*> InsertedCasts;
3462
3463 bool MadeChange = false;
3464 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3465 UI != E; ) {
3466 Use &TheUse = UI.getUse();
3467 Instruction *User = cast<Instruction>(*UI);
3468
3469 // Figure out which BB this cast is used in. For PHI's this is the
3470 // appropriate predecessor block.
3471 BasicBlock *UserBB = User->getParent();
3472 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3473 unsigned OpVal = UI.getOperandNo()/2;
3474 UserBB = PN->getIncomingBlock(OpVal);
3475 }
3476
3477 // Preincrement use iterator so we don't invalidate it.
3478 ++UI;
3479
3480 // If this user is in the same block as the cast, don't change the cast.
3481 if (UserBB == DefBB) continue;
3482
3483 // If we have already inserted a cast into this block, use it.
3484 CastInst *&InsertedCast = InsertedCasts[UserBB];
3485
3486 if (!InsertedCast) {
3487 BasicBlock::iterator InsertPt = UserBB->begin();
3488 while (isa<PHINode>(InsertPt)) ++InsertPt;
3489
3490 InsertedCast =
Reid Spencer3da59db2006-11-27 01:05:10 +00003491 CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3492 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003493 MadeChange = true;
3494 }
3495
3496 // Replace a use of the cast with a use of the new casat.
3497 TheUse = InsertedCast;
3498 }
3499
3500 // If we removed all uses, nuke the cast.
3501 if (CI->use_empty())
3502 CI->eraseFromParent();
3503
3504 return MadeChange;
3505}
3506
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003507/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3508/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003509static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3510 Instruction *GEPI, Value *Ptr,
3511 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003512 if (V) return V; // Already computed.
3513
Reid Spencer3da59db2006-11-27 01:05:10 +00003514 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003515 BasicBlock::iterator InsertPt;
3516 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003517 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003518 InsertPt = GEPI;
3519 ++InsertPt;
3520 } else {
3521 // Otherwise, insert at the top of BB, after any PHI nodes
3522 InsertPt = BB->begin();
3523 while (isa<PHINode>(InsertPt)) ++InsertPt;
3524 }
3525
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003526 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3527 // BB so that there is only one value live across basic blocks (the cast
3528 // operand).
3529 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3530 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer3da59db2006-11-27 01:05:10 +00003531 Ptr = CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3532 InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003533
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003534 // Add the offset, cast it to the right type.
3535 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003536 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3537 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3538 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003539}
3540
Chris Lattner90323642006-05-05 21:17:49 +00003541/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3542/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3543/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3544/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3545/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3546/// the constant add into a load or store instruction. Additionally, if a user
3547/// is a pointer-pointer cast, we look through it to find its users.
3548static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3549 Constant *PtrOffset, BasicBlock *DefBB,
3550 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003551 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003552 while (!RepPtr->use_empty()) {
3553 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003554
Reid Spencer3da59db2006-11-27 01:05:10 +00003555 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3556 // used for a Pointer-Pointer cast.
3557 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003558 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003559
Chris Lattner90323642006-05-05 21:17:49 +00003560 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3561 // could invalidate an iterator.
3562 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3563 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003564 }
3565
Chris Lattner90323642006-05-05 21:17:49 +00003566 // If this is a load of the pointer, or a store through the pointer, emit
3567 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003568 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003569 if (isa<LoadInst>(User) ||
3570 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3571 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3572 User->getParent(), GEPI,
3573 Ptr, PtrOffset);
3574 } else {
3575 // If this use is not foldable into the addressing mode, use a version
3576 // emitted in the GEP block.
3577 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3578 Ptr, PtrOffset);
3579 }
3580
Chris Lattnerf0df8822006-05-06 09:10:37 +00003581 if (GEPI->getType() != RepPtr->getType()) {
3582 BasicBlock::iterator IP = NewVal;
3583 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003584 // NewVal must be a GEP which must be pointer type, so BitCast
3585 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003586 }
Chris Lattner90323642006-05-05 21:17:49 +00003587 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003588 }
3589}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003590
Chris Lattner90323642006-05-05 21:17:49 +00003591
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003592/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3593/// selection, we want to be a bit careful about some things. In particular, if
3594/// we have a GEP instruction that is used in a different block than it is
3595/// defined, the addressing expression of the GEP cannot be folded into loads or
3596/// stores that use it. In this case, decompose the GEP and move constant
3597/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003598static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003599 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003600 // If this GEP is only used inside the block it is defined in, there is no
3601 // need to rewrite it.
3602 bool isUsedOutsideDefBB = false;
3603 BasicBlock *DefBB = GEPI->getParent();
3604 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3605 UI != E; ++UI) {
3606 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3607 isUsedOutsideDefBB = true;
3608 break;
3609 }
3610 }
Chris Lattner90323642006-05-05 21:17:49 +00003611 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003612
3613 // If this GEP has no non-zero constant indices, there is nothing we can do,
3614 // ignore it.
3615 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003616 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003617 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3618 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003619 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003620 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003621 hasConstantIndex = true;
3622 break;
3623 }
Chris Lattner90323642006-05-05 21:17:49 +00003624 } else {
3625 hasVariableIndex = true;
3626 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003627 }
Chris Lattner90323642006-05-05 21:17:49 +00003628
3629 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3630 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003631 /// The GEP operand must be a pointer, so must its result -> BitCast
3632 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003633 GEPI->getName(), GEPI);
3634 GEPI->replaceAllUsesWith(NC);
3635 GEPI->eraseFromParent();
3636 return true;
3637 }
3638
Chris Lattner3802c252005-12-11 09:05:13 +00003639 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003640 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3641 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003642
3643 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3644 // constant offset (which we now know is non-zero) and deal with it later.
3645 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003646 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003647 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003648 const Type *Ty = GEPI->getOperand(0)->getType();
3649
3650 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3651 E = GEPI->op_end(); OI != E; ++OI) {
3652 Value *Idx = *OI;
3653 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003654 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003655 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003656 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003657 Ty = StTy->getElementType(Field);
3658 } else {
3659 Ty = cast<SequentialType>(Ty)->getElementType();
3660
3661 // Handle constant subscripts.
3662 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003663 if (CI->getZExtValue() == 0) continue;
3664 if (CI->getType()->isSigned())
3665 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003666 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003667 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003668 continue;
3669 }
3670
3671 // Ptr = Ptr + Idx * ElementSize;
3672
3673 // Cast Idx to UIntPtrTy if needed.
Reid Spencer3da59db2006-11-27 01:05:10 +00003674 Idx = CastInst::createInferredCast(Idx, UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003675
Owen Andersona69571c2006-05-03 01:29:57 +00003676 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003677 // Mask off bits that should not be set.
3678 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003679 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003680
3681 // Multiply by the element size and add to the base.
3682 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3683 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3684 }
3685 }
3686
3687 // Make sure that the offset fits in uintptr_t.
3688 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003689 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003690
3691 // Okay, we have now emitted all of the variable index parts to the BB that
3692 // the GEP is defined in. Loop over all of the using instructions, inserting
3693 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003694 // instruction to use the newly computed value, making GEPI dead. When the
3695 // user is a load or store instruction address, we emit the add into the user
3696 // block, otherwise we use a canonical version right next to the gep (these
3697 // won't be foldable as addresses, so we might as well share the computation).
3698
Chris Lattnerf0df8822006-05-06 09:10:37 +00003699 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003700 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003701
3702 // Finally, the GEP is dead, remove it.
3703 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003704
3705 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003706}
3707
Chris Lattnerbad7f482006-10-28 19:22:10 +00003708
3709/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3710/// successor if it will improve codegen. We only do this if the successor has
3711/// phi nodes (otherwise critical edges are ok). If there is already another
3712/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3713/// instead of introducing a new block.
3714static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3715 BasicBlock *TIBB = TI->getParent();
3716 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3717 assert(isa<PHINode>(Dest->begin()) &&
3718 "This should only be called if Dest has a PHI!");
3719
3720 /// TIPHIValues - This array is lazily computed to determine the values of
3721 /// PHIs in Dest that TI would provide.
3722 std::vector<Value*> TIPHIValues;
3723
3724 // Check to see if Dest has any blocks that can be used as a split edge for
3725 // this terminator.
3726 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3727 BasicBlock *Pred = *PI;
3728 // To be usable, the pred has to end with an uncond branch to the dest.
3729 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3730 if (!PredBr || !PredBr->isUnconditional() ||
3731 // Must be empty other than the branch.
3732 &Pred->front() != PredBr)
3733 continue;
3734
3735 // Finally, since we know that Dest has phi nodes in it, we have to make
3736 // sure that jumping to Pred will have the same affect as going to Dest in
3737 // terms of PHI values.
3738 PHINode *PN;
3739 unsigned PHINo = 0;
3740 bool FoundMatch = true;
3741 for (BasicBlock::iterator I = Dest->begin();
3742 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3743 if (PHINo == TIPHIValues.size())
3744 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3745
3746 // If the PHI entry doesn't work, we can't use this pred.
3747 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3748 FoundMatch = false;
3749 break;
3750 }
3751 }
3752
3753 // If we found a workable predecessor, change TI to branch to Succ.
3754 if (FoundMatch) {
3755 Dest->removePredecessor(TIBB);
3756 TI->setSuccessor(SuccNum, Pred);
3757 return;
3758 }
3759 }
3760
3761 SplitCriticalEdge(TI, SuccNum, P, true);
3762}
3763
3764
Chris Lattner1c08c712005-01-07 07:47:53 +00003765bool SelectionDAGISel::runOnFunction(Function &Fn) {
3766 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3767 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003768 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003769
Chris Lattner47e32e62006-10-28 17:04:37 +00003770 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003771 //
Chris Lattner7e598092006-05-05 01:04:50 +00003772 // In this pass we also look for GEP and cast instructions that are used
3773 // across basic blocks and rewrite them to improve basic-block-at-a-time
3774 // selection.
3775 //
Chris Lattner90323642006-05-05 21:17:49 +00003776 bool MadeChange = true;
3777 while (MadeChange) {
3778 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003779 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003780 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003781 TerminatorInst *BBTI = BB->getTerminator();
3782 if (BBTI->getNumSuccessors() > 1) {
3783 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003784 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3785 isCriticalEdge(BBTI, i, true))
3786 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003787 }
3788
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003789
Chris Lattner57f9a432006-09-28 06:17:10 +00003790 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003791 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003792
3793 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3794 // If we found an inline asm expession, and if the target knows how to
3795 // lower it to normal LLVM code, do so now.
3796 if (isa<InlineAsm>(CI->getCalledValue()))
3797 if (const TargetAsmInfo *TAI =
3798 TLI.getTargetMachine().getTargetAsmInfo()) {
3799 if (TAI->ExpandInlineAsm(CI))
3800 BBI = BB->begin();
3801 }
3802 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003803 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003804 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003805 // If the source of the cast is a constant, then this should have
3806 // already been constant folded. The only reason NOT to constant fold
3807 // it is if something (e.g. LSR) was careful to place the constant
3808 // evaluation in a block other than then one that uses it (e.g. to hoist
3809 // the address of globals out of a loop). If this is the case, we don't
3810 // want to forward-subst the cast.
3811 if (isa<Constant>(CI->getOperand(0)))
3812 continue;
3813
Chris Lattner7e598092006-05-05 01:04:50 +00003814 // If this is a noop copy, sink it into user blocks to reduce the number
3815 // of virtual registers that must be created and coallesced.
3816 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3817 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3818
3819 // This is an fp<->int conversion?
3820 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3821 continue;
3822
3823 // If this is an extension, it will be a zero or sign extension, which
3824 // isn't a noop.
3825 if (SrcVT < DstVT) continue;
3826
3827 // If these values will be promoted, find out what they will be promoted
3828 // to. This helps us consider truncates on PPC as noop copies when they
3829 // are.
3830 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3831 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3832 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3833 DstVT = TLI.getTypeToTransformTo(DstVT);
3834
3835 // If, after promotion, these are the same types, this is a noop copy.
3836 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003837 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003838 }
3839 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003840 }
Chris Lattner90323642006-05-05 21:17:49 +00003841 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003842
Chris Lattner1c08c712005-01-07 07:47:53 +00003843 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3844
3845 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3846 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003847
Chris Lattner1c08c712005-01-07 07:47:53 +00003848 return true;
3849}
3850
Chris Lattner571e4342006-10-27 21:36:01 +00003851SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3852 unsigned Reg) {
3853 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003854 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003855 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003856 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003857
3858 // If this type is not legal, we must make sure to not create an invalid
3859 // register use.
3860 MVT::ValueType SrcVT = Op.getValueType();
3861 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003862 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003863 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003864 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003865 // Handle copies from generic vectors to registers.
3866 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3867 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3868 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003869
Chris Lattner70c2a612006-03-31 02:06:56 +00003870 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3871 // MVT::Vector type.
3872 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3873 DAG.getConstant(NE, MVT::i32),
3874 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003875
Chris Lattner70c2a612006-03-31 02:06:56 +00003876 // Loop over all of the elements of the resultant vector,
3877 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3878 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003879 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003880 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003881 for (unsigned i = 0; i != NE; ++i) {
3882 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003883 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003884 if (PTyElementVT == PTyLegalElementVT) {
3885 // Elements are legal.
3886 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3887 } else if (PTyLegalElementVT > PTyElementVT) {
3888 // Elements are promoted.
3889 if (MVT::isFloatingPoint(PTyLegalElementVT))
3890 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3891 else
3892 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3893 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3894 } else {
3895 // Elements are expanded.
3896 // The src value is expanded into multiple registers.
3897 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003898 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003899 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003900 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003901 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3902 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3903 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003904 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003905 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3906 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003907 } else if (SrcVT < DestVT) {
3908 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003909 if (MVT::isFloatingPoint(SrcVT))
3910 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3911 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003912 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003913 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003914 } else {
3915 // The src value is expanded into multiple registers.
3916 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003917 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003918 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003919 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003920 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003921 return DAG.getCopyToReg(Op, Reg+1, Hi);
3922 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003923}
3924
Chris Lattner068a81e2005-01-17 17:15:02 +00003925void SelectionDAGISel::
3926LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3927 std::vector<SDOperand> &UnorderedChains) {
3928 // If this is the entry block, emit arguments.
3929 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003930 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003931 SDOperand OldRoot = SDL.DAG.getRoot();
3932 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003933
Chris Lattnerbf209482005-10-30 19:42:35 +00003934 unsigned a = 0;
3935 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3936 AI != E; ++AI, ++a)
3937 if (!AI->use_empty()) {
3938 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003939
Chris Lattnerbf209482005-10-30 19:42:35 +00003940 // If this argument is live outside of the entry block, insert a copy from
3941 // whereever we got it to the vreg that other BB's will reference it as.
3942 if (FuncInfo.ValueMap.count(AI)) {
3943 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003944 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003945 UnorderedChains.push_back(Copy);
3946 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003947 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003948
Chris Lattnerbf209482005-10-30 19:42:35 +00003949 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003950 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003951 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003952}
3953
Chris Lattner1c08c712005-01-07 07:47:53 +00003954void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3955 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003956 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003957 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003958
3959 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003960
Chris Lattnerbf209482005-10-30 19:42:35 +00003961 // Lower any arguments needed in this block if this is the entry block.
3962 if (LLVMBB == &LLVMBB->getParent()->front())
3963 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003964
3965 BB = FuncInfo.MBBMap[LLVMBB];
3966 SDL.setCurrentBasicBlock(BB);
3967
3968 // Lower all of the non-terminator instructions.
3969 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3970 I != E; ++I)
3971 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003972
Chris Lattner1c08c712005-01-07 07:47:53 +00003973 // Ensure that all instructions which are used outside of their defining
3974 // blocks are available as virtual registers.
3975 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003976 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003977 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003978 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003979 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003980 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003981 }
3982
3983 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3984 // ensure constants are generated when needed. Remember the virtual registers
3985 // that need to be added to the Machine PHI nodes as input. We cannot just
3986 // directly add them, because expansion might result in multiple MBB's for one
3987 // BB. As such, the start of the BB might correspond to a different MBB than
3988 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003989 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00003990 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00003991
3992 // Emit constants only once even if used by multiple PHI nodes.
3993 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003994
Chris Lattner8c494ab2006-10-27 23:50:33 +00003995 // Vector bool would be better, but vector<bool> is really slow.
3996 std::vector<unsigned char> SuccsHandled;
3997 if (TI->getNumSuccessors())
3998 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3999
Chris Lattner1c08c712005-01-07 07:47:53 +00004000 // Check successor nodes PHI nodes that expect a constant to be available from
4001 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004002 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4003 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004004 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004005 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004006
Chris Lattner8c494ab2006-10-27 23:50:33 +00004007 // If this terminator has multiple identical successors (common for
4008 // switches), only handle each succ once.
4009 unsigned SuccMBBNo = SuccMBB->getNumber();
4010 if (SuccsHandled[SuccMBBNo]) continue;
4011 SuccsHandled[SuccMBBNo] = true;
4012
4013 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004014 PHINode *PN;
4015
4016 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4017 // nodes and Machine PHI nodes, but the incoming operands have not been
4018 // emitted yet.
4019 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004020 (PN = dyn_cast<PHINode>(I)); ++I) {
4021 // Ignore dead phi's.
4022 if (PN->use_empty()) continue;
4023
4024 unsigned Reg;
4025 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004026
Chris Lattner8c494ab2006-10-27 23:50:33 +00004027 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4028 unsigned &RegOut = ConstantsOut[C];
4029 if (RegOut == 0) {
4030 RegOut = FuncInfo.CreateRegForValue(C);
4031 UnorderedChains.push_back(
4032 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004033 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004034 Reg = RegOut;
4035 } else {
4036 Reg = FuncInfo.ValueMap[PHIOp];
4037 if (Reg == 0) {
4038 assert(isa<AllocaInst>(PHIOp) &&
4039 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4040 "Didn't codegen value into a register!??");
4041 Reg = FuncInfo.CreateRegForValue(PHIOp);
4042 UnorderedChains.push_back(
4043 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004044 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004045 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004046
4047 // Remember that this register needs to added to the machine PHI node as
4048 // the input for this MBB.
4049 MVT::ValueType VT = TLI.getValueType(PN->getType());
4050 unsigned NumElements;
4051 if (VT != MVT::Vector)
4052 NumElements = TLI.getNumElements(VT);
4053 else {
4054 MVT::ValueType VT1,VT2;
4055 NumElements =
4056 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4057 VT1, VT2);
4058 }
4059 for (unsigned i = 0, e = NumElements; i != e; ++i)
4060 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4061 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004062 }
4063 ConstantsOut.clear();
4064
Chris Lattnerddb870b2005-01-13 17:59:43 +00004065 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004066 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004067 SDOperand Root = SDL.getRoot();
4068 if (Root.getOpcode() != ISD::EntryToken) {
4069 unsigned i = 0, e = UnorderedChains.size();
4070 for (; i != e; ++i) {
4071 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4072 if (UnorderedChains[i].Val->getOperand(0) == Root)
4073 break; // Don't add the root if we already indirectly depend on it.
4074 }
4075
4076 if (i == e)
4077 UnorderedChains.push_back(Root);
4078 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004079 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4080 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004081 }
4082
Chris Lattner1c08c712005-01-07 07:47:53 +00004083 // Lower the terminator after the copies are emitted.
4084 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004085
Nate Begemanf15485a2006-03-27 01:32:24 +00004086 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004087 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004088 SwitchCases.clear();
4089 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004090 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004091
Chris Lattnera651cf62005-01-17 19:43:36 +00004092 // Make sure the root of the DAG is up-to-date.
4093 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004094}
4095
Nate Begemanf15485a2006-03-27 01:32:24 +00004096void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004097 // Get alias analysis for load/store combining.
4098 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4099
Chris Lattneraf21d552005-10-10 16:47:10 +00004100 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004101 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004102
Bill Wendling832171c2006-12-07 20:04:42 +00004103 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004104 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004105
Chris Lattner1c08c712005-01-07 07:47:53 +00004106 // Second step, hack on the DAG until it only uses operations and types that
4107 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004108 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004109
Bill Wendling832171c2006-12-07 20:04:42 +00004110 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004111 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004112
Chris Lattneraf21d552005-10-10 16:47:10 +00004113 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004114 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004115
Evan Chenga9c20912006-01-21 02:32:06 +00004116 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004117
Chris Lattnera33ef482005-03-30 01:10:47 +00004118 // Third, instruction select all of the operations to machine code, adding the
4119 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004120 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004121
Bill Wendling832171c2006-12-07 20:04:42 +00004122 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004123 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004124}
Chris Lattner1c08c712005-01-07 07:47:53 +00004125
Nate Begemanf15485a2006-03-27 01:32:24 +00004126void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4127 FunctionLoweringInfo &FuncInfo) {
4128 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4129 {
4130 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4131 CurDAG = &DAG;
4132
4133 // First step, lower LLVM code to some DAG. This DAG may use operations and
4134 // types that are not supported by the target.
4135 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4136
4137 // Second step, emit the lowered DAG as machine code.
4138 CodeGenAndEmitDAG(DAG);
4139 }
4140
Chris Lattnera33ef482005-03-30 01:10:47 +00004141 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004142 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004143 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004144 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4145 MachineInstr *PHI = PHINodesToUpdate[i].first;
4146 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4147 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004148 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004149 PHI->addMachineBasicBlockOperand(BB);
4150 }
4151 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004152 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004153
Nate Begeman9453eea2006-04-23 06:26:20 +00004154 // If the JumpTable record is filled in, then we need to emit a jump table.
4155 // Updating the PHI nodes is tricky in this case, since we need to determine
4156 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004157 if (JT.Reg) {
4158 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4159 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4160 CurDAG = &SDAG;
4161 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004162 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004163 // Set the current basic block to the mbb we wish to insert the code into
4164 BB = JT.MBB;
4165 SDL.setCurrentBasicBlock(BB);
4166 // Emit the code
4167 SDL.visitJumpTable(JT);
4168 SDAG.setRoot(SDL.getRoot());
4169 CodeGenAndEmitDAG(SDAG);
4170 // Update PHI Nodes
4171 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4172 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4173 MachineBasicBlock *PHIBB = PHI->getParent();
4174 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4175 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004176 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004177 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004178 PHI->addMachineBasicBlockOperand(RangeBB);
4179 }
4180 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004181 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004182 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004183 }
4184 }
4185 return;
4186 }
4187
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004188 // If the switch block involved a branch to one of the actual successors, we
4189 // need to update PHI nodes in that block.
4190 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4191 MachineInstr *PHI = PHINodesToUpdate[i].first;
4192 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4193 "This is not a machine PHI node that we are updating!");
4194 if (BB->isSuccessor(PHI->getParent())) {
4195 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4196 PHI->addMachineBasicBlockOperand(BB);
4197 }
4198 }
4199
Nate Begemanf15485a2006-03-27 01:32:24 +00004200 // If we generated any switch lowering information, build and codegen any
4201 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004202 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004203 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4204 CurDAG = &SDAG;
4205 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004206
Nate Begemanf15485a2006-03-27 01:32:24 +00004207 // Set the current basic block to the mbb we wish to insert the code into
4208 BB = SwitchCases[i].ThisBB;
4209 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004210
Nate Begemanf15485a2006-03-27 01:32:24 +00004211 // Emit the code
4212 SDL.visitSwitchCase(SwitchCases[i]);
4213 SDAG.setRoot(SDL.getRoot());
4214 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004215
4216 // Handle any PHI nodes in successors of this chunk, as if we were coming
4217 // from the original BB before switch expansion. Note that PHI nodes can
4218 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4219 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004220 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004221 for (MachineBasicBlock::iterator Phi = BB->begin();
4222 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4223 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4224 for (unsigned pn = 0; ; ++pn) {
4225 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4226 if (PHINodesToUpdate[pn].first == Phi) {
4227 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4228 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4229 break;
4230 }
4231 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004232 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004233
4234 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004235 if (BB == SwitchCases[i].FalseBB)
4236 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004237
4238 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004239 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004240 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004241 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004242 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004243 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004244}
Evan Chenga9c20912006-01-21 02:32:06 +00004245
Jim Laskey13ec7022006-08-01 14:21:23 +00004246
Evan Chenga9c20912006-01-21 02:32:06 +00004247//===----------------------------------------------------------------------===//
4248/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4249/// target node in the graph.
4250void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4251 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004252
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004253 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004254
4255 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004256 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004257 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004258 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004259
Jim Laskey9ff542f2006-08-01 18:29:48 +00004260 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004261 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004262 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004263}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004264
Chris Lattner03fc53c2006-03-06 00:22:00 +00004265
Jim Laskey9ff542f2006-08-01 18:29:48 +00004266HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4267 return new HazardRecognizer();
4268}
4269
Chris Lattner75548062006-10-11 03:58:02 +00004270//===----------------------------------------------------------------------===//
4271// Helper functions used by the generated instruction selector.
4272//===----------------------------------------------------------------------===//
4273// Calls to these methods are generated by tblgen.
4274
4275/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4276/// the dag combiner simplified the 255, we still want to match. RHS is the
4277/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4278/// specified in the .td file (e.g. 255).
4279bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4280 int64_t DesiredMaskS) {
4281 uint64_t ActualMask = RHS->getValue();
4282 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4283
4284 // If the actual mask exactly matches, success!
4285 if (ActualMask == DesiredMask)
4286 return true;
4287
4288 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4289 if (ActualMask & ~DesiredMask)
4290 return false;
4291
4292 // Otherwise, the DAG Combiner may have proven that the value coming in is
4293 // either already zero or is not demanded. Check for known zero input bits.
4294 uint64_t NeededMask = DesiredMask & ~ActualMask;
4295 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4296 return true;
4297
4298 // TODO: check to see if missing bits are just not demanded.
4299
4300 // Otherwise, this pattern doesn't match.
4301 return false;
4302}
4303
4304/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4305/// the dag combiner simplified the 255, we still want to match. RHS is the
4306/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4307/// specified in the .td file (e.g. 255).
4308bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4309 int64_t DesiredMaskS) {
4310 uint64_t ActualMask = RHS->getValue();
4311 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4312
4313 // If the actual mask exactly matches, success!
4314 if (ActualMask == DesiredMask)
4315 return true;
4316
4317 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4318 if (ActualMask & ~DesiredMask)
4319 return false;
4320
4321 // Otherwise, the DAG Combiner may have proven that the value coming in is
4322 // either already zero or is not demanded. Check for known zero input bits.
4323 uint64_t NeededMask = DesiredMask & ~ActualMask;
4324
4325 uint64_t KnownZero, KnownOne;
4326 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4327
4328 // If all the missing bits in the or are already known to be set, match!
4329 if ((NeededMask & KnownOne) == NeededMask)
4330 return true;
4331
4332 // TODO: check to see if missing bits are just not demanded.
4333
4334 // Otherwise, this pattern doesn't match.
4335 return false;
4336}
4337
Jim Laskey9ff542f2006-08-01 18:29:48 +00004338
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004339/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4340/// by tblgen. Others should not call it.
4341void SelectionDAGISel::
4342SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4343 std::vector<SDOperand> InOps;
4344 std::swap(InOps, Ops);
4345
4346 Ops.push_back(InOps[0]); // input chain.
4347 Ops.push_back(InOps[1]); // input asm string.
4348
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004349 unsigned i = 2, e = InOps.size();
4350 if (InOps[e-1].getValueType() == MVT::Flag)
4351 --e; // Don't process a flag operand if it is here.
4352
4353 while (i != e) {
4354 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4355 if ((Flags & 7) != 4 /*MEM*/) {
4356 // Just skip over this operand, copying the operands verbatim.
4357 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4358 i += (Flags >> 3) + 1;
4359 } else {
4360 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4361 // Otherwise, this is a memory operand. Ask the target to select it.
4362 std::vector<SDOperand> SelOps;
4363 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004364 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004365 exit(1);
4366 }
4367
4368 // Add this to the output node.
4369 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4370 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4371 i += 2;
4372 }
4373 }
4374
4375 // Add the flag input back if present.
4376 if (e != InOps.size())
4377 Ops.push_back(InOps.back());
4378}