blob: 8a597da7f75894e8ee49f06135e432d394ec5e26 [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.
Evan Cheng9f877882006-12-13 20:57:08 +0000349 VT = TLI.getTypeToExpandTo(VT);
350 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000351 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000352 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000353 return R;
354}
Chris Lattner1c08c712005-01-07 07:47:53 +0000355
356//===----------------------------------------------------------------------===//
357/// SelectionDAGLowering - This is the common target-independent lowering
358/// implementation that is parameterized by a TargetLowering object.
359/// Also, targets can overload any lowering method.
360///
361namespace llvm {
362class SelectionDAGLowering {
363 MachineBasicBlock *CurMBB;
364
365 std::map<const Value*, SDOperand> NodeMap;
366
Chris Lattnerd3948112005-01-17 22:19:26 +0000367 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
368 /// them up and then emit token factor nodes when possible. This allows us to
369 /// get simple disambiguation between loads without worrying about alias
370 /// analysis.
371 std::vector<SDOperand> PendingLoads;
372
Nate Begemanf15485a2006-03-27 01:32:24 +0000373 /// Case - A pair of values to record the Value for a switch case, and the
374 /// case's target basic block.
375 typedef std::pair<Constant*, MachineBasicBlock*> Case;
376 typedef std::vector<Case>::iterator CaseItr;
377 typedef std::pair<CaseItr, CaseItr> CaseRange;
378
379 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
380 /// of conditional branches.
381 struct CaseRec {
382 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
383 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
384
385 /// CaseBB - The MBB in which to emit the compare and branch
386 MachineBasicBlock *CaseBB;
387 /// LT, GE - If nonzero, we know the current case value must be less-than or
388 /// greater-than-or-equal-to these Constants.
389 Constant *LT;
390 Constant *GE;
391 /// Range - A pair of iterators representing the range of case values to be
392 /// processed at this point in the binary search tree.
393 CaseRange Range;
394 };
395
396 /// The comparison function for sorting Case values.
397 struct CaseCmp {
398 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000399 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
400 return cast<const ConstantInt>(C1.first)->getZExtValue() <
401 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000402 }
403 };
404
Chris Lattner1c08c712005-01-07 07:47:53 +0000405public:
406 // TLI - This is information that describes the available target features we
407 // need for lowering. This indicates when operations are unavailable,
408 // implemented with a libcall, etc.
409 TargetLowering &TLI;
410 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000411 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000412
Nate Begemanf15485a2006-03-27 01:32:24 +0000413 /// SwitchCases - Vector of CaseBlock structures used to communicate
414 /// SwitchInst code generation information.
415 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000416 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000417
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 /// FuncInfo - Information about the function as a whole.
419 ///
420 FunctionLoweringInfo &FuncInfo;
421
422 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000423 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000424 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000425 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 }
427
Chris Lattnera651cf62005-01-17 19:43:36 +0000428 /// getRoot - Return the current virtual root of the Selection DAG.
429 ///
430 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000431 if (PendingLoads.empty())
432 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000433
Chris Lattnerd3948112005-01-17 22:19:26 +0000434 if (PendingLoads.size() == 1) {
435 SDOperand Root = PendingLoads[0];
436 DAG.setRoot(Root);
437 PendingLoads.clear();
438 return Root;
439 }
440
441 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000442 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
443 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000444 PendingLoads.clear();
445 DAG.setRoot(Root);
446 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000447 }
448
Chris Lattner571e4342006-10-27 21:36:01 +0000449 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
450
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 void visit(Instruction &I) { visit(I.getOpcode(), I); }
452
453 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000454 // Note: this doesn't use InstVisitor, because it has to work with
455 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000456 switch (Opcode) {
457 default: assert(0 && "Unknown instruction type encountered!");
458 abort();
459 // Build the switch statement using the Instruction.def file.
460#define HANDLE_INST(NUM, OPCODE, CLASS) \
461 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
462#include "llvm/Instruction.def"
463 }
464 }
465
466 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
467
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000468 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000469 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000470 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000471
472 SDOperand getIntPtrConstant(uint64_t Val) {
473 return DAG.getConstant(Val, TLI.getPointerTy());
474 }
475
Chris Lattner199862b2006-03-16 19:57:50 +0000476 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000477
478 const SDOperand &setValue(const Value *V, SDOperand NewN) {
479 SDOperand &N = NodeMap[V];
480 assert(N.Val == 0 && "Already set a value for this node!");
481 return N = NewN;
482 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000483
Chris Lattner864635a2006-02-22 22:37:12 +0000484 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
485 MVT::ValueType VT,
486 bool OutReg, bool InReg,
487 std::set<unsigned> &OutputRegs,
488 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000489
Chris Lattner571e4342006-10-27 21:36:01 +0000490 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
491 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
492 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000493 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000494 void ExportFromCurrentBlock(Value *V);
495
Chris Lattner1c08c712005-01-07 07:47:53 +0000496 // Terminator instructions.
497 void visitRet(ReturnInst &I);
498 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000499 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000500 void visitUnreachable(UnreachableInst &I) { /* noop */ }
501
Nate Begemanf15485a2006-03-27 01:32:24 +0000502 // Helper for visitSwitch
503 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000504 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000505
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000507 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
508 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
509
Reid Spencer1628cec2006-10-26 06:15:43 +0000510 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
511 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000512 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000513 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000514 if (I.getType()->isFloatingPoint())
515 visitFPBinary(I, ISD::FADD, ISD::VADD);
516 else
517 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000518 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000519 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 void visitMul(User &I) {
521 if (I.getType()->isFloatingPoint())
522 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
523 else
524 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000525 }
Reid Spencer0a783f72006-11-02 01:53:59 +0000526 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
527 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
528 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000529 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
530 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer0a783f72006-11-02 01:53:59 +0000531 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000532 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
533 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
534 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000535 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000536 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
537 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000538 void visitICmp(User &I);
539 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000540 // Visit the conversion instructions
541 void visitTrunc(User &I);
542 void visitZExt(User &I);
543 void visitSExt(User &I);
544 void visitFPTrunc(User &I);
545 void visitFPExt(User &I);
546 void visitFPToUI(User &I);
547 void visitFPToSI(User &I);
548 void visitUIToFP(User &I);
549 void visitSIToFP(User &I);
550 void visitPtrToInt(User &I);
551 void visitIntToPtr(User &I);
552 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000553
Chris Lattner2bbd8102006-03-29 00:11:43 +0000554 void visitExtractElement(User &I);
555 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000556 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000557
Chris Lattner1c08c712005-01-07 07:47:53 +0000558 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000559 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000560
561 void visitMalloc(MallocInst &I);
562 void visitFree(FreeInst &I);
563 void visitAlloca(AllocaInst &I);
564 void visitLoad(LoadInst &I);
565 void visitStore(StoreInst &I);
566 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
567 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000568 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000569 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000570 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000571
Chris Lattner1c08c712005-01-07 07:47:53 +0000572 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000573 void visitVAArg(VAArgInst &I);
574 void visitVAEnd(CallInst &I);
575 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000576 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000577
Chris Lattner7041ee32005-01-11 05:56:49 +0000578 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000579
580 void visitUserOp1(Instruction &I) {
581 assert(0 && "UserOp1 should not exist at instruction selection time!");
582 abort();
583 }
584 void visitUserOp2(Instruction &I) {
585 assert(0 && "UserOp2 should not exist at instruction selection time!");
586 abort();
587 }
588};
589} // end namespace llvm
590
Chris Lattner199862b2006-03-16 19:57:50 +0000591SDOperand SelectionDAGLowering::getValue(const Value *V) {
592 SDOperand &N = NodeMap[V];
593 if (N.Val) return N;
594
595 const Type *VTy = V->getType();
596 MVT::ValueType VT = TLI.getValueType(VTy);
597 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
599 visit(CE->getOpcode(), *CE);
600 assert(N.Val && "visit didn't populate the ValueMap!");
601 return N;
602 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
603 return N = DAG.getGlobalAddress(GV, VT);
604 } else if (isa<ConstantPointerNull>(C)) {
605 return N = DAG.getConstant(0, TLI.getPointerTy());
606 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000607 if (!isa<PackedType>(VTy))
608 return N = DAG.getNode(ISD::UNDEF, VT);
609
Chris Lattnerb2827b02006-03-19 00:52:58 +0000610 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000611 const PackedType *PTy = cast<PackedType>(VTy);
612 unsigned NumElements = PTy->getNumElements();
613 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
614
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000615 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000616 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
617
618 // Create a VConstant node with generic Vector type.
619 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
620 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000621 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
622 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000623 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
624 return N = DAG.getConstantFP(CFP->getValue(), VT);
625 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
626 unsigned NumElements = PTy->getNumElements();
627 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000628
629 // Now that we know the number and type of the elements, push a
630 // Constant or ConstantFP node onto the ops list for each element of
631 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000632 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000633 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000634 for (unsigned i = 0; i != NumElements; ++i)
635 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000636 } else {
637 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
638 SDOperand Op;
639 if (MVT::isFloatingPoint(PVT))
640 Op = DAG.getConstantFP(0, PVT);
641 else
642 Op = DAG.getConstant(0, PVT);
643 Ops.assign(NumElements, Op);
644 }
645
Chris Lattnerb2827b02006-03-19 00:52:58 +0000646 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000647 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
648 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000649 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000650 } else {
651 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000652 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000653 }
654 }
655
656 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
657 std::map<const AllocaInst*, int>::iterator SI =
658 FuncInfo.StaticAllocaMap.find(AI);
659 if (SI != FuncInfo.StaticAllocaMap.end())
660 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
661 }
662
663 std::map<const Value*, unsigned>::const_iterator VMI =
664 FuncInfo.ValueMap.find(V);
665 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
666
667 unsigned InReg = VMI->second;
668
669 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000670 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000671 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000672 // Source must be expanded. This input value is actually coming from the
673 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000674 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
675 unsigned NumVals = TLI.getNumElements(VT);
676 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
677 if (NumVals == 1)
678 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
679 else {
680 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
681 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
682 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
683 }
684 } else {
685 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
686 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
687 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
688 N = MVT::isFloatingPoint(VT)
689 ? DAG.getNode(ISD::FP_ROUND, VT, N)
690 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000691 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000692 } else {
693 // Otherwise, if this is a vector, make it available as a generic vector
694 // here.
695 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000696 const PackedType *PTy = cast<PackedType>(VTy);
697 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000698 PTyLegalElementVT);
699
700 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000701 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000702 if (PTyElementVT == PTyLegalElementVT) {
703 // If the value types are legal, just VBUILD the CopyFromReg nodes.
704 for (unsigned i = 0; i != NE; ++i)
705 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
706 PTyElementVT));
707 } else if (PTyElementVT < PTyLegalElementVT) {
708 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
709 for (unsigned i = 0; i != NE; ++i) {
710 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 PTyElementVT);
712 if (MVT::isFloatingPoint(PTyElementVT))
713 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
714 else
715 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
716 Ops.push_back(Op);
717 }
718 } else {
719 // If the register was expanded, use BUILD_PAIR.
720 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
721 for (unsigned i = 0; i != NE/2; ++i) {
722 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
723 PTyElementVT);
724 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
725 PTyElementVT);
726 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
727 }
728 }
729
730 Ops.push_back(DAG.getConstant(NE, MVT::i32));
731 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000732 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000733
734 // Finally, use a VBIT_CONVERT to make this available as the appropriate
735 // vector type.
736 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
737 DAG.getConstant(PTy->getNumElements(),
738 MVT::i32),
739 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000740 }
741
742 return N;
743}
744
745
Chris Lattner1c08c712005-01-07 07:47:53 +0000746void SelectionDAGLowering::visitRet(ReturnInst &I) {
747 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000748 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000749 return;
750 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000751 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000752 NewValues.push_back(getRoot());
753 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
754 SDOperand RetOp = getValue(I.getOperand(i));
755
756 // If this is an integer return value, we need to promote it ourselves to
757 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
758 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000759 // FIXME: C calling convention requires the return type to be promoted to
760 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000761 if (MVT::isInteger(RetOp.getValueType()) &&
762 RetOp.getValueType() < MVT::i64) {
763 MVT::ValueType TmpVT;
764 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
765 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
766 else
767 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000768 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
769 ISD::NodeType ExtendKind = ISD::SIGN_EXTEND;
770 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
771 ExtendKind = ISD::ZERO_EXTEND;
772 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000773 }
774 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000775 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000776 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000777 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
778 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000779}
780
Chris Lattner571e4342006-10-27 21:36:01 +0000781/// ExportFromCurrentBlock - If this condition isn't known to be exported from
782/// the current basic block, add it to ValueMap now so that we'll get a
783/// CopyTo/FromReg.
784void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
785 // No need to export constants.
786 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
787
788 // Already exported?
789 if (FuncInfo.isExportedInst(V)) return;
790
791 unsigned Reg = FuncInfo.InitializeRegForValue(V);
792 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
793}
794
Chris Lattner8c494ab2006-10-27 23:50:33 +0000795bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
796 const BasicBlock *FromBB) {
797 // The operands of the setcc have to be in this block. We don't know
798 // how to export them from some other block.
799 if (Instruction *VI = dyn_cast<Instruction>(V)) {
800 // Can export from current BB.
801 if (VI->getParent() == FromBB)
802 return true;
803
804 // Is already exported, noop.
805 return FuncInfo.isExportedInst(V);
806 }
807
808 // If this is an argument, we can export it if the BB is the entry block or
809 // if it is already exported.
810 if (isa<Argument>(V)) {
811 if (FromBB == &FromBB->getParent()->getEntryBlock())
812 return true;
813
814 // Otherwise, can only export this if it is already exported.
815 return FuncInfo.isExportedInst(V);
816 }
817
818 // Otherwise, constants can always be exported.
819 return true;
820}
821
Chris Lattner6a586c82006-10-29 21:01:20 +0000822static bool InBlock(const Value *V, const BasicBlock *BB) {
823 if (const Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() == BB;
825 return true;
826}
827
Chris Lattner571e4342006-10-27 21:36:01 +0000828/// FindMergedConditions - If Cond is an expression like
829void SelectionDAGLowering::FindMergedConditions(Value *Cond,
830 MachineBasicBlock *TBB,
831 MachineBasicBlock *FBB,
832 MachineBasicBlock *CurBB,
833 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000834 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000835 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000836
Reid Spencere4d87aa2006-12-23 06:05:41 +0000837 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
838 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000839 BOp->getParent() != CurBB->getBasicBlock() ||
840 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
841 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000842 const BasicBlock *BB = CurBB->getBasicBlock();
843
Chris Lattnerdf19f272006-10-31 22:37:42 +0000844 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
845 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
846 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
847 // The operands of the setcc have to be in this block. We don't know
848 // how to export them from some other block. If this is the first
849 // block of the sequence, no exporting is needed.
850 (CurBB == CurMBB ||
851 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
852 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
853 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
854 II->getOperand(2), TBB, FBB, CurBB);
855 SwitchCases.push_back(CB);
856 return;
857 }
858
859
Reid Spencere4d87aa2006-12-23 06:05:41 +0000860 // If the leaf of the tree is a comparison, merge the condition into
861 // the caseblock.
862 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
863 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000864 // how to export them from some other block. If this is the first block
865 // of the sequence, no exporting is needed.
866 (CurBB == CurMBB ||
867 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
868 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000869 BOp = cast<Instruction>(Cond);
870 ISD::CondCode Condition;
871 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
872 switch (IC->getPredicate()) {
873 default: assert(0 && "Unknown icmp predicate opcode!");
874 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
875 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
876 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
877 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
878 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
879 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
880 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
881 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
882 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
883 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
884 }
885 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
886 ISD::CondCode FPC, FOC;
887 switch (FC->getPredicate()) {
888 default: assert(0 && "Unknown fcmp predicate opcode!");
889 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
890 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
891 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
892 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
893 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
894 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
895 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
896 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
897 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
898 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
899 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
900 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
901 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
902 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
903 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
904 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
905 }
906 if (FiniteOnlyFPMath())
907 Condition = FOC;
908 else
909 Condition = FPC;
910 } else {
911 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000912 }
913
Chris Lattner571e4342006-10-27 21:36:01 +0000914 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
915 BOp->getOperand(1), TBB, FBB, CurBB);
916 SwitchCases.push_back(CB);
917 return;
918 }
919
920 // Create a CaseBlock record representing this branch.
921 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
922 TBB, FBB, CurBB);
923 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000924 return;
925 }
926
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000927
928 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000929 MachineFunction::iterator BBI = CurBB;
930 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
931 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
932
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000933 if (Opc == Instruction::Or) {
934 // Codegen X | Y as:
935 // jmp_if_X TBB
936 // jmp TmpBB
937 // TmpBB:
938 // jmp_if_Y TBB
939 // jmp FBB
940 //
Chris Lattner571e4342006-10-27 21:36:01 +0000941
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000942 // Emit the LHS condition.
943 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
944
945 // Emit the RHS condition into TmpBB.
946 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
947 } else {
948 assert(Opc == Instruction::And && "Unknown merge op!");
949 // Codegen X & Y as:
950 // jmp_if_X TmpBB
951 // jmp FBB
952 // TmpBB:
953 // jmp_if_Y TBB
954 // jmp FBB
955 //
956 // This requires creation of TmpBB after CurBB.
957
958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
960
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
963 }
Chris Lattner571e4342006-10-27 21:36:01 +0000964}
965
Chris Lattnerdf19f272006-10-31 22:37:42 +0000966/// If the set of cases should be emitted as a series of branches, return true.
967/// If we should emit this as a bunch of and/or'd together conditions, return
968/// false.
969static bool
970ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
971 if (Cases.size() != 2) return true;
972
Chris Lattner0ccb5002006-10-31 23:06:00 +0000973 // If this is two comparisons of the same values or'd or and'd together, they
974 // will get folded into a single comparison, so don't emit two blocks.
975 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
976 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
977 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
978 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
979 return false;
980 }
981
Chris Lattnerdf19f272006-10-31 22:37:42 +0000982 return true;
983}
984
Chris Lattner1c08c712005-01-07 07:47:53 +0000985void SelectionDAGLowering::visitBr(BranchInst &I) {
986 // Update machine-CFG edges.
987 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000988
989 // Figure out which block is immediately after the current one.
990 MachineBasicBlock *NextBlock = 0;
991 MachineFunction::iterator BBI = CurMBB;
992 if (++BBI != CurMBB->getParent()->end())
993 NextBlock = BBI;
994
995 if (I.isUnconditional()) {
996 // If this is not a fall-through branch, emit the branch.
997 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000998 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000999 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001000
Chris Lattner57ab6592006-10-24 17:57:59 +00001001 // Update machine-CFG edges.
1002 CurMBB->addSuccessor(Succ0MBB);
1003
1004 return;
1005 }
1006
1007 // If this condition is one of the special cases we handle, do special stuff
1008 // now.
1009 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001010 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001011
1012 // If this is a series of conditions that are or'd or and'd together, emit
1013 // this as a sequence of branches instead of setcc's with and/or operations.
1014 // For example, instead of something like:
1015 // cmp A, B
1016 // C = seteq
1017 // cmp D, E
1018 // F = setle
1019 // or C, F
1020 // jnz foo
1021 // Emit:
1022 // cmp A, B
1023 // je foo
1024 // cmp D, E
1025 // jle foo
1026 //
1027 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1028 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001029 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001030 BOp->getOpcode() == Instruction::Or)) {
1031 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001032 // If the compares in later blocks need to use values not currently
1033 // exported from this block, export them now. This block should always
1034 // be the first entry.
1035 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1036
Chris Lattnerdf19f272006-10-31 22:37:42 +00001037 // Allow some cases to be rejected.
1038 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001039 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1040 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1041 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1042 }
1043
1044 // Emit the branch for this block.
1045 visitSwitchCase(SwitchCases[0]);
1046 SwitchCases.erase(SwitchCases.begin());
1047 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001048 }
1049
Chris Lattner0ccb5002006-10-31 23:06:00 +00001050 // Okay, we decided not to do this, remove any inserted MBB's and clear
1051 // SwitchCases.
1052 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1053 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1054
Chris Lattnerdf19f272006-10-31 22:37:42 +00001055 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001056 }
1057 }
Chris Lattner24525952006-10-24 18:07:37 +00001058
1059 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +00001060 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001061 Succ0MBB, Succ1MBB, CurMBB);
1062 // Use visitSwitchCase to actually insert the fast branch sequence for this
1063 // cond branch.
1064 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001065}
1066
Nate Begemanf15485a2006-03-27 01:32:24 +00001067/// visitSwitchCase - Emits the necessary code to represent a single node in
1068/// the binary search tree resulting from lowering a switch instruction.
1069void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001070 SDOperand Cond;
1071 SDOperand CondLHS = getValue(CB.CmpLHS);
1072
Chris Lattner571e4342006-10-27 21:36:01 +00001073 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1074 // handle common cases produced by branch lowering.
1075 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001076 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +00001077 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1078 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1079 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1080 } else
1081 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001082
1083 // Set NextBlock to be the MBB immediately after the current one, if any.
1084 // This is used to avoid emitting unnecessary branches to the next block.
1085 MachineBasicBlock *NextBlock = 0;
1086 MachineFunction::iterator BBI = CurMBB;
1087 if (++BBI != CurMBB->getParent()->end())
1088 NextBlock = BBI;
1089
1090 // If the lhs block is the next block, invert the condition so that we can
1091 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001092 if (CB.TrueBB == NextBlock) {
1093 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001094 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1095 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1096 }
1097 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001098 DAG.getBasicBlock(CB.TrueBB));
1099 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001100 DAG.setRoot(BrCond);
1101 else
1102 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001103 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001104 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001105 CurMBB->addSuccessor(CB.TrueBB);
1106 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001107}
1108
Nate Begeman37efe672006-04-22 18:53:45 +00001109void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001110 // Emit the code for the jump table
1111 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001112 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1113 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1114 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1115 Table, Index));
1116 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001117}
1118
Nate Begemanf15485a2006-03-27 01:32:24 +00001119void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1120 // Figure out which block is immediately after the current one.
1121 MachineBasicBlock *NextBlock = 0;
1122 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001123
Nate Begemanf15485a2006-03-27 01:32:24 +00001124 if (++BBI != CurMBB->getParent()->end())
1125 NextBlock = BBI;
1126
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001127 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1128
Nate Begemanf15485a2006-03-27 01:32:24 +00001129 // If there is only the default destination, branch to it if it is not the
1130 // next basic block. Otherwise, just fall through.
1131 if (I.getNumOperands() == 2) {
1132 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001133
Nate Begemanf15485a2006-03-27 01:32:24 +00001134 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001135 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001136 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001137 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001138
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001139 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001140 return;
1141 }
1142
1143 // If there are any non-default case statements, create a vector of Cases
1144 // representing each one, and sort the vector so that we can efficiently
1145 // create a binary search tree from them.
1146 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001147
Nate Begemanf15485a2006-03-27 01:32:24 +00001148 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1149 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1150 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1151 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001152
Nate Begemanf15485a2006-03-27 01:32:24 +00001153 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1154
1155 // Get the Value to be switched on and default basic blocks, which will be
1156 // inserted into CaseBlock records, representing basic blocks in the binary
1157 // search tree.
1158 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001159
1160 // Get the MachineFunction which holds the current MBB. This is used during
1161 // emission of jump tables, and when inserting any additional MBBs necessary
1162 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001163 MachineFunction *CurMF = CurMBB->getParent();
1164 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001165
1166 // If the switch has few cases (two or less) emit a series of specific
1167 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001168 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001169 // TODO: If any two of the cases has the same destination, and if one value
1170 // is the same as the other, but has one bit unset that the other has set,
1171 // use bit manipulation to do two compares at once. For example:
1172 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1173
Chris Lattnerb3543432006-10-23 18:38:22 +00001174 // Rearrange the case blocks so that the last one falls through if possible.
1175 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1176 // The last case block won't fall through into 'NextBlock' if we emit the
1177 // branches in this order. See if rearranging a case value would help.
1178 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1179 if (Cases[i].second == NextBlock) {
1180 std::swap(Cases[i], Cases.back());
1181 break;
1182 }
1183 }
1184 }
1185
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001186 // Create a CaseBlock record representing a conditional branch to
1187 // the Case's target mbb if the value being switched on SV is equal
1188 // to C.
1189 MachineBasicBlock *CurBlock = CurMBB;
1190 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1191 MachineBasicBlock *FallThrough;
1192 if (i != e-1) {
1193 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1194 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1195 } else {
1196 // If the last case doesn't match, go to the default block.
1197 FallThrough = Default;
1198 }
1199
1200 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1201 Cases[i].second, FallThrough, CurBlock);
1202
1203 // If emitting the first comparison, just call visitSwitchCase to emit the
1204 // code into the current block. Otherwise, push the CaseBlock onto the
1205 // vector to be later processed by SDISel, and insert the node's MBB
1206 // before the next MBB.
1207 if (CurBlock == CurMBB)
1208 visitSwitchCase(CB);
1209 else
1210 SwitchCases.push_back(CB);
1211
1212 CurBlock = FallThrough;
1213 }
1214 return;
1215 }
Nate Begeman37efe672006-04-22 18:53:45 +00001216
Nate Begeman17c275f2006-05-08 16:51:36 +00001217 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1218 // target supports indirect branches, then emit a jump table rather than
1219 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001220 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1221 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001222 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001223 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1224 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001225 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1226
Nate Begeman17c275f2006-05-08 16:51:36 +00001227 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001228 // Create a new basic block to hold the code for loading the address
1229 // of the jump table, and jumping to it. Update successor information;
1230 // we will either branch to the default case for the switch, or the jump
1231 // table.
1232 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1233 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1234 CurMBB->addSuccessor(Default);
1235 CurMBB->addSuccessor(JumpTableBB);
1236
1237 // Subtract the lowest switch case value from the value being switched on
1238 // and conditional branch to default mbb if the result is greater than the
1239 // difference between smallest and largest cases.
1240 SDOperand SwitchOp = getValue(SV);
1241 MVT::ValueType VT = SwitchOp.getValueType();
1242 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1243 DAG.getConstant(First, VT));
1244
1245 // The SDNode we just created, which holds the value being switched on
1246 // minus the the smallest case value, needs to be copied to a virtual
1247 // register so it can be used as an index into the jump table in a
1248 // subsequent basic block. This value may be smaller or larger than the
1249 // target's pointer type, and therefore require extension or truncating.
1250 if (VT > TLI.getPointerTy())
1251 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1252 else
1253 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001254
Nate Begeman37efe672006-04-22 18:53:45 +00001255 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1256 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1257
1258 // Emit the range check for the jump table, and branch to the default
1259 // block for the switch statement if the value being switched on exceeds
1260 // the largest case in the switch.
1261 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1262 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1263 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1264 DAG.getBasicBlock(Default)));
1265
Nate Begemanf4360a42006-05-03 03:48:02 +00001266 // Build a vector of destination BBs, corresponding to each target
1267 // of the jump table. If the value of the jump table slot corresponds to
1268 // a case statement, push the case's BB onto the vector, otherwise, push
1269 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001270 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001271 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001272 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001273 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001274 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001275 ++ii;
1276 } else {
1277 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001278 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001279
Chris Lattner8c494ab2006-10-27 23:50:33 +00001280 // Update successor info. Add one edge to each unique successor.
1281 // Vector bool would be better, but vector<bool> is really slow.
1282 std::vector<unsigned char> SuccsHandled;
1283 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1284
Chris Lattnerc66764c2006-09-10 06:36:57 +00001285 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001286 E = DestBBs.end(); I != E; ++I) {
1287 if (!SuccsHandled[(*I)->getNumber()]) {
1288 SuccsHandled[(*I)->getNumber()] = true;
1289 JumpTableBB->addSuccessor(*I);
1290 }
1291 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001292
1293 // Create a jump table index for this jump table, or return an existing
1294 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001295 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1296
1297 // Set the jump table information so that we can codegen it as a second
1298 // MachineBasicBlock
1299 JT.Reg = JumpTableReg;
1300 JT.JTI = JTI;
1301 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001302 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001303 return;
1304 }
1305 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001306
1307 // Push the initial CaseRec onto the worklist
1308 std::vector<CaseRec> CaseVec;
1309 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1310
1311 while (!CaseVec.empty()) {
1312 // Grab a record representing a case range to process off the worklist
1313 CaseRec CR = CaseVec.back();
1314 CaseVec.pop_back();
1315
1316 // Size is the number of Cases represented by this range. If Size is 1,
1317 // then we are processing a leaf of the binary search tree. Otherwise,
1318 // we need to pick a pivot, and push left and right ranges onto the
1319 // worklist.
1320 unsigned Size = CR.Range.second - CR.Range.first;
1321
1322 if (Size == 1) {
1323 // Create a CaseBlock record representing a conditional branch to
1324 // the Case's target mbb if the value being switched on SV is equal
1325 // to C. Otherwise, branch to default.
1326 Constant *C = CR.Range.first->first;
1327 MachineBasicBlock *Target = CR.Range.first->second;
1328 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1329 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001330
Nate Begemanf15485a2006-03-27 01:32:24 +00001331 // If the MBB representing the leaf node is the current MBB, then just
1332 // call visitSwitchCase to emit the code into the current block.
1333 // Otherwise, push the CaseBlock onto the vector to be later processed
1334 // by SDISel, and insert the node's MBB before the next MBB.
1335 if (CR.CaseBB == CurMBB)
1336 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001337 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001338 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001339 } else {
1340 // split case range at pivot
1341 CaseItr Pivot = CR.Range.first + (Size / 2);
1342 CaseRange LHSR(CR.Range.first, Pivot);
1343 CaseRange RHSR(Pivot, CR.Range.second);
1344 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001345 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001346
Nate Begemanf15485a2006-03-27 01:32:24 +00001347 // We know that we branch to the LHS if the Value being switched on is
1348 // less than the Pivot value, C. We use this to optimize our binary
1349 // tree a bit, by recognizing that if SV is greater than or equal to the
1350 // LHS's Case Value, and that Case Value is exactly one less than the
1351 // Pivot's Value, then we can branch directly to the LHS's Target,
1352 // rather than creating a leaf node for it.
1353 if ((LHSR.second - LHSR.first) == 1 &&
1354 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001355 cast<ConstantIntegral>(C)->getZExtValue() ==
1356 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001357 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001358 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001359 TrueBB = new MachineBasicBlock(LLVMBB);
1360 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1361 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001362 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001363
Nate Begemanf15485a2006-03-27 01:32:24 +00001364 // Similar to the optimization above, if the Value being switched on is
1365 // known to be less than the Constant CR.LT, and the current Case Value
1366 // is CR.LT - 1, then we can branch directly to the target block for
1367 // the current Case Value, rather than emitting a RHS leaf node for it.
1368 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001369 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1370 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001371 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001372 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001373 FalseBB = new MachineBasicBlock(LLVMBB);
1374 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1375 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001376 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001377
Nate Begemanf15485a2006-03-27 01:32:24 +00001378 // Create a CaseBlock record representing a conditional branch to
1379 // the LHS node if the value being switched on SV is less than C.
1380 // Otherwise, branch to LHS.
Reid Spencer47857812006-12-31 05:55:36 +00001381 ISD::CondCode CC = ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001382 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001383
Nate Begemanf15485a2006-03-27 01:32:24 +00001384 if (CR.CaseBB == CurMBB)
1385 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001386 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001387 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001388 }
1389 }
1390}
1391
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001392void SelectionDAGLowering::visitSub(User &I) {
1393 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001394 if (I.getType()->isFloatingPoint()) {
1395 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1396 if (CFP->isExactlyValue(-0.0)) {
1397 SDOperand Op2 = getValue(I.getOperand(1));
1398 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1399 return;
1400 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001401 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1402 } else
1403 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001404}
1405
Reid Spencer1628cec2006-10-26 06:15:43 +00001406void
1407SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001408 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001409 SDOperand Op1 = getValue(I.getOperand(0));
1410 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001411
Reid Spencer1628cec2006-10-26 06:15:43 +00001412 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001413 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1414 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1415 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001416 } else {
1417 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1418 }
1419}
1420
1421void
1422SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1423 const Type *Ty = I.getType();
1424 SDOperand Op1 = getValue(I.getOperand(0));
1425 SDOperand Op2 = getValue(I.getOperand(1));
1426
1427 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1428 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));
1431 } else {
1432 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001433 }
Nate Begemane21ea612005-11-18 07:42:56 +00001434}
Chris Lattner2c49f272005-01-19 22:31:21 +00001435
Nate Begemane21ea612005-11-18 07:42:56 +00001436void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1437 SDOperand Op1 = getValue(I.getOperand(0));
1438 SDOperand Op2 = getValue(I.getOperand(1));
1439
1440 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1441
Chris Lattner1c08c712005-01-07 07:47:53 +00001442 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1443}
1444
Reid Spencer45fb3f32006-11-20 01:22:35 +00001445void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001446 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1447 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1448 predicate = IC->getPredicate();
1449 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1450 predicate = ICmpInst::Predicate(IC->getPredicate());
1451 SDOperand Op1 = getValue(I.getOperand(0));
1452 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001453 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001454 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001455 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1456 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1457 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1458 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1459 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1460 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1461 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1462 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1463 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1464 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1465 default:
1466 assert(!"Invalid ICmp predicate value");
1467 Opcode = ISD::SETEQ;
1468 break;
1469 }
1470 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1471}
1472
1473void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001474 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1475 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1476 predicate = FC->getPredicate();
1477 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1478 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001479 SDOperand Op1 = getValue(I.getOperand(0));
1480 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001481 ISD::CondCode Condition, FOC, FPC;
1482 switch (predicate) {
1483 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1484 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1485 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1486 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1487 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1488 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1489 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1490 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1491 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1492 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1493 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1494 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1495 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1496 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1497 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1498 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1499 default:
1500 assert(!"Invalid FCmp predicate value");
1501 FOC = FPC = ISD::SETFALSE;
1502 break;
1503 }
1504 if (FiniteOnlyFPMath())
1505 Condition = FOC;
1506 else
1507 Condition = FPC;
1508 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001509}
1510
1511void SelectionDAGLowering::visitSelect(User &I) {
1512 SDOperand Cond = getValue(I.getOperand(0));
1513 SDOperand TrueVal = getValue(I.getOperand(1));
1514 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001515 if (!isa<PackedType>(I.getType())) {
1516 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1517 TrueVal, FalseVal));
1518 } else {
1519 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1520 *(TrueVal.Val->op_end()-2),
1521 *(TrueVal.Val->op_end()-1)));
1522 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001523}
1524
Reid Spencer3da59db2006-11-27 01:05:10 +00001525
1526void SelectionDAGLowering::visitTrunc(User &I) {
1527 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1528 SDOperand N = getValue(I.getOperand(0));
1529 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1530 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1531}
1532
1533void SelectionDAGLowering::visitZExt(User &I) {
1534 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1535 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1536 SDOperand N = getValue(I.getOperand(0));
1537 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1538 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1539}
1540
1541void SelectionDAGLowering::visitSExt(User &I) {
1542 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1543 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1544 SDOperand N = getValue(I.getOperand(0));
1545 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1546 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1547}
1548
1549void SelectionDAGLowering::visitFPTrunc(User &I) {
1550 // FPTrunc is never a no-op cast, no need to check
1551 SDOperand N = getValue(I.getOperand(0));
1552 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1553 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1554}
1555
1556void SelectionDAGLowering::visitFPExt(User &I){
1557 // FPTrunc is never a no-op cast, no need to check
1558 SDOperand N = getValue(I.getOperand(0));
1559 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1560 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1561}
1562
1563void SelectionDAGLowering::visitFPToUI(User &I) {
1564 // FPToUI is never a no-op cast, no need to check
1565 SDOperand N = getValue(I.getOperand(0));
1566 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1567 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1568}
1569
1570void SelectionDAGLowering::visitFPToSI(User &I) {
1571 // FPToSI is never a no-op cast, no need to check
1572 SDOperand N = getValue(I.getOperand(0));
1573 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1574 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1575}
1576
1577void SelectionDAGLowering::visitUIToFP(User &I) {
1578 // UIToFP is never a no-op cast, no need to check
1579 SDOperand N = getValue(I.getOperand(0));
1580 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1581 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1582}
1583
1584void SelectionDAGLowering::visitSIToFP(User &I){
1585 // UIToFP is never a no-op cast, no need to check
1586 SDOperand N = getValue(I.getOperand(0));
1587 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1588 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1589}
1590
1591void SelectionDAGLowering::visitPtrToInt(User &I) {
1592 // What to do depends on the size of the integer and the size of the pointer.
1593 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001594 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001595 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001596 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001597 SDOperand Result;
1598 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1599 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1600 else
1601 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1602 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1603 setValue(&I, Result);
1604}
Chris Lattner1c08c712005-01-07 07:47:53 +00001605
Reid Spencer3da59db2006-11-27 01:05:10 +00001606void SelectionDAGLowering::visitIntToPtr(User &I) {
1607 // What to do depends on the size of the integer and the size of the pointer.
1608 // We can either truncate, zero extend, or no-op, accordingly.
1609 SDOperand N = getValue(I.getOperand(0));
1610 MVT::ValueType SrcVT = N.getValueType();
1611 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1612 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1613 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1614 else
1615 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1616 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1617}
1618
1619void SelectionDAGLowering::visitBitCast(User &I) {
1620 SDOperand N = getValue(I.getOperand(0));
1621 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001622 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001623 // This is a cast to a vector from something else.
1624 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001625 const PackedType *DestTy = cast<PackedType>(I.getType());
1626 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1627 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1628 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1629 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001630 return;
1631 }
1632 MVT::ValueType SrcVT = N.getValueType();
1633 if (SrcVT == MVT::Vector) {
1634 // This is a cast from a vctor to something else.
1635 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001636 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001637 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001638 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001639
1640 // BitCast assures us that source and destination are the same size so this
1641 // is either a BIT_CONVERT or a no-op.
1642 if (DestVT != N.getValueType())
1643 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1644 else
1645 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001646}
1647
Chris Lattner2bbd8102006-03-29 00:11:43 +00001648void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001649 SDOperand InVec = getValue(I.getOperand(0));
1650 SDOperand InVal = getValue(I.getOperand(1));
1651 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1652 getValue(I.getOperand(2)));
1653
Chris Lattner2332b9f2006-03-19 01:17:20 +00001654 SDOperand Num = *(InVec.Val->op_end()-2);
1655 SDOperand Typ = *(InVec.Val->op_end()-1);
1656 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1657 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001658}
1659
Chris Lattner2bbd8102006-03-29 00:11:43 +00001660void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001661 SDOperand InVec = getValue(I.getOperand(0));
1662 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1663 getValue(I.getOperand(1)));
1664 SDOperand Typ = *(InVec.Val->op_end()-1);
1665 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1666 TLI.getValueType(I.getType()), InVec, InIdx));
1667}
Chris Lattnerc7029802006-03-18 01:44:44 +00001668
Chris Lattner3e104b12006-04-08 04:15:24 +00001669void SelectionDAGLowering::visitShuffleVector(User &I) {
1670 SDOperand V1 = getValue(I.getOperand(0));
1671 SDOperand V2 = getValue(I.getOperand(1));
1672 SDOperand Mask = getValue(I.getOperand(2));
1673
1674 SDOperand Num = *(V1.Val->op_end()-2);
1675 SDOperand Typ = *(V2.Val->op_end()-1);
1676 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1677 V1, V2, Mask, Num, Typ));
1678}
1679
1680
Chris Lattner1c08c712005-01-07 07:47:53 +00001681void SelectionDAGLowering::visitGetElementPtr(User &I) {
1682 SDOperand N = getValue(I.getOperand(0));
1683 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001684
1685 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1686 OI != E; ++OI) {
1687 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001688 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001689 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001690 if (Field) {
1691 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001692 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001693 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001694 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001695 }
1696 Ty = StTy->getElementType(Field);
1697 } else {
1698 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001699
Chris Lattner7c0104b2005-11-09 04:45:33 +00001700 // If this is a constant subscript, handle it quickly.
1701 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001702 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001703 uint64_t Offs =
Reid Spencerb83eb642006-10-20 07:07:24 +00001704 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001705 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1706 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001707 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001708
1709 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001710 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001711 SDOperand IdxN = getValue(Idx);
1712
1713 // If the index is smaller or larger than intptr_t, truncate or extend
1714 // it.
1715 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001716 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001717 } else if (IdxN.getValueType() > N.getValueType())
1718 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1719
1720 // If this is a multiply by a power of two, turn it into a shl
1721 // immediately. This is a very common case.
1722 if (isPowerOf2_64(ElementSize)) {
1723 unsigned Amt = Log2_64(ElementSize);
1724 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001725 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001726 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1727 continue;
1728 }
1729
1730 SDOperand Scale = getIntPtrConstant(ElementSize);
1731 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1732 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001733 }
1734 }
1735 setValue(&I, N);
1736}
1737
1738void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1739 // If this is a fixed sized alloca in the entry block of the function,
1740 // allocate it statically on the stack.
1741 if (FuncInfo.StaticAllocaMap.count(&I))
1742 return; // getValue will auto-populate this.
1743
1744 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001745 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1746 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001747 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001748
1749 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001750 MVT::ValueType IntPtr = TLI.getPointerTy();
1751 if (IntPtr < AllocSize.getValueType())
1752 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1753 else if (IntPtr > AllocSize.getValueType())
1754 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001755
Chris Lattner68cd65e2005-01-22 23:04:37 +00001756 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001757 getIntPtrConstant(TySize));
1758
1759 // Handle alignment. If the requested alignment is less than or equal to the
1760 // stack alignment, ignore it and round the size of the allocation up to the
1761 // stack alignment size. If the size is greater than the stack alignment, we
1762 // note this in the DYNAMIC_STACKALLOC node.
1763 unsigned StackAlign =
1764 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1765 if (Align <= StackAlign) {
1766 Align = 0;
1767 // Add SA-1 to the size.
1768 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1769 getIntPtrConstant(StackAlign-1));
1770 // Mask out the low bits for alignment purposes.
1771 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1772 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1773 }
1774
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001775 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001776 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1777 MVT::Other);
1778 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001779 DAG.setRoot(setValue(&I, DSA).getValue(1));
1780
1781 // Inform the Frame Information that we have just allocated a variable-sized
1782 // object.
1783 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1784}
1785
Chris Lattner1c08c712005-01-07 07:47:53 +00001786void SelectionDAGLowering::visitLoad(LoadInst &I) {
1787 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001788
Chris Lattnerd3948112005-01-17 22:19:26 +00001789 SDOperand Root;
1790 if (I.isVolatile())
1791 Root = getRoot();
1792 else {
1793 // Do not serialize non-volatile loads against each other.
1794 Root = DAG.getRoot();
1795 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001796
Evan Cheng466685d2006-10-09 20:57:25 +00001797 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001798 Root, I.isVolatile()));
1799}
1800
1801SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001802 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001803 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001804 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001805 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001806 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001807 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1808 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001809 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001810 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001811 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001812
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001813 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001814 DAG.setRoot(L.getValue(1));
1815 else
1816 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001817
1818 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001819}
1820
1821
1822void SelectionDAGLowering::visitStore(StoreInst &I) {
1823 Value *SrcV = I.getOperand(0);
1824 SDOperand Src = getValue(SrcV);
1825 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001826 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001827 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001828}
1829
Chris Lattner0eade312006-03-24 02:22:33 +00001830/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1831/// access memory and has no other side effects at all.
1832static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1833#define GET_NO_MEMORY_INTRINSICS
1834#include "llvm/Intrinsics.gen"
1835#undef GET_NO_MEMORY_INTRINSICS
1836 return false;
1837}
1838
Chris Lattnere58a7802006-04-02 03:41:14 +00001839// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1840// have any side-effects or if it only reads memory.
1841static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1842#define GET_SIDE_EFFECT_INFO
1843#include "llvm/Intrinsics.gen"
1844#undef GET_SIDE_EFFECT_INFO
1845 return false;
1846}
1847
Chris Lattner0eade312006-03-24 02:22:33 +00001848/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1849/// node.
1850void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1851 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001852 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001853 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001854
1855 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001856 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001857 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1858 if (OnlyLoad) {
1859 // We don't need to serialize loads against other loads.
1860 Ops.push_back(DAG.getRoot());
1861 } else {
1862 Ops.push_back(getRoot());
1863 }
1864 }
Chris Lattner0eade312006-03-24 02:22:33 +00001865
1866 // Add the intrinsic ID as an integer operand.
1867 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1868
1869 // Add all operands of the call to the operand list.
1870 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1871 SDOperand Op = getValue(I.getOperand(i));
1872
1873 // If this is a vector type, force it to the right packed type.
1874 if (Op.getValueType() == MVT::Vector) {
1875 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1876 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1877
1878 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1879 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1880 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1881 }
1882
1883 assert(TLI.isTypeLegal(Op.getValueType()) &&
1884 "Intrinsic uses a non-legal type?");
1885 Ops.push_back(Op);
1886 }
1887
1888 std::vector<MVT::ValueType> VTs;
1889 if (I.getType() != Type::VoidTy) {
1890 MVT::ValueType VT = TLI.getValueType(I.getType());
1891 if (VT == MVT::Vector) {
1892 const PackedType *DestTy = cast<PackedType>(I.getType());
1893 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1894
1895 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1896 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1897 }
1898
1899 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1900 VTs.push_back(VT);
1901 }
1902 if (HasChain)
1903 VTs.push_back(MVT::Other);
1904
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001905 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1906
Chris Lattner0eade312006-03-24 02:22:33 +00001907 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001908 SDOperand Result;
1909 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001910 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1911 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001912 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001913 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1914 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001915 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001916 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1917 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001918
Chris Lattnere58a7802006-04-02 03:41:14 +00001919 if (HasChain) {
1920 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1921 if (OnlyLoad)
1922 PendingLoads.push_back(Chain);
1923 else
1924 DAG.setRoot(Chain);
1925 }
Chris Lattner0eade312006-03-24 02:22:33 +00001926 if (I.getType() != Type::VoidTy) {
1927 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1928 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1929 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1930 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1931 DAG.getValueType(EVT));
1932 }
1933 setValue(&I, Result);
1934 }
1935}
1936
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001937/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1938/// we want to emit this as a call to a named external function, return the name
1939/// otherwise lower it and return null.
1940const char *
1941SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1942 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001943 default:
1944 // By default, turn this into a target intrinsic node.
1945 visitTargetIntrinsic(I, Intrinsic);
1946 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001947 case Intrinsic::vastart: visitVAStart(I); return 0;
1948 case Intrinsic::vaend: visitVAEnd(I); return 0;
1949 case Intrinsic::vacopy: visitVACopy(I); return 0;
1950 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1951 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1952 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001953 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001954 break;
1955 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001956 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001957 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001958 case Intrinsic::memcpy_i32:
1959 case Intrinsic::memcpy_i64:
1960 visitMemIntrinsic(I, ISD::MEMCPY);
1961 return 0;
1962 case Intrinsic::memset_i32:
1963 case Intrinsic::memset_i64:
1964 visitMemIntrinsic(I, ISD::MEMSET);
1965 return 0;
1966 case Intrinsic::memmove_i32:
1967 case Intrinsic::memmove_i64:
1968 visitMemIntrinsic(I, ISD::MEMMOVE);
1969 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001970
Chris Lattner86cb6432005-12-13 17:40:33 +00001971 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001972 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001973 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001974 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001975 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001976
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001977 Ops[0] = getRoot();
1978 Ops[1] = getValue(SPI.getLineValue());
1979 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001980
Jim Laskey43970fe2006-03-23 18:06:46 +00001981 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001982 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001983 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1984
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001985 Ops[3] = DAG.getString(CompileUnit->getFileName());
1986 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001987
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001988 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001989 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001990
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001991 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001992 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001993 case Intrinsic::dbg_region_start: {
1994 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1995 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001996 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001997 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001998 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1999 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002000 }
2001
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002002 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002003 }
2004 case Intrinsic::dbg_region_end: {
2005 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2006 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002007 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002008 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002009 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2010 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002011 }
2012
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002013 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002014 }
2015 case Intrinsic::dbg_func_start: {
2016 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2017 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002018 if (DebugInfo && FSI.getSubprogram() &&
2019 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002020 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002021 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2022 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002023 }
2024
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002025 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002026 }
2027 case Intrinsic::dbg_declare: {
2028 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2029 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00002030 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002031 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002032 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00002033 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002034 }
2035
2036 return 0;
2037 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002038
Reid Spencer0b118202006-01-16 21:12:35 +00002039 case Intrinsic::isunordered_f32:
2040 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002041 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2042 getValue(I.getOperand(2)), ISD::SETUO));
2043 return 0;
2044
Reid Spencer0b118202006-01-16 21:12:35 +00002045 case Intrinsic::sqrt_f32:
2046 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002047 setValue(&I, DAG.getNode(ISD::FSQRT,
2048 getValue(I.getOperand(1)).getValueType(),
2049 getValue(I.getOperand(1))));
2050 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002051 case Intrinsic::powi_f32:
2052 case Intrinsic::powi_f64:
2053 setValue(&I, DAG.getNode(ISD::FPOWI,
2054 getValue(I.getOperand(1)).getValueType(),
2055 getValue(I.getOperand(1)),
2056 getValue(I.getOperand(2))));
2057 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002058 case Intrinsic::pcmarker: {
2059 SDOperand Tmp = getValue(I.getOperand(1));
2060 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2061 return 0;
2062 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002063 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002064 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002065 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2066 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2067 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002068 setValue(&I, Tmp);
2069 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002070 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002071 }
Nate Begemand88fc032006-01-14 03:14:10 +00002072 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002073 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002074 case Intrinsic::bswap_i64:
2075 setValue(&I, DAG.getNode(ISD::BSWAP,
2076 getValue(I.getOperand(1)).getValueType(),
2077 getValue(I.getOperand(1))));
2078 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002079 case Intrinsic::cttz_i8:
2080 case Intrinsic::cttz_i16:
2081 case Intrinsic::cttz_i32:
2082 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002083 setValue(&I, DAG.getNode(ISD::CTTZ,
2084 getValue(I.getOperand(1)).getValueType(),
2085 getValue(I.getOperand(1))));
2086 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002087 case Intrinsic::ctlz_i8:
2088 case Intrinsic::ctlz_i16:
2089 case Intrinsic::ctlz_i32:
2090 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002091 setValue(&I, DAG.getNode(ISD::CTLZ,
2092 getValue(I.getOperand(1)).getValueType(),
2093 getValue(I.getOperand(1))));
2094 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002095 case Intrinsic::ctpop_i8:
2096 case Intrinsic::ctpop_i16:
2097 case Intrinsic::ctpop_i32:
2098 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002099 setValue(&I, DAG.getNode(ISD::CTPOP,
2100 getValue(I.getOperand(1)).getValueType(),
2101 getValue(I.getOperand(1))));
2102 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002103 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002104 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002105 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2106 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002107 setValue(&I, Tmp);
2108 DAG.setRoot(Tmp.getValue(1));
2109 return 0;
2110 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002111 case Intrinsic::stackrestore: {
2112 SDOperand Tmp = getValue(I.getOperand(1));
2113 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002114 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002115 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002116 case Intrinsic::prefetch:
2117 // FIXME: Currently discarding prefetches.
2118 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002119 }
2120}
2121
2122
Chris Lattner1c08c712005-01-07 07:47:53 +00002123void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002124 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002125 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002126 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002127 if (unsigned IID = F->getIntrinsicID()) {
2128 RenameFn = visitIntrinsicCall(I, IID);
2129 if (!RenameFn)
2130 return;
2131 } else { // Not an LLVM intrinsic.
2132 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002133 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2134 if (I.getNumOperands() == 3 && // Basic sanity checks.
2135 I.getOperand(1)->getType()->isFloatingPoint() &&
2136 I.getType() == I.getOperand(1)->getType() &&
2137 I.getType() == I.getOperand(2)->getType()) {
2138 SDOperand LHS = getValue(I.getOperand(1));
2139 SDOperand RHS = getValue(I.getOperand(2));
2140 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2141 LHS, RHS));
2142 return;
2143 }
2144 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002145 if (I.getNumOperands() == 2 && // Basic sanity checks.
2146 I.getOperand(1)->getType()->isFloatingPoint() &&
2147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002149 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2150 return;
2151 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002152 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002153 if (I.getNumOperands() == 2 && // Basic sanity checks.
2154 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002155 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002156 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002157 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2158 return;
2159 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002160 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002161 if (I.getNumOperands() == 2 && // Basic sanity checks.
2162 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002163 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002164 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002165 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2166 return;
2167 }
2168 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002169 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002170 } else if (isa<InlineAsm>(I.getOperand(0))) {
2171 visitInlineAsm(I);
2172 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002173 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002174
Reid Spencer47857812006-12-31 05:55:36 +00002175 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2176 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2177
Chris Lattner64e14b12005-01-08 22:48:57 +00002178 SDOperand Callee;
2179 if (!RenameFn)
2180 Callee = getValue(I.getOperand(0));
2181 else
2182 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencer47857812006-12-31 05:55:36 +00002183 TargetLowering::ArgListTy Args;
2184 TargetLowering::ArgListEntry Entry;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002185 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002186 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2187 Value *Arg = I.getOperand(i);
2188 SDOperand ArgNode = getValue(Arg);
Reid Spencer47857812006-12-31 05:55:36 +00002189 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2190 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2191 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002192 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002193
Chris Lattnercf5734d2005-01-08 19:26:18 +00002194 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002195 TLI.LowerCallTo(getRoot(), I.getType(),
2196 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2197 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2198 Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002199 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002200 setValue(&I, Result.first);
2201 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002202}
2203
Chris Lattner864635a2006-02-22 22:37:12 +00002204SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002205 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002206 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2207 Chain = Val.getValue(1);
2208 Flag = Val.getValue(2);
2209
2210 // If the result was expanded, copy from the top part.
2211 if (Regs.size() > 1) {
2212 assert(Regs.size() == 2 &&
2213 "Cannot expand to more than 2 elts yet!");
2214 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002215 Chain = Hi.getValue(1);
2216 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002217 if (DAG.getTargetLoweringInfo().isLittleEndian())
2218 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2219 else
2220 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002221 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002222
Chris Lattnercf752aa2006-06-08 18:22:48 +00002223 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002224 // appropriate type.
2225 if (RegVT == ValueVT)
2226 return Val;
2227
Chris Lattnercf752aa2006-06-08 18:22:48 +00002228 if (MVT::isInteger(RegVT)) {
2229 if (ValueVT < RegVT)
2230 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2231 else
2232 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2233 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002234 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002235 }
Chris Lattner864635a2006-02-22 22:37:12 +00002236}
2237
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002238/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2239/// specified value into the registers specified by this object. This uses
2240/// Chain/Flag as the input and updates them for the output Chain/Flag.
2241void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002242 SDOperand &Chain, SDOperand &Flag,
2243 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002244 if (Regs.size() == 1) {
2245 // If there is a single register and the types differ, this must be
2246 // a promotion.
2247 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002248 if (MVT::isInteger(RegVT)) {
2249 if (RegVT < ValueVT)
2250 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2251 else
2252 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2253 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002254 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2255 }
2256 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2257 Flag = Chain.getValue(1);
2258 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002259 std::vector<unsigned> R(Regs);
2260 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2261 std::reverse(R.begin(), R.end());
2262
2263 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002264 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002265 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002266 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002267 Flag = Chain.getValue(1);
2268 }
2269 }
2270}
Chris Lattner864635a2006-02-22 22:37:12 +00002271
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002272/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2273/// operand list. This adds the code marker and includes the number of
2274/// values added into it.
2275void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002276 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002277 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2278 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2279 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2280}
Chris Lattner864635a2006-02-22 22:37:12 +00002281
2282/// isAllocatableRegister - If the specified register is safe to allocate,
2283/// i.e. it isn't a stack pointer or some other special register, return the
2284/// register class for the register. Otherwise, return null.
2285static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002286isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2287 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002288 MVT::ValueType FoundVT = MVT::Other;
2289 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002290 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2291 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002292 MVT::ValueType ThisVT = MVT::Other;
2293
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002294 const TargetRegisterClass *RC = *RCI;
2295 // If none of the the value types for this register class are valid, we
2296 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002297 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2298 I != E; ++I) {
2299 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002300 // If we have already found this register in a different register class,
2301 // choose the one with the largest VT specified. For example, on
2302 // PowerPC, we favor f64 register classes over f32.
2303 if (FoundVT == MVT::Other ||
2304 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2305 ThisVT = *I;
2306 break;
2307 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002308 }
2309 }
2310
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002311 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002312
Chris Lattner864635a2006-02-22 22:37:12 +00002313 // NOTE: This isn't ideal. In particular, this might allocate the
2314 // frame pointer in functions that need it (due to them not being taken
2315 // out of allocation, because a variable sized allocation hasn't been seen
2316 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002317 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2318 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002319 if (*I == Reg) {
2320 // We found a matching register class. Keep looking at others in case
2321 // we find one with larger registers that this physreg is also in.
2322 FoundRC = RC;
2323 FoundVT = ThisVT;
2324 break;
2325 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002326 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002327 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002328}
2329
2330RegsForValue SelectionDAGLowering::
2331GetRegistersForValue(const std::string &ConstrCode,
2332 MVT::ValueType VT, bool isOutReg, bool isInReg,
2333 std::set<unsigned> &OutputRegs,
2334 std::set<unsigned> &InputRegs) {
2335 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2336 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2337 std::vector<unsigned> Regs;
2338
2339 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2340 MVT::ValueType RegVT;
2341 MVT::ValueType ValueVT = VT;
2342
Chris Lattner2a821602006-11-02 01:41:49 +00002343 // If this is a constraint for a specific physical register, like {r17},
2344 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002345 if (PhysReg.first) {
2346 if (VT == MVT::Other)
2347 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002348
2349 // Get the actual register value type. This is important, because the user
2350 // may have asked for (e.g.) the AX register in i32 type. We need to
2351 // remember that AX is actually i16 to get the right extension.
2352 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002353
2354 // This is a explicit reference to a physical register.
2355 Regs.push_back(PhysReg.first);
2356
2357 // If this is an expanded reference, add the rest of the regs to Regs.
2358 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002359 TargetRegisterClass::iterator I = PhysReg.second->begin();
2360 TargetRegisterClass::iterator E = PhysReg.second->end();
2361 for (; *I != PhysReg.first; ++I)
2362 assert(I != E && "Didn't find reg!");
2363
2364 // Already added the first reg.
2365 --NumRegs; ++I;
2366 for (; NumRegs; --NumRegs, ++I) {
2367 assert(I != E && "Ran out of registers to allocate!");
2368 Regs.push_back(*I);
2369 }
2370 }
2371 return RegsForValue(Regs, RegVT, ValueVT);
2372 }
2373
Chris Lattner2a821602006-11-02 01:41:49 +00002374 // Otherwise, if this was a reference to an LLVM register class, create vregs
2375 // for this reference.
2376 std::vector<unsigned> RegClassRegs;
2377 if (PhysReg.second) {
2378 // If this is an early clobber or tied register, our regalloc doesn't know
2379 // how to maintain the constraint. If it isn't, go ahead and create vreg
2380 // and let the regalloc do the right thing.
2381 if (!isOutReg || !isInReg) {
2382 if (VT == MVT::Other)
2383 ValueVT = *PhysReg.second->vt_begin();
2384 RegVT = *PhysReg.second->vt_begin();
2385
2386 // Create the appropriate number of virtual registers.
2387 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2388 for (; NumRegs; --NumRegs)
2389 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2390
2391 return RegsForValue(Regs, RegVT, ValueVT);
2392 }
2393
2394 // Otherwise, we can't allocate it. Let the code below figure out how to
2395 // maintain these constraints.
2396 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2397
2398 } else {
2399 // This is a reference to a register class that doesn't directly correspond
2400 // to an LLVM register class. Allocate NumRegs consecutive, available,
2401 // registers from the class.
2402 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2403 }
Chris Lattner864635a2006-02-22 22:37:12 +00002404
2405 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2406 MachineFunction &MF = *CurMBB->getParent();
2407 unsigned NumAllocated = 0;
2408 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2409 unsigned Reg = RegClassRegs[i];
2410 // See if this register is available.
2411 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2412 (isInReg && InputRegs.count(Reg))) { // Already used.
2413 // Make sure we find consecutive registers.
2414 NumAllocated = 0;
2415 continue;
2416 }
2417
2418 // Check to see if this register is allocatable (i.e. don't give out the
2419 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002420 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002421 if (!RC) {
2422 // Make sure we find consecutive registers.
2423 NumAllocated = 0;
2424 continue;
2425 }
2426
2427 // Okay, this register is good, we can use it.
2428 ++NumAllocated;
2429
2430 // If we allocated enough consecutive
2431 if (NumAllocated == NumRegs) {
2432 unsigned RegStart = (i-NumAllocated)+1;
2433 unsigned RegEnd = i+1;
2434 // Mark all of the allocated registers used.
2435 for (unsigned i = RegStart; i != RegEnd; ++i) {
2436 unsigned Reg = RegClassRegs[i];
2437 Regs.push_back(Reg);
2438 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2439 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2440 }
2441
2442 return RegsForValue(Regs, *RC->vt_begin(), VT);
2443 }
2444 }
2445
2446 // Otherwise, we couldn't allocate enough registers for this.
2447 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002448}
2449
Chris Lattner864635a2006-02-22 22:37:12 +00002450
Chris Lattnerce7518c2006-01-26 22:24:51 +00002451/// visitInlineAsm - Handle a call to an InlineAsm object.
2452///
2453void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2454 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2455
2456 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2457 MVT::Other);
2458
Chris Lattner2cc2f662006-02-01 01:28:23 +00002459 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002460 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002461
2462 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2463 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2464 /// if it is a def of that register.
2465 std::vector<SDOperand> AsmNodeOperands;
2466 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2467 AsmNodeOperands.push_back(AsmStr);
2468
2469 SDOperand Chain = getRoot();
2470 SDOperand Flag;
2471
Chris Lattner4e4b5762006-02-01 18:59:47 +00002472 // We fully assign registers here at isel time. This is not optimal, but
2473 // should work. For register classes that correspond to LLVM classes, we
2474 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2475 // over the constraints, collecting fixed registers that we know we can't use.
2476 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002477 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002478 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2479 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2480 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002481
Chris Lattner1efa40f2006-02-22 00:56:39 +00002482 MVT::ValueType OpVT;
2483
2484 // Compute the value type for each operand and add it to ConstraintVTs.
2485 switch (Constraints[i].Type) {
2486 case InlineAsm::isOutput:
2487 if (!Constraints[i].isIndirectOutput) {
2488 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2489 OpVT = TLI.getValueType(I.getType());
2490 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002491 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002492 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2493 OpNum++; // Consumes a call operand.
2494 }
2495 break;
2496 case InlineAsm::isInput:
2497 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2498 OpNum++; // Consumes a call operand.
2499 break;
2500 case InlineAsm::isClobber:
2501 OpVT = MVT::Other;
2502 break;
2503 }
2504
2505 ConstraintVTs.push_back(OpVT);
2506
Chris Lattner864635a2006-02-22 22:37:12 +00002507 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2508 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002509
Chris Lattner864635a2006-02-22 22:37:12 +00002510 // Build a list of regs that this operand uses. This always has a single
2511 // element for promoted/expanded operands.
2512 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2513 false, false,
2514 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002515
2516 switch (Constraints[i].Type) {
2517 case InlineAsm::isOutput:
2518 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002519 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002520 // If this is an early-clobber output, it cannot be assigned to the same
2521 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002522 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002523 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002524 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002525 case InlineAsm::isInput:
2526 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002527 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002528 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002529 case InlineAsm::isClobber:
2530 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002531 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2532 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002533 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002534 }
2535 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002536
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002537 // Loop over all of the inputs, copying the operand values into the
2538 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002539 RegsForValue RetValRegs;
2540 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002541 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002542
Chris Lattner6656dd12006-01-31 02:03:41 +00002543 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002544 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2545 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002546
Chris Lattner2cc2f662006-02-01 01:28:23 +00002547 switch (Constraints[i].Type) {
2548 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002549 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2550 if (ConstraintCode.size() == 1) // not a physreg name.
2551 CTy = TLI.getConstraintType(ConstraintCode[0]);
2552
2553 if (CTy == TargetLowering::C_Memory) {
2554 // Memory output.
2555 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2556
2557 // Check that the operand (the address to store to) isn't a float.
2558 if (!MVT::isInteger(InOperandVal.getValueType()))
2559 assert(0 && "MATCH FAIL!");
2560
2561 if (!Constraints[i].isIndirectOutput)
2562 assert(0 && "MATCH FAIL!");
2563
2564 OpNum++; // Consumes a call operand.
2565
2566 // Extend/truncate to the right pointer type if needed.
2567 MVT::ValueType PtrType = TLI.getPointerTy();
2568 if (InOperandVal.getValueType() < PtrType)
2569 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2570 else if (InOperandVal.getValueType() > PtrType)
2571 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2572
2573 // Add information to the INLINEASM node to know about this output.
2574 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2575 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2576 AsmNodeOperands.push_back(InOperandVal);
2577 break;
2578 }
2579
2580 // Otherwise, this is a register output.
2581 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2582
Chris Lattner864635a2006-02-22 22:37:12 +00002583 // If this is an early-clobber output, or if there is an input
2584 // constraint that matches this, we need to reserve the input register
2585 // so no other inputs allocate to it.
2586 bool UsesInputRegister = false;
2587 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2588 UsesInputRegister = true;
2589
2590 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002591 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002592 RegsForValue Regs =
2593 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2594 true, UsesInputRegister,
2595 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002596 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002597 cerr << "Couldn't allocate output reg for contraint '"
2598 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002599 exit(1);
2600 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002601
Chris Lattner2cc2f662006-02-01 01:28:23 +00002602 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002603 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002604 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002605 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002606 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002607 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002608 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2609 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002610 OpNum++; // Consumes a call operand.
2611 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002612
2613 // Add information to the INLINEASM node to know that this register is
2614 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002615 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002616 break;
2617 }
2618 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002619 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002620 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002621
Chris Lattner2223aea2006-02-02 00:25:23 +00002622 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2623 // If this is required to match an output register we have already set,
2624 // just use its register.
2625 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002626
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002627 // Scan until we find the definition we already emitted of this operand.
2628 // When we find it, create a RegsForValue operand.
2629 unsigned CurOp = 2; // The first operand.
2630 for (; OperandNo; --OperandNo) {
2631 // Advance to the next operand.
2632 unsigned NumOps =
2633 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002634 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2635 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002636 "Skipped past definitions?");
2637 CurOp += (NumOps>>3)+1;
2638 }
2639
2640 unsigned NumOps =
2641 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2642 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2643 "Skipped past definitions?");
2644
2645 // Add NumOps>>3 registers to MatchedRegs.
2646 RegsForValue MatchedRegs;
2647 MatchedRegs.ValueVT = InOperandVal.getValueType();
2648 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2649 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2650 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2651 MatchedRegs.Regs.push_back(Reg);
2652 }
2653
2654 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002655 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2656 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002657 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002658 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002659 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002660
2661 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2662 if (ConstraintCode.size() == 1) // not a physreg name.
2663 CTy = TLI.getConstraintType(ConstraintCode[0]);
2664
2665 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002666 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2667 ConstraintCode[0], DAG);
2668 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002669 cerr << "Invalid operand for inline asm constraint '"
2670 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002671 exit(1);
2672 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002673
2674 // Add information to the INLINEASM node to know about this input.
2675 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2676 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2677 AsmNodeOperands.push_back(InOperandVal);
2678 break;
2679 } else if (CTy == TargetLowering::C_Memory) {
2680 // Memory input.
2681
2682 // Check that the operand isn't a float.
2683 if (!MVT::isInteger(InOperandVal.getValueType()))
2684 assert(0 && "MATCH FAIL!");
2685
2686 // Extend/truncate to the right pointer type if needed.
2687 MVT::ValueType PtrType = TLI.getPointerTy();
2688 if (InOperandVal.getValueType() < PtrType)
2689 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2690 else if (InOperandVal.getValueType() > PtrType)
2691 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2692
2693 // Add information to the INLINEASM node to know about this input.
2694 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2695 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2696 AsmNodeOperands.push_back(InOperandVal);
2697 break;
2698 }
2699
2700 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2701
2702 // Copy the input into the appropriate registers.
2703 RegsForValue InRegs =
2704 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2705 false, true, OutputRegs, InputRegs);
2706 // FIXME: should be match fail.
2707 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2708
Evan Chenga8441262006-06-15 08:11:54 +00002709 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002710
2711 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002712 break;
2713 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002714 case InlineAsm::isClobber: {
2715 RegsForValue ClobberedRegs =
2716 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2717 OutputRegs, InputRegs);
2718 // Add the clobbered value to the operand list, so that the register
2719 // allocator is aware that the physreg got clobbered.
2720 if (!ClobberedRegs.Regs.empty())
2721 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002722 break;
2723 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002724 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002725 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002726
2727 // Finish up input operands.
2728 AsmNodeOperands[0] = Chain;
2729 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2730
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002731 Chain = DAG.getNode(ISD::INLINEASM,
2732 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002733 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002734 Flag = Chain.getValue(1);
2735
Chris Lattner6656dd12006-01-31 02:03:41 +00002736 // If this asm returns a register value, copy the result from that register
2737 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002738 if (!RetValRegs.Regs.empty())
2739 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002740
Chris Lattner6656dd12006-01-31 02:03:41 +00002741 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2742
2743 // Process indirect outputs, first output all of the flagged copies out of
2744 // physregs.
2745 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002746 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002747 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002748 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2749 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002750 }
2751
2752 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002753 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002754 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002755 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002756 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002757 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002758 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002759 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2760 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002761 DAG.setRoot(Chain);
2762}
2763
2764
Chris Lattner1c08c712005-01-07 07:47:53 +00002765void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2766 SDOperand Src = getValue(I.getOperand(0));
2767
2768 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002769
2770 if (IntPtr < Src.getValueType())
2771 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2772 else if (IntPtr > Src.getValueType())
2773 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002774
2775 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002776 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002777 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2778 Src, getIntPtrConstant(ElementSize));
2779
Reid Spencer47857812006-12-31 05:55:36 +00002780 TargetLowering::ArgListTy Args;
2781 TargetLowering::ArgListEntry Entry;
2782 Entry.Node = Src;
2783 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2784 Entry.isSigned = false;
2785 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002786
2787 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002788 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002789 DAG.getExternalSymbol("malloc", IntPtr),
2790 Args, DAG);
2791 setValue(&I, Result.first); // Pointers always fit in registers
2792 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002793}
2794
2795void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002796 TargetLowering::ArgListTy Args;
2797 TargetLowering::ArgListEntry Entry;
2798 Entry.Node = getValue(I.getOperand(0));
2799 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2800 Entry.isSigned = false;
2801 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002802 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002803 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002804 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002805 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2806 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002807}
2808
Chris Lattner025c39b2005-08-26 20:54:47 +00002809// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2810// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2811// instructions are special in various ways, which require special support to
2812// insert. The specified MachineInstr is created but not inserted into any
2813// basic blocks, and the scheduler passes ownership of it to this method.
2814MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2815 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002816 cerr << "If a target marks an instruction with "
2817 << "'usesCustomDAGSchedInserter', it must implement "
2818 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00002819 abort();
2820 return 0;
2821}
2822
Chris Lattner39ae3622005-01-09 00:00:49 +00002823void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002824 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2825 getValue(I.getOperand(1)),
2826 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002827}
2828
2829void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002830 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2831 getValue(I.getOperand(0)),
2832 DAG.getSrcValue(I.getOperand(0)));
2833 setValue(&I, V);
2834 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002835}
2836
2837void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002838 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2839 getValue(I.getOperand(1)),
2840 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002841}
2842
2843void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002844 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2845 getValue(I.getOperand(1)),
2846 getValue(I.getOperand(2)),
2847 DAG.getSrcValue(I.getOperand(1)),
2848 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002849}
2850
Evan Chengb15974a2006-12-12 07:27:38 +00002851/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2852/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2853static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2854 unsigned &i, SelectionDAG &DAG,
2855 TargetLowering &TLI) {
2856 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2857 return SDOperand(Arg, i++);
2858
2859 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2860 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2861 if (NumVals == 1) {
2862 return DAG.getNode(ISD::BIT_CONVERT, VT,
2863 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2864 } else if (NumVals == 2) {
2865 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2866 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2867 if (!TLI.isLittleEndian())
2868 std::swap(Lo, Hi);
2869 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2870 } else {
2871 // Value scalarized into many values. Unimp for now.
2872 assert(0 && "Cannot expand i64 -> i16 yet!");
2873 }
2874 return SDOperand();
2875}
2876
Chris Lattnerfdfded52006-04-12 16:20:43 +00002877/// TargetLowering::LowerArguments - This is the default LowerArguments
2878/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002879/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2880/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002881std::vector<SDOperand>
2882TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2883 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2884 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002885 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002886 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2887 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2888
2889 // Add one result value for each formal argument.
2890 std::vector<MVT::ValueType> RetVals;
2891 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2892 MVT::ValueType VT = getValueType(I->getType());
2893
2894 switch (getTypeAction(VT)) {
2895 default: assert(0 && "Unknown type action!");
2896 case Legal:
2897 RetVals.push_back(VT);
2898 break;
2899 case Promote:
2900 RetVals.push_back(getTypeToTransformTo(VT));
2901 break;
2902 case Expand:
2903 if (VT != MVT::Vector) {
2904 // If this is a large integer, it needs to be broken up into small
2905 // integers. Figure out what the destination type is and how many small
2906 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00002907 MVT::ValueType NVT = getTypeToExpandTo(VT);
2908 unsigned NumVals = getNumElements(VT);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002909 for (unsigned i = 0; i != NumVals; ++i)
2910 RetVals.push_back(NVT);
2911 } else {
2912 // Otherwise, this is a vector type. We only support legal vectors
2913 // right now.
2914 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2915 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002916
Chris Lattnerfdfded52006-04-12 16:20:43 +00002917 // Figure out if there is a Packed type corresponding to this Vector
2918 // type. If so, convert to the packed type.
2919 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2920 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2921 RetVals.push_back(TVT);
2922 } else {
2923 assert(0 && "Don't support illegal by-val vector arguments yet!");
2924 }
2925 }
2926 break;
2927 }
2928 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002929
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002930 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002931
2932 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002933 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2934 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002935 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002936
2937 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002938
2939 // Set up the return result vector.
2940 Ops.clear();
Reid Spencer47857812006-12-31 05:55:36 +00002941 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002942 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00002943 unsigned Idx = 1;
2944 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2945 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002946 MVT::ValueType VT = getValueType(I->getType());
2947
2948 switch (getTypeAction(VT)) {
2949 default: assert(0 && "Unknown type action!");
2950 case Legal:
2951 Ops.push_back(SDOperand(Result, i++));
2952 break;
2953 case Promote: {
2954 SDOperand Op(Result, i++);
2955 if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00002956 unsigned AssertOp = ISD::AssertSext;
2957 if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
2958 AssertOp = ISD::AssertZext;
Chris Lattnerfdfded52006-04-12 16:20:43 +00002959 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2960 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2961 } else {
2962 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2963 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2964 }
2965 Ops.push_back(Op);
2966 break;
2967 }
2968 case Expand:
2969 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00002970 // If this is a large integer or a floating point node that needs to be
2971 // expanded, it needs to be reassembled from small integers. Figure out
2972 // what the source elt type is and how many small integers it is.
2973 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002974 } else {
2975 // Otherwise, this is a vector type. We only support legal vectors
2976 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002977 const PackedType *PTy = cast<PackedType>(I->getType());
2978 unsigned NumElems = PTy->getNumElements();
2979 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002980
Chris Lattnerfdfded52006-04-12 16:20:43 +00002981 // Figure out if there is a Packed type corresponding to this Vector
2982 // type. If so, convert to the packed type.
2983 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002984 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002985 SDOperand N = SDOperand(Result, i++);
2986 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002987 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2988 DAG.getConstant(NumElems, MVT::i32),
2989 DAG.getValueType(getValueType(EltTy)));
2990 Ops.push_back(N);
2991 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002992 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002993 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002994 }
2995 }
2996 break;
2997 }
2998 }
2999 return Ops;
3000}
3001
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003002
Evan Chengb15974a2006-12-12 07:27:38 +00003003/// ExpandScalarCallArgs - Recursively expand call argument node by
3004/// bit_converting it or extract a pair of elements from the larger node.
3005static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3006 bool isSigned,
3007 SmallVector<SDOperand, 32> &Ops,
3008 SelectionDAG &DAG,
3009 TargetLowering &TLI) {
3010 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3011 Ops.push_back(Arg);
3012 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3013 return;
3014 }
3015
3016 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3017 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3018 if (NumVals == 1) {
3019 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3020 ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
3021 } else if (NumVals == 2) {
3022 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3023 DAG.getConstant(0, TLI.getPointerTy()));
3024 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3025 DAG.getConstant(1, TLI.getPointerTy()));
3026 if (!TLI.isLittleEndian())
3027 std::swap(Lo, Hi);
3028 ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
3029 ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
3030 } else {
3031 // Value scalarized into many values. Unimp for now.
3032 assert(0 && "Cannot expand i64 -> i16 yet!");
3033 }
3034}
3035
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003036/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3037/// implementation, which just inserts an ISD::CALL node, which is later custom
3038/// lowered by the target to something concrete. FIXME: When all targets are
3039/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3040std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003041TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3042 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003043 unsigned CallingConv, bool isTailCall,
3044 SDOperand Callee,
3045 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003046 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003047 Ops.push_back(Chain); // Op#0 - Chain
3048 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3049 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3050 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3051 Ops.push_back(Callee);
3052
3053 // Handle all of the outgoing arguments.
3054 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003055 MVT::ValueType VT = getValueType(Args[i].Ty);
3056 SDOperand Op = Args[i].Node;
3057 bool isSigned = Args[i].isSigned;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003058 switch (getTypeAction(VT)) {
3059 default: assert(0 && "Unknown type action!");
3060 case Legal:
3061 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003062 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003063 break;
3064 case Promote:
3065 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003066 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003067 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3068 } else {
3069 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3070 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3071 }
3072 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003073 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003074 break;
3075 case Expand:
3076 if (VT != MVT::Vector) {
3077 // If this is a large integer, it needs to be broken down into small
3078 // integers. Figure out what the source elt type is and how many small
3079 // integers it is.
Evan Chengb15974a2006-12-12 07:27:38 +00003080 ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003081 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003082 // Otherwise, this is a vector type. We only support legal vectors
3083 // right now.
Reid Spencer47857812006-12-31 05:55:36 +00003084 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003085 unsigned NumElems = PTy->getNumElements();
3086 const Type *EltTy = PTy->getElementType();
3087
3088 // Figure out if there is a Packed type corresponding to this Vector
3089 // type. If so, convert to the packed type.
3090 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003091 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3092 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3093 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3094 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003095 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003096 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003097 assert(0 && "Don't support illegal by-val vector call args yet!");
3098 abort();
3099 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003100 }
3101 break;
3102 }
3103 }
3104
3105 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003106 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003107
3108 if (RetTy != Type::VoidTy) {
3109 MVT::ValueType VT = getValueType(RetTy);
3110 switch (getTypeAction(VT)) {
3111 default: assert(0 && "Unknown type action!");
3112 case Legal:
3113 RetTys.push_back(VT);
3114 break;
3115 case Promote:
3116 RetTys.push_back(getTypeToTransformTo(VT));
3117 break;
3118 case Expand:
3119 if (VT != MVT::Vector) {
3120 // If this is a large integer, it needs to be reassembled from small
3121 // integers. Figure out what the source elt type is and how many small
3122 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003123 MVT::ValueType NVT = getTypeToExpandTo(VT);
3124 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003125 for (unsigned i = 0; i != NumVals; ++i)
3126 RetTys.push_back(NVT);
3127 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003128 // Otherwise, this is a vector type. We only support legal vectors
3129 // right now.
3130 const PackedType *PTy = cast<PackedType>(RetTy);
3131 unsigned NumElems = PTy->getNumElements();
3132 const Type *EltTy = PTy->getElementType();
3133
3134 // Figure out if there is a Packed type corresponding to this Vector
3135 // type. If so, convert to the packed type.
3136 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3137 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3138 RetTys.push_back(TVT);
3139 } else {
3140 assert(0 && "Don't support illegal by-val vector call results yet!");
3141 abort();
3142 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003143 }
3144 }
3145 }
3146
3147 RetTys.push_back(MVT::Other); // Always has a chain.
3148
3149 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003150 SDOperand Res = DAG.getNode(ISD::CALL,
3151 DAG.getVTList(&RetTys[0], RetTys.size()),
3152 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003153
3154 // This returns a pair of operands. The first element is the
3155 // return value for the function (if RetTy is not VoidTy). The second
3156 // element is the outgoing token chain.
3157 SDOperand ResVal;
3158 if (RetTys.size() != 1) {
3159 MVT::ValueType VT = getValueType(RetTy);
3160 if (RetTys.size() == 2) {
3161 ResVal = Res;
3162
3163 // If this value was promoted, truncate it down.
3164 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003165 if (VT == MVT::Vector) {
3166 // Insert a VBITCONVERT to convert from the packed result type to the
3167 // MVT::Vector type.
3168 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3169 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3170
3171 // Figure out if there is a Packed type corresponding to this Vector
3172 // type. If so, convert to the packed type.
3173 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3174 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003175 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3176 // "N x PTyElementVT" MVT::Vector type.
3177 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003178 DAG.getConstant(NumElems, MVT::i32),
3179 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003180 } else {
3181 abort();
3182 }
3183 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003184 unsigned AssertOp = ISD::AssertSext;
3185 if (!RetTyIsSigned)
3186 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003187 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3188 DAG.getValueType(VT));
3189 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3190 } else {
3191 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003192 if (getTypeAction(VT) == Expand)
3193 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3194 else
3195 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003196 }
3197 }
3198 } else if (RetTys.size() == 3) {
3199 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3200 Res.getValue(0), Res.getValue(1));
3201
3202 } else {
3203 assert(0 && "Case not handled yet!");
3204 }
3205 }
3206
3207 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3208}
3209
3210
3211
Chris Lattner39ae3622005-01-09 00:00:49 +00003212// It is always conservatively correct for llvm.returnaddress and
3213// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003214//
3215// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3216// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00003217std::pair<SDOperand, SDOperand>
3218TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3219 unsigned Depth, SelectionDAG &DAG) {
3220 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00003221}
3222
Chris Lattner50381b62005-05-14 05:50:48 +00003223SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003224 assert(0 && "LowerOperation not implemented for this target!");
3225 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003226 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003227}
3228
Nate Begeman0aed7842006-01-28 03:14:31 +00003229SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3230 SelectionDAG &DAG) {
3231 assert(0 && "CustomPromoteOperation not implemented for this target!");
3232 abort();
3233 return SDOperand();
3234}
3235
Chris Lattner39ae3622005-01-09 00:00:49 +00003236void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003237 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003238 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003239 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003240 setValue(&I, Result.first);
3241 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003242}
3243
Evan Cheng74d0aa92006-02-15 21:59:04 +00003244/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003245/// operand.
3246static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003247 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003248 MVT::ValueType CurVT = VT;
3249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3250 uint64_t Val = C->getValue() & 255;
3251 unsigned Shift = 8;
3252 while (CurVT != MVT::i8) {
3253 Val = (Val << Shift) | Val;
3254 Shift <<= 1;
3255 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003256 }
3257 return DAG.getConstant(Val, VT);
3258 } else {
3259 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3260 unsigned Shift = 8;
3261 while (CurVT != MVT::i8) {
3262 Value =
3263 DAG.getNode(ISD::OR, VT,
3264 DAG.getNode(ISD::SHL, VT, Value,
3265 DAG.getConstant(Shift, MVT::i8)), Value);
3266 Shift <<= 1;
3267 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003268 }
3269
3270 return Value;
3271 }
3272}
3273
Evan Cheng74d0aa92006-02-15 21:59:04 +00003274/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3275/// used when a memcpy is turned into a memset when the source is a constant
3276/// string ptr.
3277static SDOperand getMemsetStringVal(MVT::ValueType VT,
3278 SelectionDAG &DAG, TargetLowering &TLI,
3279 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003280 uint64_t Val = 0;
3281 unsigned MSB = getSizeInBits(VT) / 8;
3282 if (TLI.isLittleEndian())
3283 Offset = Offset + MSB - 1;
3284 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003285 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003286 Offset += TLI.isLittleEndian() ? -1 : 1;
3287 }
3288 return DAG.getConstant(Val, VT);
3289}
3290
Evan Cheng1db92f92006-02-14 08:22:34 +00003291/// getMemBasePlusOffset - Returns base and offset node for the
3292static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3293 SelectionDAG &DAG, TargetLowering &TLI) {
3294 MVT::ValueType VT = Base.getValueType();
3295 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3296}
3297
Evan Chengc4f8eee2006-02-14 20:12:38 +00003298/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003299/// to replace the memset / memcpy is below the threshold. It also returns the
3300/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003301static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3302 unsigned Limit, uint64_t Size,
3303 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003304 MVT::ValueType VT;
3305
3306 if (TLI.allowsUnalignedMemoryAccesses()) {
3307 VT = MVT::i64;
3308 } else {
3309 switch (Align & 7) {
3310 case 0:
3311 VT = MVT::i64;
3312 break;
3313 case 4:
3314 VT = MVT::i32;
3315 break;
3316 case 2:
3317 VT = MVT::i16;
3318 break;
3319 default:
3320 VT = MVT::i8;
3321 break;
3322 }
3323 }
3324
Evan Cheng80e89d72006-02-14 09:11:59 +00003325 MVT::ValueType LVT = MVT::i64;
3326 while (!TLI.isTypeLegal(LVT))
3327 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3328 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003329
Evan Cheng80e89d72006-02-14 09:11:59 +00003330 if (VT > LVT)
3331 VT = LVT;
3332
Evan Chengdea72452006-02-14 23:05:54 +00003333 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003334 while (Size != 0) {
3335 unsigned VTSize = getSizeInBits(VT) / 8;
3336 while (VTSize > Size) {
3337 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003338 VTSize >>= 1;
3339 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003340 assert(MVT::isInteger(VT));
3341
3342 if (++NumMemOps > Limit)
3343 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003344 MemOps.push_back(VT);
3345 Size -= VTSize;
3346 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003347
3348 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003349}
3350
Chris Lattner7041ee32005-01-11 05:56:49 +00003351void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003352 SDOperand Op1 = getValue(I.getOperand(1));
3353 SDOperand Op2 = getValue(I.getOperand(2));
3354 SDOperand Op3 = getValue(I.getOperand(3));
3355 SDOperand Op4 = getValue(I.getOperand(4));
3356 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3357 if (Align == 0) Align = 1;
3358
3359 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3360 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003361
3362 // Expand memset / memcpy to a series of load / store ops
3363 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003364 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003365 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003366 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003367 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003368 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3369 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003370 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003371 unsigned Offset = 0;
3372 for (unsigned i = 0; i < NumMemOps; i++) {
3373 MVT::ValueType VT = MemOps[i];
3374 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003375 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003376 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003377 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003378 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003379 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003380 Offset += VTSize;
3381 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003382 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003383 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003384 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003385 case ISD::MEMCPY: {
3386 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3387 Size->getValue(), Align, TLI)) {
3388 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003389 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003390 GlobalAddressSDNode *G = NULL;
3391 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003392 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003393
3394 if (Op2.getOpcode() == ISD::GlobalAddress)
3395 G = cast<GlobalAddressSDNode>(Op2);
3396 else if (Op2.getOpcode() == ISD::ADD &&
3397 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3398 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3399 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003400 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003401 }
3402 if (G) {
3403 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003404 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003405 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003406 if (!Str.empty()) {
3407 CopyFromStr = true;
3408 SrcOff += SrcDelta;
3409 }
3410 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003411 }
3412
Evan Chengc080d6f2006-02-15 01:54:51 +00003413 for (unsigned i = 0; i < NumMemOps; i++) {
3414 MVT::ValueType VT = MemOps[i];
3415 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003416 SDOperand Value, Chain, Store;
3417
Evan Chengcffbb512006-02-16 23:11:42 +00003418 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003419 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3420 Chain = getRoot();
3421 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003422 DAG.getStore(Chain, Value,
3423 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003424 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003425 } else {
3426 Value = DAG.getLoad(VT, getRoot(),
3427 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003428 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003429 Chain = Value.getValue(1);
3430 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003431 DAG.getStore(Chain, Value,
3432 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003433 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003434 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003435 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003436 SrcOff += VTSize;
3437 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003438 }
3439 }
3440 break;
3441 }
3442 }
3443
3444 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003445 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3446 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003447 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003448 }
3449 }
3450
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003451 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003452}
3453
Chris Lattner7041ee32005-01-11 05:56:49 +00003454//===----------------------------------------------------------------------===//
3455// SelectionDAGISel code
3456//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003457
3458unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3459 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3460}
3461
Chris Lattner495a0b52005-08-17 06:37:43 +00003462void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003463 // FIXME: we only modify the CFG to split critical edges. This
3464 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003465 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003466}
Chris Lattner1c08c712005-01-07 07:47:53 +00003467
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003468
Chris Lattner90323642006-05-05 21:17:49 +00003469/// OptimizeNoopCopyExpression - We have determined that the specified cast
3470/// instruction is a noop copy (e.g. it's casting from one pointer type to
3471/// another, int->uint, or int->sbyte on PPC.
3472///
3473/// Return true if any changes are made.
3474static bool OptimizeNoopCopyExpression(CastInst *CI) {
3475 BasicBlock *DefBB = CI->getParent();
3476
3477 /// InsertedCasts - Only insert a cast in each block once.
3478 std::map<BasicBlock*, CastInst*> InsertedCasts;
3479
3480 bool MadeChange = false;
3481 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3482 UI != E; ) {
3483 Use &TheUse = UI.getUse();
3484 Instruction *User = cast<Instruction>(*UI);
3485
3486 // Figure out which BB this cast is used in. For PHI's this is the
3487 // appropriate predecessor block.
3488 BasicBlock *UserBB = User->getParent();
3489 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3490 unsigned OpVal = UI.getOperandNo()/2;
3491 UserBB = PN->getIncomingBlock(OpVal);
3492 }
3493
3494 // Preincrement use iterator so we don't invalidate it.
3495 ++UI;
3496
3497 // If this user is in the same block as the cast, don't change the cast.
3498 if (UserBB == DefBB) continue;
3499
3500 // If we have already inserted a cast into this block, use it.
3501 CastInst *&InsertedCast = InsertedCasts[UserBB];
3502
3503 if (!InsertedCast) {
3504 BasicBlock::iterator InsertPt = UserBB->begin();
3505 while (isa<PHINode>(InsertPt)) ++InsertPt;
3506
3507 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003508 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3509 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003510 MadeChange = true;
3511 }
3512
3513 // Replace a use of the cast with a use of the new casat.
3514 TheUse = InsertedCast;
3515 }
3516
3517 // If we removed all uses, nuke the cast.
3518 if (CI->use_empty())
3519 CI->eraseFromParent();
3520
3521 return MadeChange;
3522}
3523
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003524/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3525/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003526static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3527 Instruction *GEPI, Value *Ptr,
3528 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003529 if (V) return V; // Already computed.
3530
Reid Spencer3da59db2006-11-27 01:05:10 +00003531 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003532 BasicBlock::iterator InsertPt;
3533 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003534 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003535 InsertPt = GEPI;
3536 ++InsertPt;
3537 } else {
3538 // Otherwise, insert at the top of BB, after any PHI nodes
3539 InsertPt = BB->begin();
3540 while (isa<PHINode>(InsertPt)) ++InsertPt;
3541 }
3542
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003543 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3544 // BB so that there is only one value live across basic blocks (the cast
3545 // operand).
3546 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3547 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003548 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3549 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003550
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003551 // Add the offset, cast it to the right type.
3552 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003553 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3554 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3555 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003556}
3557
Chris Lattner90323642006-05-05 21:17:49 +00003558/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3559/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3560/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3561/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3562/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3563/// the constant add into a load or store instruction. Additionally, if a user
3564/// is a pointer-pointer cast, we look through it to find its users.
3565static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3566 Constant *PtrOffset, BasicBlock *DefBB,
3567 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003568 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003569 while (!RepPtr->use_empty()) {
3570 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003571
Reid Spencer3da59db2006-11-27 01:05:10 +00003572 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3573 // used for a Pointer-Pointer cast.
3574 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003575 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003576
Chris Lattner90323642006-05-05 21:17:49 +00003577 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3578 // could invalidate an iterator.
3579 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3580 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003581 }
3582
Chris Lattner90323642006-05-05 21:17:49 +00003583 // If this is a load of the pointer, or a store through the pointer, emit
3584 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003585 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003586 if (isa<LoadInst>(User) ||
3587 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3588 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3589 User->getParent(), GEPI,
3590 Ptr, PtrOffset);
3591 } else {
3592 // If this use is not foldable into the addressing mode, use a version
3593 // emitted in the GEP block.
3594 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3595 Ptr, PtrOffset);
3596 }
3597
Chris Lattnerf0df8822006-05-06 09:10:37 +00003598 if (GEPI->getType() != RepPtr->getType()) {
3599 BasicBlock::iterator IP = NewVal;
3600 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003601 // NewVal must be a GEP which must be pointer type, so BitCast
3602 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003603 }
Chris Lattner90323642006-05-05 21:17:49 +00003604 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003605 }
3606}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003607
Chris Lattner90323642006-05-05 21:17:49 +00003608
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003609/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3610/// selection, we want to be a bit careful about some things. In particular, if
3611/// we have a GEP instruction that is used in a different block than it is
3612/// defined, the addressing expression of the GEP cannot be folded into loads or
3613/// stores that use it. In this case, decompose the GEP and move constant
3614/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003615static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003616 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003617 // If this GEP is only used inside the block it is defined in, there is no
3618 // need to rewrite it.
3619 bool isUsedOutsideDefBB = false;
3620 BasicBlock *DefBB = GEPI->getParent();
3621 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3622 UI != E; ++UI) {
3623 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3624 isUsedOutsideDefBB = true;
3625 break;
3626 }
3627 }
Chris Lattner90323642006-05-05 21:17:49 +00003628 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003629
3630 // If this GEP has no non-zero constant indices, there is nothing we can do,
3631 // ignore it.
3632 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003633 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003634 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3635 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003636 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003637 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003638 hasConstantIndex = true;
3639 break;
3640 }
Chris Lattner90323642006-05-05 21:17:49 +00003641 } else {
3642 hasVariableIndex = true;
3643 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003644 }
Chris Lattner90323642006-05-05 21:17:49 +00003645
3646 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3647 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003648 /// The GEP operand must be a pointer, so must its result -> BitCast
3649 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003650 GEPI->getName(), GEPI);
3651 GEPI->replaceAllUsesWith(NC);
3652 GEPI->eraseFromParent();
3653 return true;
3654 }
3655
Chris Lattner3802c252005-12-11 09:05:13 +00003656 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003657 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3658 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003659
3660 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3661 // constant offset (which we now know is non-zero) and deal with it later.
3662 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003663 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003664 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003665 const Type *Ty = GEPI->getOperand(0)->getType();
3666
3667 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3668 E = GEPI->op_end(); OI != E; ++OI) {
3669 Value *Idx = *OI;
3670 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003671 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003672 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003673 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003674 Ty = StTy->getElementType(Field);
3675 } else {
3676 Ty = cast<SequentialType>(Ty)->getElementType();
3677
3678 // Handle constant subscripts.
3679 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003680 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003681 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003682 continue;
3683 }
3684
3685 // Ptr = Ptr + Idx * ElementSize;
3686
3687 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003688 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003689
Owen Andersona69571c2006-05-03 01:29:57 +00003690 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003691 // Mask off bits that should not be set.
3692 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003693 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003694
3695 // Multiply by the element size and add to the base.
3696 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3697 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3698 }
3699 }
3700
3701 // Make sure that the offset fits in uintptr_t.
3702 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003703 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003704
3705 // Okay, we have now emitted all of the variable index parts to the BB that
3706 // the GEP is defined in. Loop over all of the using instructions, inserting
3707 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003708 // instruction to use the newly computed value, making GEPI dead. When the
3709 // user is a load or store instruction address, we emit the add into the user
3710 // block, otherwise we use a canonical version right next to the gep (these
3711 // won't be foldable as addresses, so we might as well share the computation).
3712
Chris Lattnerf0df8822006-05-06 09:10:37 +00003713 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003714 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003715
3716 // Finally, the GEP is dead, remove it.
3717 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003718
3719 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003720}
3721
Chris Lattnerbad7f482006-10-28 19:22:10 +00003722
3723/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3724/// successor if it will improve codegen. We only do this if the successor has
3725/// phi nodes (otherwise critical edges are ok). If there is already another
3726/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3727/// instead of introducing a new block.
3728static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3729 BasicBlock *TIBB = TI->getParent();
3730 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3731 assert(isa<PHINode>(Dest->begin()) &&
3732 "This should only be called if Dest has a PHI!");
3733
3734 /// TIPHIValues - This array is lazily computed to determine the values of
3735 /// PHIs in Dest that TI would provide.
3736 std::vector<Value*> TIPHIValues;
3737
3738 // Check to see if Dest has any blocks that can be used as a split edge for
3739 // this terminator.
3740 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3741 BasicBlock *Pred = *PI;
3742 // To be usable, the pred has to end with an uncond branch to the dest.
3743 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3744 if (!PredBr || !PredBr->isUnconditional() ||
3745 // Must be empty other than the branch.
3746 &Pred->front() != PredBr)
3747 continue;
3748
3749 // Finally, since we know that Dest has phi nodes in it, we have to make
3750 // sure that jumping to Pred will have the same affect as going to Dest in
3751 // terms of PHI values.
3752 PHINode *PN;
3753 unsigned PHINo = 0;
3754 bool FoundMatch = true;
3755 for (BasicBlock::iterator I = Dest->begin();
3756 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3757 if (PHINo == TIPHIValues.size())
3758 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3759
3760 // If the PHI entry doesn't work, we can't use this pred.
3761 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3762 FoundMatch = false;
3763 break;
3764 }
3765 }
3766
3767 // If we found a workable predecessor, change TI to branch to Succ.
3768 if (FoundMatch) {
3769 Dest->removePredecessor(TIBB);
3770 TI->setSuccessor(SuccNum, Pred);
3771 return;
3772 }
3773 }
3774
3775 SplitCriticalEdge(TI, SuccNum, P, true);
3776}
3777
3778
Chris Lattner1c08c712005-01-07 07:47:53 +00003779bool SelectionDAGISel::runOnFunction(Function &Fn) {
3780 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3781 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003782 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003783
Chris Lattner47e32e62006-10-28 17:04:37 +00003784 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003785 //
Chris Lattner7e598092006-05-05 01:04:50 +00003786 // In this pass we also look for GEP and cast instructions that are used
3787 // across basic blocks and rewrite them to improve basic-block-at-a-time
3788 // selection.
3789 //
Chris Lattner90323642006-05-05 21:17:49 +00003790 bool MadeChange = true;
3791 while (MadeChange) {
3792 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003793 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003794 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003795 TerminatorInst *BBTI = BB->getTerminator();
3796 if (BBTI->getNumSuccessors() > 1) {
3797 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003798 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3799 isCriticalEdge(BBTI, i, true))
3800 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003801 }
3802
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003803
Chris Lattner57f9a432006-09-28 06:17:10 +00003804 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003805 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003806
3807 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3808 // If we found an inline asm expession, and if the target knows how to
3809 // lower it to normal LLVM code, do so now.
3810 if (isa<InlineAsm>(CI->getCalledValue()))
3811 if (const TargetAsmInfo *TAI =
3812 TLI.getTargetMachine().getTargetAsmInfo()) {
3813 if (TAI->ExpandInlineAsm(CI))
3814 BBI = BB->begin();
3815 }
3816 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003817 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003818 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003819 // If the source of the cast is a constant, then this should have
3820 // already been constant folded. The only reason NOT to constant fold
3821 // it is if something (e.g. LSR) was careful to place the constant
3822 // evaluation in a block other than then one that uses it (e.g. to hoist
3823 // the address of globals out of a loop). If this is the case, we don't
3824 // want to forward-subst the cast.
3825 if (isa<Constant>(CI->getOperand(0)))
3826 continue;
3827
Chris Lattner7e598092006-05-05 01:04:50 +00003828 // If this is a noop copy, sink it into user blocks to reduce the number
3829 // of virtual registers that must be created and coallesced.
3830 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3831 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3832
3833 // This is an fp<->int conversion?
3834 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3835 continue;
3836
3837 // If this is an extension, it will be a zero or sign extension, which
3838 // isn't a noop.
3839 if (SrcVT < DstVT) continue;
3840
3841 // If these values will be promoted, find out what they will be promoted
3842 // to. This helps us consider truncates on PPC as noop copies when they
3843 // are.
3844 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3845 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3846 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3847 DstVT = TLI.getTypeToTransformTo(DstVT);
3848
3849 // If, after promotion, these are the same types, this is a noop copy.
3850 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003851 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003852 }
3853 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003854 }
Chris Lattner90323642006-05-05 21:17:49 +00003855 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003856
Chris Lattner1c08c712005-01-07 07:47:53 +00003857 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3858
3859 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3860 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003861
Chris Lattner1c08c712005-01-07 07:47:53 +00003862 return true;
3863}
3864
Chris Lattner571e4342006-10-27 21:36:01 +00003865SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3866 unsigned Reg) {
3867 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003868 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003869 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003870 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003871
3872 // If this type is not legal, we must make sure to not create an invalid
3873 // register use.
3874 MVT::ValueType SrcVT = Op.getValueType();
3875 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003876 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003877 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003878 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003879 // Handle copies from generic vectors to registers.
3880 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3881 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3882 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003883
Chris Lattner70c2a612006-03-31 02:06:56 +00003884 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3885 // MVT::Vector type.
3886 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3887 DAG.getConstant(NE, MVT::i32),
3888 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003889
Chris Lattner70c2a612006-03-31 02:06:56 +00003890 // Loop over all of the elements of the resultant vector,
3891 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3892 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003893 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003894 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003895 for (unsigned i = 0; i != NE; ++i) {
3896 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003897 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003898 if (PTyElementVT == PTyLegalElementVT) {
3899 // Elements are legal.
3900 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3901 } else if (PTyLegalElementVT > PTyElementVT) {
3902 // Elements are promoted.
3903 if (MVT::isFloatingPoint(PTyLegalElementVT))
3904 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3905 else
3906 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3907 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3908 } else {
3909 // Elements are expanded.
3910 // The src value is expanded into multiple registers.
3911 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003912 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003913 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003914 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003915 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3916 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3917 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003918 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003919 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3920 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00003921 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003922 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003923 if (MVT::isFloatingPoint(SrcVT))
3924 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3925 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003926 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003927 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003928 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00003929 DestVT = TLI.getTypeToExpandTo(SrcVT);
3930 unsigned NumVals = TLI.getNumElements(SrcVT);
3931 if (NumVals == 1)
3932 return DAG.getCopyToReg(getRoot(), Reg,
3933 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3934 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003935 // The src value is expanded into multiple registers.
3936 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003937 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003938 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003939 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003940 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003941 return DAG.getCopyToReg(Op, Reg+1, Hi);
3942 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003943}
3944
Chris Lattner068a81e2005-01-17 17:15:02 +00003945void SelectionDAGISel::
3946LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3947 std::vector<SDOperand> &UnorderedChains) {
3948 // If this is the entry block, emit arguments.
3949 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003950 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003951 SDOperand OldRoot = SDL.DAG.getRoot();
3952 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003953
Chris Lattnerbf209482005-10-30 19:42:35 +00003954 unsigned a = 0;
3955 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3956 AI != E; ++AI, ++a)
3957 if (!AI->use_empty()) {
3958 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003959
Chris Lattnerbf209482005-10-30 19:42:35 +00003960 // If this argument is live outside of the entry block, insert a copy from
3961 // whereever we got it to the vreg that other BB's will reference it as.
3962 if (FuncInfo.ValueMap.count(AI)) {
3963 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003964 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003965 UnorderedChains.push_back(Copy);
3966 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003967 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003968
Chris Lattnerbf209482005-10-30 19:42:35 +00003969 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003970 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003971 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003972}
3973
Chris Lattner1c08c712005-01-07 07:47:53 +00003974void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3975 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003976 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003977 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003978
3979 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003980
Chris Lattnerbf209482005-10-30 19:42:35 +00003981 // Lower any arguments needed in this block if this is the entry block.
3982 if (LLVMBB == &LLVMBB->getParent()->front())
3983 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003984
3985 BB = FuncInfo.MBBMap[LLVMBB];
3986 SDL.setCurrentBasicBlock(BB);
3987
3988 // Lower all of the non-terminator instructions.
3989 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3990 I != E; ++I)
3991 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003992
Chris Lattner1c08c712005-01-07 07:47:53 +00003993 // Ensure that all instructions which are used outside of their defining
3994 // blocks are available as virtual registers.
3995 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003996 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003997 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003998 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003999 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004000 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004001 }
4002
4003 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4004 // ensure constants are generated when needed. Remember the virtual registers
4005 // that need to be added to the Machine PHI nodes as input. We cannot just
4006 // directly add them, because expansion might result in multiple MBB's for one
4007 // BB. As such, the start of the BB might correspond to a different MBB than
4008 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004009 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004010 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004011
4012 // Emit constants only once even if used by multiple PHI nodes.
4013 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004014
Chris Lattner8c494ab2006-10-27 23:50:33 +00004015 // Vector bool would be better, but vector<bool> is really slow.
4016 std::vector<unsigned char> SuccsHandled;
4017 if (TI->getNumSuccessors())
4018 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4019
Chris Lattner1c08c712005-01-07 07:47:53 +00004020 // Check successor nodes PHI nodes that expect a constant to be available from
4021 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004022 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4023 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004024 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004025 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004026
Chris Lattner8c494ab2006-10-27 23:50:33 +00004027 // If this terminator has multiple identical successors (common for
4028 // switches), only handle each succ once.
4029 unsigned SuccMBBNo = SuccMBB->getNumber();
4030 if (SuccsHandled[SuccMBBNo]) continue;
4031 SuccsHandled[SuccMBBNo] = true;
4032
4033 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004034 PHINode *PN;
4035
4036 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4037 // nodes and Machine PHI nodes, but the incoming operands have not been
4038 // emitted yet.
4039 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004040 (PN = dyn_cast<PHINode>(I)); ++I) {
4041 // Ignore dead phi's.
4042 if (PN->use_empty()) continue;
4043
4044 unsigned Reg;
4045 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004046
Chris Lattner8c494ab2006-10-27 23:50:33 +00004047 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4048 unsigned &RegOut = ConstantsOut[C];
4049 if (RegOut == 0) {
4050 RegOut = FuncInfo.CreateRegForValue(C);
4051 UnorderedChains.push_back(
4052 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004053 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004054 Reg = RegOut;
4055 } else {
4056 Reg = FuncInfo.ValueMap[PHIOp];
4057 if (Reg == 0) {
4058 assert(isa<AllocaInst>(PHIOp) &&
4059 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4060 "Didn't codegen value into a register!??");
4061 Reg = FuncInfo.CreateRegForValue(PHIOp);
4062 UnorderedChains.push_back(
4063 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004064 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004065 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004066
4067 // Remember that this register needs to added to the machine PHI node as
4068 // the input for this MBB.
4069 MVT::ValueType VT = TLI.getValueType(PN->getType());
4070 unsigned NumElements;
4071 if (VT != MVT::Vector)
4072 NumElements = TLI.getNumElements(VT);
4073 else {
4074 MVT::ValueType VT1,VT2;
4075 NumElements =
4076 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4077 VT1, VT2);
4078 }
4079 for (unsigned i = 0, e = NumElements; i != e; ++i)
4080 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4081 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004082 }
4083 ConstantsOut.clear();
4084
Chris Lattnerddb870b2005-01-13 17:59:43 +00004085 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004086 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004087 SDOperand Root = SDL.getRoot();
4088 if (Root.getOpcode() != ISD::EntryToken) {
4089 unsigned i = 0, e = UnorderedChains.size();
4090 for (; i != e; ++i) {
4091 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4092 if (UnorderedChains[i].Val->getOperand(0) == Root)
4093 break; // Don't add the root if we already indirectly depend on it.
4094 }
4095
4096 if (i == e)
4097 UnorderedChains.push_back(Root);
4098 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004099 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4100 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004101 }
4102
Chris Lattner1c08c712005-01-07 07:47:53 +00004103 // Lower the terminator after the copies are emitted.
4104 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004105
Nate Begemanf15485a2006-03-27 01:32:24 +00004106 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004107 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004108 SwitchCases.clear();
4109 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004110 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004111
Chris Lattnera651cf62005-01-17 19:43:36 +00004112 // Make sure the root of the DAG is up-to-date.
4113 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004114}
4115
Nate Begemanf15485a2006-03-27 01:32:24 +00004116void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004117 // Get alias analysis for load/store combining.
4118 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4119
Chris Lattneraf21d552005-10-10 16:47:10 +00004120 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004121 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004122
Bill Wendling832171c2006-12-07 20:04:42 +00004123 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004124 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004125
Chris Lattner1c08c712005-01-07 07:47:53 +00004126 // Second step, hack on the DAG until it only uses operations and types that
4127 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004128 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004129
Bill Wendling832171c2006-12-07 20:04:42 +00004130 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004131 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004132
Chris Lattneraf21d552005-10-10 16:47:10 +00004133 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004134 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004135
Evan Chenga9c20912006-01-21 02:32:06 +00004136 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004137
Chris Lattnera33ef482005-03-30 01:10:47 +00004138 // Third, instruction select all of the operations to machine code, adding the
4139 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004140 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004141
Bill Wendling832171c2006-12-07 20:04:42 +00004142 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004143 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004144}
Chris Lattner1c08c712005-01-07 07:47:53 +00004145
Nate Begemanf15485a2006-03-27 01:32:24 +00004146void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4147 FunctionLoweringInfo &FuncInfo) {
4148 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4149 {
4150 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4151 CurDAG = &DAG;
4152
4153 // First step, lower LLVM code to some DAG. This DAG may use operations and
4154 // types that are not supported by the target.
4155 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4156
4157 // Second step, emit the lowered DAG as machine code.
4158 CodeGenAndEmitDAG(DAG);
4159 }
4160
Chris Lattnera33ef482005-03-30 01:10:47 +00004161 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004162 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004163 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004164 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4165 MachineInstr *PHI = PHINodesToUpdate[i].first;
4166 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4167 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004168 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004169 PHI->addMachineBasicBlockOperand(BB);
4170 }
4171 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004172 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004173
Nate Begeman9453eea2006-04-23 06:26:20 +00004174 // If the JumpTable record is filled in, then we need to emit a jump table.
4175 // Updating the PHI nodes is tricky in this case, since we need to determine
4176 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004177 if (JT.Reg) {
4178 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4179 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4180 CurDAG = &SDAG;
4181 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004182 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004183 // Set the current basic block to the mbb we wish to insert the code into
4184 BB = JT.MBB;
4185 SDL.setCurrentBasicBlock(BB);
4186 // Emit the code
4187 SDL.visitJumpTable(JT);
4188 SDAG.setRoot(SDL.getRoot());
4189 CodeGenAndEmitDAG(SDAG);
4190 // Update PHI Nodes
4191 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4192 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4193 MachineBasicBlock *PHIBB = PHI->getParent();
4194 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4195 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004196 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004197 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004198 PHI->addMachineBasicBlockOperand(RangeBB);
4199 }
4200 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004201 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004202 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004203 }
4204 }
4205 return;
4206 }
4207
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004208 // If the switch block involved a branch to one of the actual successors, we
4209 // need to update PHI nodes in that block.
4210 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4211 MachineInstr *PHI = PHINodesToUpdate[i].first;
4212 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4213 "This is not a machine PHI node that we are updating!");
4214 if (BB->isSuccessor(PHI->getParent())) {
4215 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4216 PHI->addMachineBasicBlockOperand(BB);
4217 }
4218 }
4219
Nate Begemanf15485a2006-03-27 01:32:24 +00004220 // If we generated any switch lowering information, build and codegen any
4221 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004222 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004223 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4224 CurDAG = &SDAG;
4225 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004226
Nate Begemanf15485a2006-03-27 01:32:24 +00004227 // Set the current basic block to the mbb we wish to insert the code into
4228 BB = SwitchCases[i].ThisBB;
4229 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004230
Nate Begemanf15485a2006-03-27 01:32:24 +00004231 // Emit the code
4232 SDL.visitSwitchCase(SwitchCases[i]);
4233 SDAG.setRoot(SDL.getRoot());
4234 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004235
4236 // Handle any PHI nodes in successors of this chunk, as if we were coming
4237 // from the original BB before switch expansion. Note that PHI nodes can
4238 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4239 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004240 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004241 for (MachineBasicBlock::iterator Phi = BB->begin();
4242 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4243 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4244 for (unsigned pn = 0; ; ++pn) {
4245 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4246 if (PHINodesToUpdate[pn].first == Phi) {
4247 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4248 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4249 break;
4250 }
4251 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004252 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004253
4254 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004255 if (BB == SwitchCases[i].FalseBB)
4256 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004257
4258 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004259 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004260 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004261 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004262 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004263 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004264}
Evan Chenga9c20912006-01-21 02:32:06 +00004265
Jim Laskey13ec7022006-08-01 14:21:23 +00004266
Evan Chenga9c20912006-01-21 02:32:06 +00004267//===----------------------------------------------------------------------===//
4268/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4269/// target node in the graph.
4270void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4271 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004272
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004273 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004274
4275 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004276 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004277 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004278 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004279
Jim Laskey9ff542f2006-08-01 18:29:48 +00004280 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004281 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004282 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004283}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004284
Chris Lattner03fc53c2006-03-06 00:22:00 +00004285
Jim Laskey9ff542f2006-08-01 18:29:48 +00004286HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4287 return new HazardRecognizer();
4288}
4289
Chris Lattner75548062006-10-11 03:58:02 +00004290//===----------------------------------------------------------------------===//
4291// Helper functions used by the generated instruction selector.
4292//===----------------------------------------------------------------------===//
4293// Calls to these methods are generated by tblgen.
4294
4295/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4296/// the dag combiner simplified the 255, we still want to match. RHS is the
4297/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4298/// specified in the .td file (e.g. 255).
4299bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4300 int64_t DesiredMaskS) {
4301 uint64_t ActualMask = RHS->getValue();
4302 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4303
4304 // If the actual mask exactly matches, success!
4305 if (ActualMask == DesiredMask)
4306 return true;
4307
4308 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4309 if (ActualMask & ~DesiredMask)
4310 return false;
4311
4312 // Otherwise, the DAG Combiner may have proven that the value coming in is
4313 // either already zero or is not demanded. Check for known zero input bits.
4314 uint64_t NeededMask = DesiredMask & ~ActualMask;
4315 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4316 return true;
4317
4318 // TODO: check to see if missing bits are just not demanded.
4319
4320 // Otherwise, this pattern doesn't match.
4321 return false;
4322}
4323
4324/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4325/// the dag combiner simplified the 255, we still want to match. RHS is the
4326/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4327/// specified in the .td file (e.g. 255).
4328bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4329 int64_t DesiredMaskS) {
4330 uint64_t ActualMask = RHS->getValue();
4331 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4332
4333 // If the actual mask exactly matches, success!
4334 if (ActualMask == DesiredMask)
4335 return true;
4336
4337 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4338 if (ActualMask & ~DesiredMask)
4339 return false;
4340
4341 // Otherwise, the DAG Combiner may have proven that the value coming in is
4342 // either already zero or is not demanded. Check for known zero input bits.
4343 uint64_t NeededMask = DesiredMask & ~ActualMask;
4344
4345 uint64_t KnownZero, KnownOne;
4346 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4347
4348 // If all the missing bits in the or are already known to be set, match!
4349 if ((NeededMask & KnownOne) == NeededMask)
4350 return true;
4351
4352 // TODO: check to see if missing bits are just not demanded.
4353
4354 // Otherwise, this pattern doesn't match.
4355 return false;
4356}
4357
Jim Laskey9ff542f2006-08-01 18:29:48 +00004358
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004359/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4360/// by tblgen. Others should not call it.
4361void SelectionDAGISel::
4362SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4363 std::vector<SDOperand> InOps;
4364 std::swap(InOps, Ops);
4365
4366 Ops.push_back(InOps[0]); // input chain.
4367 Ops.push_back(InOps[1]); // input asm string.
4368
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004369 unsigned i = 2, e = InOps.size();
4370 if (InOps[e-1].getValueType() == MVT::Flag)
4371 --e; // Don't process a flag operand if it is here.
4372
4373 while (i != e) {
4374 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4375 if ((Flags & 7) != 4 /*MEM*/) {
4376 // Just skip over this operand, copying the operands verbatim.
4377 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4378 i += (Flags >> 3) + 1;
4379 } else {
4380 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4381 // Otherwise, this is a memory operand. Ask the target to select it.
4382 std::vector<SDOperand> SelOps;
4383 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004384 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004385 exit(1);
4386 }
4387
4388 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004389 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4390 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004391 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4392 i += 2;
4393 }
4394 }
4395
4396 // Add the flag input back if present.
4397 if (e != InOps.size())
4398 Ops.push_back(InOps.back());
4399}