blob: 9be3a16975bab37ef55fc53bccd14e6da430cb81 [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"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.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"
Chris Lattner1c08c712005-01-07 07:47:53 +000047#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#else
Chris Lattner5e46a192006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#endif
61
Jim Laskeyeb577ba2006-08-02 12:30:23 +000062
63//===---------------------------------------------------------------------===//
64///
65/// RegisterScheduler class - Track the registration of instruction schedulers.
66///
67//===---------------------------------------------------------------------===//
68MachinePassRegistry RegisterScheduler::Registry;
69
70//===---------------------------------------------------------------------===//
71///
72/// ISHeuristic command line option for instruction schedulers.
73///
74//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000075namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000076 cl::opt<RegisterScheduler::FunctionPassCtor, false,
77 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000078 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000079 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000080 cl::desc("Instruction schedulers available:"));
81
Jim Laskey9ff542f2006-08-01 18:29:48 +000082 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000083 defaultListDAGScheduler("default", " Best scheduler for the target",
84 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000085} // namespace
86
Chris Lattner864635a2006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000135 };
136}
Evan Cheng4ef10862006-01-23 07:01:07 +0000137
Chris Lattner1c08c712005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
175 std::map<const Value*, unsigned> ValueMap;
176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 }
Chris Lattner571e4342006-10-27 21:36:01 +0000185
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
190 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000191
Chris Lattner3c384492006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
198 }
199 };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattnerbf209482005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000217/// entry block, return true. This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000219static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner1c08c712005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattnerbf209482005-10-30 19:42:35 +0000231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 AI != E; ++AI)
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
237
Chris Lattner1c08c712005-01-07 07:47:53 +0000238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
240 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000247 unsigned Align =
Owen Andersona69571c2006-05-03 01:29:57 +0000248 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000250
Reid Spencerb83eb642006-10-20 07:07:24 +0000251 // If the alignment of the value is smaller than the size of the
252 // value, and if the size of the value is particularly small
253 // (<= 8 bytes), round up to the size of the value for potentially
254 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000255 //
256 // FIXME: This could be made better with a preferred alignment hook in
257 // TargetData. It serves primarily to 8-byte align doubles for X86.
258 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000259 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000260 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000261 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000262 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 }
264
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000265 for (; BB != EB; ++BB)
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000267 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
268 if (!isa<AllocaInst>(I) ||
269 !StaticAllocaMap.count(cast<AllocaInst>(I)))
270 InitializeRegForValue(I);
271
272 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
273 // also creates the initial PHI MachineInstrs, though none of the input
274 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000275 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000276 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277 MBBMap[BB] = MBB;
278 MF.getBasicBlockList().push_back(MBB);
279
280 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
281 // appropriate.
282 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000283 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
284 if (PN->use_empty()) continue;
285
286 MVT::ValueType VT = TLI.getValueType(PN->getType());
287 unsigned NumElements;
288 if (VT != MVT::Vector)
289 NumElements = TLI.getNumElements(VT);
290 else {
291 MVT::ValueType VT1,VT2;
292 NumElements =
293 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
294 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000295 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000296 unsigned PHIReg = ValueMap[PN];
297 assert(PHIReg && "PHI node does not have an assigned virtual register!");
298 for (unsigned i = 0; i != NumElements; ++i)
299 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
300 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000301 }
302}
303
Chris Lattner3c384492006-03-16 19:51:18 +0000304/// CreateRegForValue - Allocate the appropriate number of virtual registers of
305/// the correctly promoted or expanded types. Assign these registers
306/// consecutive vreg numbers and return the first assigned number.
307unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308 MVT::ValueType VT = TLI.getValueType(V->getType());
309
310 // The number of multiples of registers that we need, to, e.g., split up
311 // a <2 x int64> -> 4 x i32 registers.
312 unsigned NumVectorRegs = 1;
313
314 // If this is a packed type, figure out what type it will decompose into
315 // and how many of the elements it will use.
316 if (VT == MVT::Vector) {
317 const PackedType *PTy = cast<PackedType>(V->getType());
318 unsigned NumElts = PTy->getNumElements();
319 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
323 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
324 NumElts >>= 1;
325 NumVectorRegs <<= 1;
326 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000327 if (NumElts == 1)
328 VT = EltTy;
329 else
330 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000331 }
332
333 // The common case is that we will only create one register for this
334 // value. If we have that case, create and return the virtual register.
335 unsigned NV = TLI.getNumElements(VT);
336 if (NV == 1) {
337 // If we are promoting this value, pick the next largest supported type.
338 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339 unsigned Reg = MakeReg(PromotedType);
340 // If this is a vector of supported or promoted types (e.g. 4 x i16),
341 // create all of the registers.
342 for (unsigned i = 1; i != NumVectorRegs; ++i)
343 MakeReg(PromotedType);
344 return Reg;
345 }
346
347 // If this value is represented with multiple target registers, make sure
348 // to create enough consecutive registers of the right (smaller) type.
349 unsigned NT = VT-1; // Find the type to use.
350 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
351 --NT;
352
353 unsigned R = MakeReg((MVT::ValueType)NT);
354 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
355 MakeReg((MVT::ValueType)NT);
356 return R;
357}
Chris Lattner1c08c712005-01-07 07:47:53 +0000358
359//===----------------------------------------------------------------------===//
360/// SelectionDAGLowering - This is the common target-independent lowering
361/// implementation that is parameterized by a TargetLowering object.
362/// Also, targets can overload any lowering method.
363///
364namespace llvm {
365class SelectionDAGLowering {
366 MachineBasicBlock *CurMBB;
367
368 std::map<const Value*, SDOperand> NodeMap;
369
Chris Lattnerd3948112005-01-17 22:19:26 +0000370 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
371 /// them up and then emit token factor nodes when possible. This allows us to
372 /// get simple disambiguation between loads without worrying about alias
373 /// analysis.
374 std::vector<SDOperand> PendingLoads;
375
Nate Begemanf15485a2006-03-27 01:32:24 +0000376 /// Case - A pair of values to record the Value for a switch case, and the
377 /// case's target basic block.
378 typedef std::pair<Constant*, MachineBasicBlock*> Case;
379 typedef std::vector<Case>::iterator CaseItr;
380 typedef std::pair<CaseItr, CaseItr> CaseRange;
381
382 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
383 /// of conditional branches.
384 struct CaseRec {
385 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
386 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
387
388 /// CaseBB - The MBB in which to emit the compare and branch
389 MachineBasicBlock *CaseBB;
390 /// LT, GE - If nonzero, we know the current case value must be less-than or
391 /// greater-than-or-equal-to these Constants.
392 Constant *LT;
393 Constant *GE;
394 /// Range - A pair of iterators representing the range of case values to be
395 /// processed at this point in the binary search tree.
396 CaseRange Range;
397 };
398
399 /// The comparison function for sorting Case values.
400 struct CaseCmp {
401 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000402 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
403 if (I1->getType()->isUnsigned())
404 return I1->getZExtValue() <
405 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000406
Reid Spencerb83eb642006-10-20 07:07:24 +0000407 return cast<const ConstantInt>(C1.first)->getSExtValue() <
408 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000409 }
410 };
411
Chris Lattner1c08c712005-01-07 07:47:53 +0000412public:
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
416 TargetLowering &TLI;
417 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000418 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000419
Nate Begemanf15485a2006-03-27 01:32:24 +0000420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000423 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000424
Chris Lattner1c08c712005-01-07 07:47:53 +0000425 /// FuncInfo - Information about the function as a whole.
426 ///
427 FunctionLoweringInfo &FuncInfo;
428
429 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000430 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000432 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 }
434
Chris Lattnera651cf62005-01-17 19:43:36 +0000435 /// getRoot - Return the current virtual root of the Selection DAG.
436 ///
437 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000438 if (PendingLoads.empty())
439 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000440
Chris Lattnerd3948112005-01-17 22:19:26 +0000441 if (PendingLoads.size() == 1) {
442 SDOperand Root = PendingLoads[0];
443 DAG.setRoot(Root);
444 PendingLoads.clear();
445 return Root;
446 }
447
448 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000449 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
450 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000451 PendingLoads.clear();
452 DAG.setRoot(Root);
453 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000454 }
455
Chris Lattner571e4342006-10-27 21:36:01 +0000456 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457
Chris Lattner1c08c712005-01-07 07:47:53 +0000458 void visit(Instruction &I) { visit(I.getOpcode(), I); }
459
460 void visit(unsigned Opcode, User &I) {
461 switch (Opcode) {
462 default: assert(0 && "Unknown instruction type encountered!");
463 abort();
464 // Build the switch statement using the Instruction.def file.
465#define HANDLE_INST(NUM, OPCODE, CLASS) \
466 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
467#include "llvm/Instruction.def"
468 }
469 }
470
471 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
472
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000473 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000474 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000475 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000476
477 SDOperand getIntPtrConstant(uint64_t Val) {
478 return DAG.getConstant(Val, TLI.getPointerTy());
479 }
480
Chris Lattner199862b2006-03-16 19:57:50 +0000481 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000482
483 const SDOperand &setValue(const Value *V, SDOperand NewN) {
484 SDOperand &N = NodeMap[V];
485 assert(N.Val == 0 && "Already set a value for this node!");
486 return N = NewN;
487 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000488
Chris Lattner864635a2006-02-22 22:37:12 +0000489 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
490 MVT::ValueType VT,
491 bool OutReg, bool InReg,
492 std::set<unsigned> &OutputRegs,
493 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000494
Chris Lattner571e4342006-10-27 21:36:01 +0000495 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
496 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
497 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000498 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000499 void ExportFromCurrentBlock(Value *V);
500
Chris Lattner1c08c712005-01-07 07:47:53 +0000501 // Terminator instructions.
502 void visitRet(ReturnInst &I);
503 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000504 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000505 void visitUnreachable(UnreachableInst &I) { /* noop */ }
506
Nate Begemanf15485a2006-03-27 01:32:24 +0000507 // Helper for visitSwitch
508 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000509 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000510
Chris Lattner1c08c712005-01-07 07:47:53 +0000511 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
513 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
514
Reid Spencer1628cec2006-10-26 06:15:43 +0000515 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
516 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000517 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000518 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000519 if (I.getType()->isFloatingPoint())
520 visitFPBinary(I, ISD::FADD, ISD::VADD);
521 else
522 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000523 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000524 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000525 void visitMul(User &I) {
526 if (I.getType()->isFloatingPoint())
527 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
528 else
529 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000530 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000531 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
532 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
533 void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV, ISD::VSDIV); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000534 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000535 const Type *Ty = I.getType();
Reid Spencer1628cec2006-10-26 06:15:43 +0000536 if (Ty->isFloatingPoint())
537 visitFPBinary(I, ISD::FREM, 0);
538 else
539 visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000540 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000541 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
542 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
543 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000544 void visitShl(User &I) { visitShift(I, ISD::SHL); }
545 void visitShr(User &I) {
546 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000547 }
548
Evan Chengf6f95812006-05-23 06:40:47 +0000549 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
550 ISD::CondCode FPOpc);
551 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
552 ISD::SETOEQ); }
553 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
554 ISD::SETUNE); }
555 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
556 ISD::SETOLE); }
557 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
558 ISD::SETOGE); }
559 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
560 ISD::SETOLT); }
561 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
562 ISD::SETOGT); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000563
Chris Lattner2bbd8102006-03-29 00:11:43 +0000564 void visitExtractElement(User &I);
565 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000566 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000567
Chris Lattner1c08c712005-01-07 07:47:53 +0000568 void visitGetElementPtr(User &I);
569 void visitCast(User &I);
570 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000571
572 void visitMalloc(MallocInst &I);
573 void visitFree(FreeInst &I);
574 void visitAlloca(AllocaInst &I);
575 void visitLoad(LoadInst &I);
576 void visitStore(StoreInst &I);
577 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
578 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000579 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000580 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000581 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000582
Chris Lattner1c08c712005-01-07 07:47:53 +0000583 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000584 void visitVAArg(VAArgInst &I);
585 void visitVAEnd(CallInst &I);
586 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000587 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000588
Chris Lattner7041ee32005-01-11 05:56:49 +0000589 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000590
591 void visitUserOp1(Instruction &I) {
592 assert(0 && "UserOp1 should not exist at instruction selection time!");
593 abort();
594 }
595 void visitUserOp2(Instruction &I) {
596 assert(0 && "UserOp2 should not exist at instruction selection time!");
597 abort();
598 }
599};
600} // end namespace llvm
601
Chris Lattner199862b2006-03-16 19:57:50 +0000602SDOperand SelectionDAGLowering::getValue(const Value *V) {
603 SDOperand &N = NodeMap[V];
604 if (N.Val) return N;
605
606 const Type *VTy = V->getType();
607 MVT::ValueType VT = TLI.getValueType(VTy);
608 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
610 visit(CE->getOpcode(), *CE);
611 assert(N.Val && "visit didn't populate the ValueMap!");
612 return N;
613 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
614 return N = DAG.getGlobalAddress(GV, VT);
615 } else if (isa<ConstantPointerNull>(C)) {
616 return N = DAG.getConstant(0, TLI.getPointerTy());
617 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000618 if (!isa<PackedType>(VTy))
619 return N = DAG.getNode(ISD::UNDEF, VT);
620
Chris Lattnerb2827b02006-03-19 00:52:58 +0000621 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000622 const PackedType *PTy = cast<PackedType>(VTy);
623 unsigned NumElements = PTy->getNumElements();
624 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
625
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000626 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000627 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
628
629 // Create a VConstant node with generic Vector type.
630 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
631 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000632 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
633 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000634 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
635 return N = DAG.getConstantFP(CFP->getValue(), VT);
636 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
637 unsigned NumElements = PTy->getNumElements();
638 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000639
640 // Now that we know the number and type of the elements, push a
641 // Constant or ConstantFP node onto the ops list for each element of
642 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000643 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000644 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000645 for (unsigned i = 0; i != NumElements; ++i)
646 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000647 } else {
648 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
649 SDOperand Op;
650 if (MVT::isFloatingPoint(PVT))
651 Op = DAG.getConstantFP(0, PVT);
652 else
653 Op = DAG.getConstant(0, PVT);
654 Ops.assign(NumElements, Op);
655 }
656
Chris Lattnerb2827b02006-03-19 00:52:58 +0000657 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000658 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
659 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000660 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000661 } else {
662 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000663 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000664 }
665 }
666
667 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
668 std::map<const AllocaInst*, int>::iterator SI =
669 FuncInfo.StaticAllocaMap.find(AI);
670 if (SI != FuncInfo.StaticAllocaMap.end())
671 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
672 }
673
674 std::map<const Value*, unsigned>::const_iterator VMI =
675 FuncInfo.ValueMap.find(V);
676 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
677
678 unsigned InReg = VMI->second;
679
680 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000681 if (VT != MVT::Vector) {
682 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000683
Chris Lattner70c2a612006-03-31 02:06:56 +0000684 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
685 if (DestVT < VT) {
686 // Source must be expanded. This input value is actually coming from the
687 // register pair VMI->second and VMI->second+1.
688 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
689 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
690 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000691 if (MVT::isFloatingPoint(VT))
692 N = DAG.getNode(ISD::FP_ROUND, VT, N);
693 else
694 N = DAG.getNode(ISD::TRUNCATE, VT, N);
695 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000696 } else {
697 // Otherwise, if this is a vector, make it available as a generic vector
698 // here.
699 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000700 const PackedType *PTy = cast<PackedType>(VTy);
701 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000702 PTyLegalElementVT);
703
704 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000705 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000706 if (PTyElementVT == PTyLegalElementVT) {
707 // If the value types are legal, just VBUILD the CopyFromReg nodes.
708 for (unsigned i = 0; i != NE; ++i)
709 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
710 PTyElementVT));
711 } else if (PTyElementVT < PTyLegalElementVT) {
712 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
713 for (unsigned i = 0; i != NE; ++i) {
714 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
715 PTyElementVT);
716 if (MVT::isFloatingPoint(PTyElementVT))
717 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
718 else
719 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
720 Ops.push_back(Op);
721 }
722 } else {
723 // If the register was expanded, use BUILD_PAIR.
724 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
725 for (unsigned i = 0; i != NE/2; ++i) {
726 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727 PTyElementVT);
728 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
729 PTyElementVT);
730 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
731 }
732 }
733
734 Ops.push_back(DAG.getConstant(NE, MVT::i32));
735 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000736 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000737
738 // Finally, use a VBIT_CONVERT to make this available as the appropriate
739 // vector type.
740 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
741 DAG.getConstant(PTy->getNumElements(),
742 MVT::i32),
743 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000744 }
745
746 return N;
747}
748
749
Chris Lattner1c08c712005-01-07 07:47:53 +0000750void SelectionDAGLowering::visitRet(ReturnInst &I) {
751 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000752 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000753 return;
754 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000755 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000756 NewValues.push_back(getRoot());
757 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
758 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000759 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000760
761 // If this is an integer return value, we need to promote it ourselves to
762 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
763 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000764 // FIXME: C calling convention requires the return type to be promoted to
765 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000766 if (MVT::isInteger(RetOp.getValueType()) &&
767 RetOp.getValueType() < MVT::i64) {
768 MVT::ValueType TmpVT;
769 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
770 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
771 else
772 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000773
Evan Cheng8e7d0562006-05-26 23:09:09 +0000774 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000775 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
776 else
777 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
778 }
779 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000780 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000781 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000784}
785
Chris Lattner571e4342006-10-27 21:36:01 +0000786/// ExportFromCurrentBlock - If this condition isn't known to be exported from
787/// the current basic block, add it to ValueMap now so that we'll get a
788/// CopyTo/FromReg.
789void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790 // No need to export constants.
791 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792
793 // Already exported?
794 if (FuncInfo.isExportedInst(V)) return;
795
796 unsigned Reg = FuncInfo.InitializeRegForValue(V);
797 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798}
799
Chris Lattner8c494ab2006-10-27 23:50:33 +0000800bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801 const BasicBlock *FromBB) {
802 // The operands of the setcc have to be in this block. We don't know
803 // how to export them from some other block.
804 if (Instruction *VI = dyn_cast<Instruction>(V)) {
805 // Can export from current BB.
806 if (VI->getParent() == FromBB)
807 return true;
808
809 // Is already exported, noop.
810 return FuncInfo.isExportedInst(V);
811 }
812
813 // If this is an argument, we can export it if the BB is the entry block or
814 // if it is already exported.
815 if (isa<Argument>(V)) {
816 if (FromBB == &FromBB->getParent()->getEntryBlock())
817 return true;
818
819 // Otherwise, can only export this if it is already exported.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // Otherwise, constants can always be exported.
824 return true;
825}
826
Chris Lattner6a586c82006-10-29 21:01:20 +0000827static bool InBlock(const Value *V, const BasicBlock *BB) {
828 if (const Instruction *I = dyn_cast<Instruction>(V))
829 return I->getParent() == BB;
830 return true;
831}
832
Chris Lattner571e4342006-10-27 21:36:01 +0000833/// FindMergedConditions - If Cond is an expression like
834void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835 MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB,
837 MachineBasicBlock *CurBB,
838 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000839 // If this node is not part of the or/and tree, emit it as a branch.
840 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
841
842 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000843 BOp->getParent() != CurBB->getBasicBlock() ||
844 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
845 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000846 const BasicBlock *BB = CurBB->getBasicBlock();
847
Chris Lattnerdf19f272006-10-31 22:37:42 +0000848 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
849 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
850 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
851 // The operands of the setcc have to be in this block. We don't know
852 // how to export them from some other block. If this is the first
853 // block of the sequence, no exporting is needed.
854 (CurBB == CurMBB ||
855 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
856 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
857 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
858 II->getOperand(2), TBB, FBB, CurBB);
859 SwitchCases.push_back(CB);
860 return;
861 }
862
863
Chris Lattner571e4342006-10-27 21:36:01 +0000864 // If the leaf of the tree is a setcond inst, merge the condition into the
865 // caseblock.
866 if (BOp && isa<SetCondInst>(BOp) &&
867 // The operands of the setcc have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000868 // how to export them from some other block. If this is the first block
869 // of the sequence, no exporting is needed.
870 (CurBB == CurMBB ||
871 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
872 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Chris Lattner571e4342006-10-27 21:36:01 +0000873 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
874 switch (BOp->getOpcode()) {
875 default: assert(0 && "Unknown setcc opcode!");
876 case Instruction::SetEQ:
877 SignCond = ISD::SETEQ;
878 UnsCond = ISD::SETEQ;
879 FPCond = ISD::SETOEQ;
880 break;
881 case Instruction::SetNE:
882 SignCond = ISD::SETNE;
883 UnsCond = ISD::SETNE;
884 FPCond = ISD::SETUNE;
885 break;
886 case Instruction::SetLE:
887 SignCond = ISD::SETLE;
888 UnsCond = ISD::SETULE;
889 FPCond = ISD::SETOLE;
890 break;
891 case Instruction::SetGE:
892 SignCond = ISD::SETGE;
893 UnsCond = ISD::SETUGE;
894 FPCond = ISD::SETOGE;
895 break;
896 case Instruction::SetLT:
897 SignCond = ISD::SETLT;
898 UnsCond = ISD::SETULT;
899 FPCond = ISD::SETOLT;
900 break;
901 case Instruction::SetGT:
902 SignCond = ISD::SETGT;
903 UnsCond = ISD::SETUGT;
904 FPCond = ISD::SETOGT;
905 break;
906 }
907
908 const Type *OpType = BOp->getOperand(0)->getType();
909 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
910 OpType = PTy->getElementType();
911
912 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
913 Condition = FPCond;
914 else if (OpType->isUnsigned())
915 Condition = UnsCond;
916 else
917 Condition = SignCond;
918
919 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
920 BOp->getOperand(1), TBB, FBB, CurBB);
921 SwitchCases.push_back(CB);
922 return;
923 }
924
925 // Create a CaseBlock record representing this branch.
926 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
927 TBB, FBB, CurBB);
928 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000929 return;
930 }
931
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000932
933 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000934 MachineFunction::iterator BBI = CurBB;
935 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
936 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
937
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000938 if (Opc == Instruction::Or) {
939 // Codegen X | Y as:
940 // jmp_if_X TBB
941 // jmp TmpBB
942 // TmpBB:
943 // jmp_if_Y TBB
944 // jmp FBB
945 //
Chris Lattner571e4342006-10-27 21:36:01 +0000946
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000947 // Emit the LHS condition.
948 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
949
950 // Emit the RHS condition into TmpBB.
951 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
952 } else {
953 assert(Opc == Instruction::And && "Unknown merge op!");
954 // Codegen X & Y as:
955 // jmp_if_X TmpBB
956 // jmp FBB
957 // TmpBB:
958 // jmp_if_Y TBB
959 // jmp FBB
960 //
961 // This requires creation of TmpBB after CurBB.
962
963 // Emit the LHS condition.
964 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
965
966 // Emit the RHS condition into TmpBB.
967 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
968 }
Chris Lattner571e4342006-10-27 21:36:01 +0000969}
970
Chris Lattnerdf19f272006-10-31 22:37:42 +0000971/// If the set of cases should be emitted as a series of branches, return true.
972/// If we should emit this as a bunch of and/or'd together conditions, return
973/// false.
974static bool
975ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
976 if (Cases.size() != 2) return true;
977
Chris Lattner0ccb5002006-10-31 23:06:00 +0000978 // If this is two comparisons of the same values or'd or and'd together, they
979 // will get folded into a single comparison, so don't emit two blocks.
980 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
981 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
982 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
983 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
984 return false;
985 }
986
Chris Lattnerdf19f272006-10-31 22:37:42 +0000987 return true;
988}
989
Chris Lattner1c08c712005-01-07 07:47:53 +0000990void SelectionDAGLowering::visitBr(BranchInst &I) {
991 // Update machine-CFG edges.
992 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000993
994 // Figure out which block is immediately after the current one.
995 MachineBasicBlock *NextBlock = 0;
996 MachineFunction::iterator BBI = CurMBB;
997 if (++BBI != CurMBB->getParent()->end())
998 NextBlock = BBI;
999
1000 if (I.isUnconditional()) {
1001 // If this is not a fall-through branch, emit the branch.
1002 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001003 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001004 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001005
Chris Lattner57ab6592006-10-24 17:57:59 +00001006 // Update machine-CFG edges.
1007 CurMBB->addSuccessor(Succ0MBB);
1008
1009 return;
1010 }
1011
1012 // If this condition is one of the special cases we handle, do special stuff
1013 // now.
1014 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001015 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001016
1017 // If this is a series of conditions that are or'd or and'd together, emit
1018 // this as a sequence of branches instead of setcc's with and/or operations.
1019 // For example, instead of something like:
1020 // cmp A, B
1021 // C = seteq
1022 // cmp D, E
1023 // F = setle
1024 // or C, F
1025 // jnz foo
1026 // Emit:
1027 // cmp A, B
1028 // je foo
1029 // cmp D, E
1030 // jle foo
1031 //
1032 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1033 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001034 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001035 BOp->getOpcode() == Instruction::Or)) {
1036 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001037 // If the compares in later blocks need to use values not currently
1038 // exported from this block, export them now. This block should always
1039 // be the first entry.
1040 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1041
Chris Lattnerdf19f272006-10-31 22:37:42 +00001042 // Allow some cases to be rejected.
1043 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001044 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1045 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1046 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1047 }
1048
1049 // Emit the branch for this block.
1050 visitSwitchCase(SwitchCases[0]);
1051 SwitchCases.erase(SwitchCases.begin());
1052 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001053 }
1054
Chris Lattner0ccb5002006-10-31 23:06:00 +00001055 // Okay, we decided not to do this, remove any inserted MBB's and clear
1056 // SwitchCases.
1057 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1058 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1059
Chris Lattnerdf19f272006-10-31 22:37:42 +00001060 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001061 }
1062 }
Chris Lattner24525952006-10-24 18:07:37 +00001063
1064 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +00001065 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001066 Succ0MBB, Succ1MBB, CurMBB);
1067 // Use visitSwitchCase to actually insert the fast branch sequence for this
1068 // cond branch.
1069 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001070}
1071
Nate Begemanf15485a2006-03-27 01:32:24 +00001072/// visitSwitchCase - Emits the necessary code to represent a single node in
1073/// the binary search tree resulting from lowering a switch instruction.
1074void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001075 SDOperand Cond;
1076 SDOperand CondLHS = getValue(CB.CmpLHS);
1077
Chris Lattner571e4342006-10-27 21:36:01 +00001078 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1079 // handle common cases produced by branch lowering.
1080 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001081 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +00001082 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1083 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1084 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1085 } else
1086 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001087
1088 // Set NextBlock to be the MBB immediately after the current one, if any.
1089 // This is used to avoid emitting unnecessary branches to the next block.
1090 MachineBasicBlock *NextBlock = 0;
1091 MachineFunction::iterator BBI = CurMBB;
1092 if (++BBI != CurMBB->getParent()->end())
1093 NextBlock = BBI;
1094
1095 // If the lhs block is the next block, invert the condition so that we can
1096 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001097 if (CB.TrueBB == NextBlock) {
1098 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001099 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1100 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1101 }
1102 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001103 DAG.getBasicBlock(CB.TrueBB));
1104 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001105 DAG.setRoot(BrCond);
1106 else
1107 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001108 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001109 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001110 CurMBB->addSuccessor(CB.TrueBB);
1111 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001112}
1113
Nate Begeman37efe672006-04-22 18:53:45 +00001114void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001115 // Emit the code for the jump table
1116 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001117 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1118 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1119 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1120 Table, Index));
1121 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001122}
1123
Nate Begemanf15485a2006-03-27 01:32:24 +00001124void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1125 // Figure out which block is immediately after the current one.
1126 MachineBasicBlock *NextBlock = 0;
1127 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001128
Nate Begemanf15485a2006-03-27 01:32:24 +00001129 if (++BBI != CurMBB->getParent()->end())
1130 NextBlock = BBI;
1131
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001132 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1133
Nate Begemanf15485a2006-03-27 01:32:24 +00001134 // If there is only the default destination, branch to it if it is not the
1135 // next basic block. Otherwise, just fall through.
1136 if (I.getNumOperands() == 2) {
1137 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001138
Nate Begemanf15485a2006-03-27 01:32:24 +00001139 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001140 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001141 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001142 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001143
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001144 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001145 return;
1146 }
1147
1148 // If there are any non-default case statements, create a vector of Cases
1149 // representing each one, and sort the vector so that we can efficiently
1150 // create a binary search tree from them.
1151 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001152
Nate Begemanf15485a2006-03-27 01:32:24 +00001153 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1154 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1155 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1156 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001157
Nate Begemanf15485a2006-03-27 01:32:24 +00001158 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1159
1160 // Get the Value to be switched on and default basic blocks, which will be
1161 // inserted into CaseBlock records, representing basic blocks in the binary
1162 // search tree.
1163 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001164
1165 // Get the MachineFunction which holds the current MBB. This is used during
1166 // emission of jump tables, and when inserting any additional MBBs necessary
1167 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001168 MachineFunction *CurMF = CurMBB->getParent();
1169 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001170
1171 // If the switch has few cases (two or less) emit a series of specific
1172 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001173 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001174 // TODO: If any two of the cases has the same destination, and if one value
1175 // is the same as the other, but has one bit unset that the other has set,
1176 // use bit manipulation to do two compares at once. For example:
1177 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1178
Chris Lattnerb3543432006-10-23 18:38:22 +00001179 // Rearrange the case blocks so that the last one falls through if possible.
1180 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1181 // The last case block won't fall through into 'NextBlock' if we emit the
1182 // branches in this order. See if rearranging a case value would help.
1183 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1184 if (Cases[i].second == NextBlock) {
1185 std::swap(Cases[i], Cases.back());
1186 break;
1187 }
1188 }
1189 }
1190
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001191 // Create a CaseBlock record representing a conditional branch to
1192 // the Case's target mbb if the value being switched on SV is equal
1193 // to C.
1194 MachineBasicBlock *CurBlock = CurMBB;
1195 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1196 MachineBasicBlock *FallThrough;
1197 if (i != e-1) {
1198 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1199 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1200 } else {
1201 // If the last case doesn't match, go to the default block.
1202 FallThrough = Default;
1203 }
1204
1205 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1206 Cases[i].second, FallThrough, CurBlock);
1207
1208 // If emitting the first comparison, just call visitSwitchCase to emit the
1209 // code into the current block. Otherwise, push the CaseBlock onto the
1210 // vector to be later processed by SDISel, and insert the node's MBB
1211 // before the next MBB.
1212 if (CurBlock == CurMBB)
1213 visitSwitchCase(CB);
1214 else
1215 SwitchCases.push_back(CB);
1216
1217 CurBlock = FallThrough;
1218 }
1219 return;
1220 }
Nate Begeman37efe672006-04-22 18:53:45 +00001221
Nate Begeman17c275f2006-05-08 16:51:36 +00001222 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1223 // target supports indirect branches, then emit a jump table rather than
1224 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001225 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1226 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001227 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001228 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1229 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001230 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1231
Nate Begeman17c275f2006-05-08 16:51:36 +00001232 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001233 // Create a new basic block to hold the code for loading the address
1234 // of the jump table, and jumping to it. Update successor information;
1235 // we will either branch to the default case for the switch, or the jump
1236 // table.
1237 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1238 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1239 CurMBB->addSuccessor(Default);
1240 CurMBB->addSuccessor(JumpTableBB);
1241
1242 // Subtract the lowest switch case value from the value being switched on
1243 // and conditional branch to default mbb if the result is greater than the
1244 // difference between smallest and largest cases.
1245 SDOperand SwitchOp = getValue(SV);
1246 MVT::ValueType VT = SwitchOp.getValueType();
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1248 DAG.getConstant(First, VT));
1249
1250 // The SDNode we just created, which holds the value being switched on
1251 // minus the the smallest case value, needs to be copied to a virtual
1252 // register so it can be used as an index into the jump table in a
1253 // subsequent basic block. This value may be smaller or larger than the
1254 // target's pointer type, and therefore require extension or truncating.
1255 if (VT > TLI.getPointerTy())
1256 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1257 else
1258 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001259
Nate Begeman37efe672006-04-22 18:53:45 +00001260 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1261 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1262
1263 // Emit the range check for the jump table, and branch to the default
1264 // block for the switch statement if the value being switched on exceeds
1265 // the largest case in the switch.
1266 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1267 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1268 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1269 DAG.getBasicBlock(Default)));
1270
Nate Begemanf4360a42006-05-03 03:48:02 +00001271 // Build a vector of destination BBs, corresponding to each target
1272 // of the jump table. If the value of the jump table slot corresponds to
1273 // a case statement, push the case's BB onto the vector, otherwise, push
1274 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001275 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001276 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001277 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001278 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001279 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001280 ++ii;
1281 } else {
1282 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001283 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001284
Chris Lattner8c494ab2006-10-27 23:50:33 +00001285 // Update successor info. Add one edge to each unique successor.
1286 // Vector bool would be better, but vector<bool> is really slow.
1287 std::vector<unsigned char> SuccsHandled;
1288 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1289
Chris Lattnerc66764c2006-09-10 06:36:57 +00001290 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001291 E = DestBBs.end(); I != E; ++I) {
1292 if (!SuccsHandled[(*I)->getNumber()]) {
1293 SuccsHandled[(*I)->getNumber()] = true;
1294 JumpTableBB->addSuccessor(*I);
1295 }
1296 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001297
1298 // Create a jump table index for this jump table, or return an existing
1299 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001300 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1301
1302 // Set the jump table information so that we can codegen it as a second
1303 // MachineBasicBlock
1304 JT.Reg = JumpTableReg;
1305 JT.JTI = JTI;
1306 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001307 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001308 return;
1309 }
1310 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001311
1312 // Push the initial CaseRec onto the worklist
1313 std::vector<CaseRec> CaseVec;
1314 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1315
1316 while (!CaseVec.empty()) {
1317 // Grab a record representing a case range to process off the worklist
1318 CaseRec CR = CaseVec.back();
1319 CaseVec.pop_back();
1320
1321 // Size is the number of Cases represented by this range. If Size is 1,
1322 // then we are processing a leaf of the binary search tree. Otherwise,
1323 // we need to pick a pivot, and push left and right ranges onto the
1324 // worklist.
1325 unsigned Size = CR.Range.second - CR.Range.first;
1326
1327 if (Size == 1) {
1328 // Create a CaseBlock record representing a conditional branch to
1329 // the Case's target mbb if the value being switched on SV is equal
1330 // to C. Otherwise, branch to default.
1331 Constant *C = CR.Range.first->first;
1332 MachineBasicBlock *Target = CR.Range.first->second;
1333 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1334 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001335
Nate Begemanf15485a2006-03-27 01:32:24 +00001336 // If the MBB representing the leaf node is the current MBB, then just
1337 // call visitSwitchCase to emit the code into the current block.
1338 // Otherwise, push the CaseBlock onto the vector to be later processed
1339 // by SDISel, and insert the node's MBB before the next MBB.
1340 if (CR.CaseBB == CurMBB)
1341 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001342 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001343 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001344 } else {
1345 // split case range at pivot
1346 CaseItr Pivot = CR.Range.first + (Size / 2);
1347 CaseRange LHSR(CR.Range.first, Pivot);
1348 CaseRange RHSR(Pivot, CR.Range.second);
1349 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001350 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001351
Nate Begemanf15485a2006-03-27 01:32:24 +00001352 // We know that we branch to the LHS if the Value being switched on is
1353 // less than the Pivot value, C. We use this to optimize our binary
1354 // tree a bit, by recognizing that if SV is greater than or equal to the
1355 // LHS's Case Value, and that Case Value is exactly one less than the
1356 // Pivot's Value, then we can branch directly to the LHS's Target,
1357 // rather than creating a leaf node for it.
1358 if ((LHSR.second - LHSR.first) == 1 &&
1359 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001360 cast<ConstantIntegral>(C)->getZExtValue() ==
1361 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001362 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001363 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001364 TrueBB = new MachineBasicBlock(LLVMBB);
1365 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1366 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001367 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001368
Nate Begemanf15485a2006-03-27 01:32:24 +00001369 // Similar to the optimization above, if the Value being switched on is
1370 // known to be less than the Constant CR.LT, and the current Case Value
1371 // is CR.LT - 1, then we can branch directly to the target block for
1372 // the current Case Value, rather than emitting a RHS leaf node for it.
1373 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001374 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1375 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001376 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001377 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001378 FalseBB = new MachineBasicBlock(LLVMBB);
1379 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1380 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001381 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001382
Nate Begemanf15485a2006-03-27 01:32:24 +00001383 // Create a CaseBlock record representing a conditional branch to
1384 // the LHS node if the value being switched on SV is less than C.
1385 // Otherwise, branch to LHS.
1386 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001388
Nate Begemanf15485a2006-03-27 01:32:24 +00001389 if (CR.CaseBB == CurMBB)
1390 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001391 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001392 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001393 }
1394 }
1395}
1396
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001397void SelectionDAGLowering::visitSub(User &I) {
1398 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001399 if (I.getType()->isFloatingPoint()) {
1400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1401 if (CFP->isExactlyValue(-0.0)) {
1402 SDOperand Op2 = getValue(I.getOperand(1));
1403 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1404 return;
1405 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001406 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1407 } else
1408 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001409}
1410
Reid Spencer1628cec2006-10-26 06:15:43 +00001411void
1412SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001413 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001414 SDOperand Op1 = getValue(I.getOperand(0));
1415 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001416
Reid Spencer1628cec2006-10-26 06:15:43 +00001417 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001418 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1419 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1420 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001421 } else {
1422 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1423 }
1424}
1425
1426void
1427SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1428 const Type *Ty = I.getType();
1429 SDOperand Op1 = getValue(I.getOperand(0));
1430 SDOperand Op2 = getValue(I.getOperand(1));
1431
1432 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1433 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1434 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1435 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1436 } else {
1437 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001438 }
Nate Begemane21ea612005-11-18 07:42:56 +00001439}
Chris Lattner2c49f272005-01-19 22:31:21 +00001440
Nate Begemane21ea612005-11-18 07:42:56 +00001441void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1442 SDOperand Op1 = getValue(I.getOperand(0));
1443 SDOperand Op2 = getValue(I.getOperand(1));
1444
1445 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1446
Chris Lattner1c08c712005-01-07 07:47:53 +00001447 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1448}
1449
1450void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001451 ISD::CondCode UnsignedOpcode,
1452 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001453 SDOperand Op1 = getValue(I.getOperand(0));
1454 SDOperand Op2 = getValue(I.getOperand(1));
1455 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001456 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001457 Opcode = FPOpcode;
1458 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001459 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001460 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001461}
1462
1463void SelectionDAGLowering::visitSelect(User &I) {
1464 SDOperand Cond = getValue(I.getOperand(0));
1465 SDOperand TrueVal = getValue(I.getOperand(1));
1466 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001467 if (!isa<PackedType>(I.getType())) {
1468 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1469 TrueVal, FalseVal));
1470 } else {
1471 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1472 *(TrueVal.Val->op_end()-2),
1473 *(TrueVal.Val->op_end()-1)));
1474 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001475}
1476
1477void SelectionDAGLowering::visitCast(User &I) {
1478 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001479 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001480 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +00001481
Chris Lattnere25ca692006-03-22 20:09:35 +00001482 if (DestVT == MVT::Vector) {
1483 // This is a cast to a vector from something else. This is always a bit
1484 // convert. Get information about the input vector.
1485 const PackedType *DestTy = cast<PackedType>(I.getType());
1486 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1487 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1488 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1489 DAG.getValueType(EltVT)));
1490 } else if (SrcVT == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001491 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001492 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +00001493 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001494 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +00001495 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001496 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001497 } else if (isInteger(SrcVT)) {
1498 if (isInteger(DestVT)) { // Int -> Int cast
1499 if (DestVT < SrcVT) // Truncating cast?
1500 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001501 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001502 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001503 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001504 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner7e358902006-03-22 22:20:49 +00001505 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001506 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001507 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001508 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001509 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001510 } else {
1511 assert(0 && "Unknown cast!");
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001512 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001513 } else if (isFloatingPoint(SrcVT)) {
1514 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1515 if (DestVT < SrcVT) // Rounding cast?
1516 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001517 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001518 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001519 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001520 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001521 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001522 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001523 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001524 } else {
1525 assert(0 && "Unknown cast!");
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001526 }
1527 } else {
Chris Lattnere25ca692006-03-22 20:09:35 +00001528 assert(SrcVT == MVT::Vector && "Unknown cast!");
1529 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1530 // This is a cast from a vector to something else. This is always a bit
1531 // convert. Get information about the input vector.
1532 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner1c08c712005-01-07 07:47:53 +00001533 }
1534}
1535
Chris Lattner2bbd8102006-03-29 00:11:43 +00001536void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001537 SDOperand InVec = getValue(I.getOperand(0));
1538 SDOperand InVal = getValue(I.getOperand(1));
1539 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1540 getValue(I.getOperand(2)));
1541
Chris Lattner2332b9f2006-03-19 01:17:20 +00001542 SDOperand Num = *(InVec.Val->op_end()-2);
1543 SDOperand Typ = *(InVec.Val->op_end()-1);
1544 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1545 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001546}
1547
Chris Lattner2bbd8102006-03-29 00:11:43 +00001548void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001549 SDOperand InVec = getValue(I.getOperand(0));
1550 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1551 getValue(I.getOperand(1)));
1552 SDOperand Typ = *(InVec.Val->op_end()-1);
1553 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1554 TLI.getValueType(I.getType()), InVec, InIdx));
1555}
Chris Lattnerc7029802006-03-18 01:44:44 +00001556
Chris Lattner3e104b12006-04-08 04:15:24 +00001557void SelectionDAGLowering::visitShuffleVector(User &I) {
1558 SDOperand V1 = getValue(I.getOperand(0));
1559 SDOperand V2 = getValue(I.getOperand(1));
1560 SDOperand Mask = getValue(I.getOperand(2));
1561
1562 SDOperand Num = *(V1.Val->op_end()-2);
1563 SDOperand Typ = *(V2.Val->op_end()-1);
1564 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1565 V1, V2, Mask, Num, Typ));
1566}
1567
1568
Chris Lattner1c08c712005-01-07 07:47:53 +00001569void SelectionDAGLowering::visitGetElementPtr(User &I) {
1570 SDOperand N = getValue(I.getOperand(0));
1571 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001572
1573 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1574 OI != E; ++OI) {
1575 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001576 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001577 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001578 if (Field) {
1579 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001580 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001581 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001582 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001583 }
1584 Ty = StTy->getElementType(Field);
1585 } else {
1586 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001587
Chris Lattner7c0104b2005-11-09 04:45:33 +00001588 // If this is a constant subscript, handle it quickly.
1589 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001590 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001591 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001592 if (CI->getType()->isSigned())
1593 Offs = (int64_t)
1594 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001595 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001596 Offs =
1597 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001598 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1599 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001600 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001601
1602 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001603 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001604 SDOperand IdxN = getValue(Idx);
1605
1606 // If the index is smaller or larger than intptr_t, truncate or extend
1607 // it.
1608 if (IdxN.getValueType() < N.getValueType()) {
1609 if (Idx->getType()->isSigned())
1610 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1611 else
1612 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1613 } else if (IdxN.getValueType() > N.getValueType())
1614 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1615
1616 // If this is a multiply by a power of two, turn it into a shl
1617 // immediately. This is a very common case.
1618 if (isPowerOf2_64(ElementSize)) {
1619 unsigned Amt = Log2_64(ElementSize);
1620 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001621 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001622 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1623 continue;
1624 }
1625
1626 SDOperand Scale = getIntPtrConstant(ElementSize);
1627 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1628 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001629 }
1630 }
1631 setValue(&I, N);
1632}
1633
1634void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1635 // If this is a fixed sized alloca in the entry block of the function,
1636 // allocate it statically on the stack.
1637 if (FuncInfo.StaticAllocaMap.count(&I))
1638 return; // getValue will auto-populate this.
1639
1640 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001641 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1642 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001643 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001644
1645 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001646 MVT::ValueType IntPtr = TLI.getPointerTy();
1647 if (IntPtr < AllocSize.getValueType())
1648 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1649 else if (IntPtr > AllocSize.getValueType())
1650 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001651
Chris Lattner68cd65e2005-01-22 23:04:37 +00001652 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001653 getIntPtrConstant(TySize));
1654
1655 // Handle alignment. If the requested alignment is less than or equal to the
1656 // stack alignment, ignore it and round the size of the allocation up to the
1657 // stack alignment size. If the size is greater than the stack alignment, we
1658 // note this in the DYNAMIC_STACKALLOC node.
1659 unsigned StackAlign =
1660 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1661 if (Align <= StackAlign) {
1662 Align = 0;
1663 // Add SA-1 to the size.
1664 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1665 getIntPtrConstant(StackAlign-1));
1666 // Mask out the low bits for alignment purposes.
1667 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1668 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1669 }
1670
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001671 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001672 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1673 MVT::Other);
1674 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001675 DAG.setRoot(setValue(&I, DSA).getValue(1));
1676
1677 // Inform the Frame Information that we have just allocated a variable-sized
1678 // object.
1679 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1680}
1681
Chris Lattner1c08c712005-01-07 07:47:53 +00001682void SelectionDAGLowering::visitLoad(LoadInst &I) {
1683 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001684
Chris Lattnerd3948112005-01-17 22:19:26 +00001685 SDOperand Root;
1686 if (I.isVolatile())
1687 Root = getRoot();
1688 else {
1689 // Do not serialize non-volatile loads against each other.
1690 Root = DAG.getRoot();
1691 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001692
Evan Cheng466685d2006-10-09 20:57:25 +00001693 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001694 Root, I.isVolatile()));
1695}
1696
1697SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001698 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001699 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001700 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001701 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001702 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001703 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1704 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001705 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001706 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001707 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001708
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001709 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001710 DAG.setRoot(L.getValue(1));
1711 else
1712 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001713
1714 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001715}
1716
1717
1718void SelectionDAGLowering::visitStore(StoreInst &I) {
1719 Value *SrcV = I.getOperand(0);
1720 SDOperand Src = getValue(SrcV);
1721 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001722 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1723 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001724}
1725
Chris Lattner0eade312006-03-24 02:22:33 +00001726/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1727/// access memory and has no other side effects at all.
1728static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1729#define GET_NO_MEMORY_INTRINSICS
1730#include "llvm/Intrinsics.gen"
1731#undef GET_NO_MEMORY_INTRINSICS
1732 return false;
1733}
1734
Chris Lattnere58a7802006-04-02 03:41:14 +00001735// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1736// have any side-effects or if it only reads memory.
1737static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1738#define GET_SIDE_EFFECT_INFO
1739#include "llvm/Intrinsics.gen"
1740#undef GET_SIDE_EFFECT_INFO
1741 return false;
1742}
1743
Chris Lattner0eade312006-03-24 02:22:33 +00001744/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1745/// node.
1746void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1747 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001748 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001749 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001750
1751 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001752 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001753 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1754 if (OnlyLoad) {
1755 // We don't need to serialize loads against other loads.
1756 Ops.push_back(DAG.getRoot());
1757 } else {
1758 Ops.push_back(getRoot());
1759 }
1760 }
Chris Lattner0eade312006-03-24 02:22:33 +00001761
1762 // Add the intrinsic ID as an integer operand.
1763 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1764
1765 // Add all operands of the call to the operand list.
1766 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1767 SDOperand Op = getValue(I.getOperand(i));
1768
1769 // If this is a vector type, force it to the right packed type.
1770 if (Op.getValueType() == MVT::Vector) {
1771 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1772 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1773
1774 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1775 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1776 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1777 }
1778
1779 assert(TLI.isTypeLegal(Op.getValueType()) &&
1780 "Intrinsic uses a non-legal type?");
1781 Ops.push_back(Op);
1782 }
1783
1784 std::vector<MVT::ValueType> VTs;
1785 if (I.getType() != Type::VoidTy) {
1786 MVT::ValueType VT = TLI.getValueType(I.getType());
1787 if (VT == MVT::Vector) {
1788 const PackedType *DestTy = cast<PackedType>(I.getType());
1789 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1790
1791 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1792 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1793 }
1794
1795 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1796 VTs.push_back(VT);
1797 }
1798 if (HasChain)
1799 VTs.push_back(MVT::Other);
1800
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001801 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1802
Chris Lattner0eade312006-03-24 02:22:33 +00001803 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001804 SDOperand Result;
1805 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001806 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1807 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001808 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001809 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1810 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001811 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001812 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1813 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001814
Chris Lattnere58a7802006-04-02 03:41:14 +00001815 if (HasChain) {
1816 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1817 if (OnlyLoad)
1818 PendingLoads.push_back(Chain);
1819 else
1820 DAG.setRoot(Chain);
1821 }
Chris Lattner0eade312006-03-24 02:22:33 +00001822 if (I.getType() != Type::VoidTy) {
1823 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1824 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1825 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1826 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1827 DAG.getValueType(EVT));
1828 }
1829 setValue(&I, Result);
1830 }
1831}
1832
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001833/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1834/// we want to emit this as a call to a named external function, return the name
1835/// otherwise lower it and return null.
1836const char *
1837SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1838 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001839 default:
1840 // By default, turn this into a target intrinsic node.
1841 visitTargetIntrinsic(I, Intrinsic);
1842 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001843 case Intrinsic::vastart: visitVAStart(I); return 0;
1844 case Intrinsic::vaend: visitVAEnd(I); return 0;
1845 case Intrinsic::vacopy: visitVACopy(I); return 0;
1846 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1847 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1848 case Intrinsic::setjmp:
1849 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1850 break;
1851 case Intrinsic::longjmp:
1852 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1853 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001854 case Intrinsic::memcpy_i32:
1855 case Intrinsic::memcpy_i64:
1856 visitMemIntrinsic(I, ISD::MEMCPY);
1857 return 0;
1858 case Intrinsic::memset_i32:
1859 case Intrinsic::memset_i64:
1860 visitMemIntrinsic(I, ISD::MEMSET);
1861 return 0;
1862 case Intrinsic::memmove_i32:
1863 case Intrinsic::memmove_i64:
1864 visitMemIntrinsic(I, ISD::MEMMOVE);
1865 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001866
Chris Lattner86cb6432005-12-13 17:40:33 +00001867 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001868 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001869 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001870 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001871 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001872
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001873 Ops[0] = getRoot();
1874 Ops[1] = getValue(SPI.getLineValue());
1875 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001876
Jim Laskey43970fe2006-03-23 18:06:46 +00001877 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001878 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001879 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1880
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001881 Ops[3] = DAG.getString(CompileUnit->getFileName());
1882 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001883
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001884 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001885 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001886
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001887 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001888 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001889 case Intrinsic::dbg_region_start: {
1890 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1891 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001892 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001893 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001894 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1895 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001896 }
1897
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001898 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001899 }
1900 case Intrinsic::dbg_region_end: {
1901 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1902 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001903 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001904 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001905 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1906 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001907 }
1908
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001909 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001910 }
1911 case Intrinsic::dbg_func_start: {
1912 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1913 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001914 if (DebugInfo && FSI.getSubprogram() &&
1915 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001916 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001917 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1918 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001919 }
1920
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001921 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001922 }
1923 case Intrinsic::dbg_declare: {
1924 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1925 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00001926 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00001927 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001928 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00001929 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00001930 }
1931
1932 return 0;
1933 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001934
Reid Spencer0b118202006-01-16 21:12:35 +00001935 case Intrinsic::isunordered_f32:
1936 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001937 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1938 getValue(I.getOperand(2)), ISD::SETUO));
1939 return 0;
1940
Reid Spencer0b118202006-01-16 21:12:35 +00001941 case Intrinsic::sqrt_f32:
1942 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001943 setValue(&I, DAG.getNode(ISD::FSQRT,
1944 getValue(I.getOperand(1)).getValueType(),
1945 getValue(I.getOperand(1))));
1946 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00001947 case Intrinsic::powi_f32:
1948 case Intrinsic::powi_f64:
1949 setValue(&I, DAG.getNode(ISD::FPOWI,
1950 getValue(I.getOperand(1)).getValueType(),
1951 getValue(I.getOperand(1)),
1952 getValue(I.getOperand(2))));
1953 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001954 case Intrinsic::pcmarker: {
1955 SDOperand Tmp = getValue(I.getOperand(1));
1956 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1957 return 0;
1958 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001959 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001960 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001961 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1962 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1963 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001964 setValue(&I, Tmp);
1965 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001966 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001967 }
Nate Begemand88fc032006-01-14 03:14:10 +00001968 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001969 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001970 case Intrinsic::bswap_i64:
1971 setValue(&I, DAG.getNode(ISD::BSWAP,
1972 getValue(I.getOperand(1)).getValueType(),
1973 getValue(I.getOperand(1))));
1974 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001975 case Intrinsic::cttz_i8:
1976 case Intrinsic::cttz_i16:
1977 case Intrinsic::cttz_i32:
1978 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001979 setValue(&I, DAG.getNode(ISD::CTTZ,
1980 getValue(I.getOperand(1)).getValueType(),
1981 getValue(I.getOperand(1))));
1982 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001983 case Intrinsic::ctlz_i8:
1984 case Intrinsic::ctlz_i16:
1985 case Intrinsic::ctlz_i32:
1986 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001987 setValue(&I, DAG.getNode(ISD::CTLZ,
1988 getValue(I.getOperand(1)).getValueType(),
1989 getValue(I.getOperand(1))));
1990 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001991 case Intrinsic::ctpop_i8:
1992 case Intrinsic::ctpop_i16:
1993 case Intrinsic::ctpop_i32:
1994 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001995 setValue(&I, DAG.getNode(ISD::CTPOP,
1996 getValue(I.getOperand(1)).getValueType(),
1997 getValue(I.getOperand(1))));
1998 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001999 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002000 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002001 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2002 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002003 setValue(&I, Tmp);
2004 DAG.setRoot(Tmp.getValue(1));
2005 return 0;
2006 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002007 case Intrinsic::stackrestore: {
2008 SDOperand Tmp = getValue(I.getOperand(1));
2009 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002010 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002011 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002012 case Intrinsic::prefetch:
2013 // FIXME: Currently discarding prefetches.
2014 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002015 }
2016}
2017
2018
Chris Lattner1c08c712005-01-07 07:47:53 +00002019void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002020 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002021 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002022 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002023 if (unsigned IID = F->getIntrinsicID()) {
2024 RenameFn = visitIntrinsicCall(I, IID);
2025 if (!RenameFn)
2026 return;
2027 } else { // Not an LLVM intrinsic.
2028 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002029 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2030 if (I.getNumOperands() == 3 && // Basic sanity checks.
2031 I.getOperand(1)->getType()->isFloatingPoint() &&
2032 I.getType() == I.getOperand(1)->getType() &&
2033 I.getType() == I.getOperand(2)->getType()) {
2034 SDOperand LHS = getValue(I.getOperand(1));
2035 SDOperand RHS = getValue(I.getOperand(2));
2036 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2037 LHS, RHS));
2038 return;
2039 }
2040 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002041 if (I.getNumOperands() == 2 && // Basic sanity checks.
2042 I.getOperand(1)->getType()->isFloatingPoint() &&
2043 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002044 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002045 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2046 return;
2047 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002048 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002049 if (I.getNumOperands() == 2 && // Basic sanity checks.
2050 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002051 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002052 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002053 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2054 return;
2055 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002056 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002057 if (I.getNumOperands() == 2 && // Basic sanity checks.
2058 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002059 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002060 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002061 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2062 return;
2063 }
2064 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002065 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002066 } else if (isa<InlineAsm>(I.getOperand(0))) {
2067 visitInlineAsm(I);
2068 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002069 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002070
Chris Lattner64e14b12005-01-08 22:48:57 +00002071 SDOperand Callee;
2072 if (!RenameFn)
2073 Callee = getValue(I.getOperand(0));
2074 else
2075 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00002076 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002077 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002078 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2079 Value *Arg = I.getOperand(i);
2080 SDOperand ArgNode = getValue(Arg);
2081 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2082 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002083
Nate Begeman8e21e712005-03-26 01:29:23 +00002084 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2085 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00002086
Chris Lattnercf5734d2005-01-08 19:26:18 +00002087 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00002088 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00002089 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002090 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002091 setValue(&I, Result.first);
2092 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002093}
2094
Chris Lattner864635a2006-02-22 22:37:12 +00002095SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002096 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002097 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2098 Chain = Val.getValue(1);
2099 Flag = Val.getValue(2);
2100
2101 // If the result was expanded, copy from the top part.
2102 if (Regs.size() > 1) {
2103 assert(Regs.size() == 2 &&
2104 "Cannot expand to more than 2 elts yet!");
2105 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002106 Chain = Hi.getValue(1);
2107 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002108 if (DAG.getTargetLoweringInfo().isLittleEndian())
2109 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2110 else
2111 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002112 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002113
Chris Lattnercf752aa2006-06-08 18:22:48 +00002114 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002115 // appropriate type.
2116 if (RegVT == ValueVT)
2117 return Val;
2118
Chris Lattnercf752aa2006-06-08 18:22:48 +00002119 if (MVT::isInteger(RegVT)) {
2120 if (ValueVT < RegVT)
2121 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2122 else
2123 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2124 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002125 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002126 }
Chris Lattner864635a2006-02-22 22:37:12 +00002127}
2128
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002129/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2130/// specified value into the registers specified by this object. This uses
2131/// Chain/Flag as the input and updates them for the output Chain/Flag.
2132void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002133 SDOperand &Chain, SDOperand &Flag,
2134 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002135 if (Regs.size() == 1) {
2136 // If there is a single register and the types differ, this must be
2137 // a promotion.
2138 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002139 if (MVT::isInteger(RegVT)) {
2140 if (RegVT < ValueVT)
2141 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2142 else
2143 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2144 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002145 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2146 }
2147 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2148 Flag = Chain.getValue(1);
2149 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002150 std::vector<unsigned> R(Regs);
2151 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2152 std::reverse(R.begin(), R.end());
2153
2154 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002155 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002156 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002157 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002158 Flag = Chain.getValue(1);
2159 }
2160 }
2161}
Chris Lattner864635a2006-02-22 22:37:12 +00002162
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002163/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2164/// operand list. This adds the code marker and includes the number of
2165/// values added into it.
2166void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002167 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002168 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2169 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2170 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2171}
Chris Lattner864635a2006-02-22 22:37:12 +00002172
2173/// isAllocatableRegister - If the specified register is safe to allocate,
2174/// i.e. it isn't a stack pointer or some other special register, return the
2175/// register class for the register. Otherwise, return null.
2176static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002177isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2178 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002179 MVT::ValueType FoundVT = MVT::Other;
2180 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002181 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2182 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002183 MVT::ValueType ThisVT = MVT::Other;
2184
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002185 const TargetRegisterClass *RC = *RCI;
2186 // If none of the the value types for this register class are valid, we
2187 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002188 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2189 I != E; ++I) {
2190 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002191 // If we have already found this register in a different register class,
2192 // choose the one with the largest VT specified. For example, on
2193 // PowerPC, we favor f64 register classes over f32.
2194 if (FoundVT == MVT::Other ||
2195 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2196 ThisVT = *I;
2197 break;
2198 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002199 }
2200 }
2201
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002202 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002203
Chris Lattner864635a2006-02-22 22:37:12 +00002204 // NOTE: This isn't ideal. In particular, this might allocate the
2205 // frame pointer in functions that need it (due to them not being taken
2206 // out of allocation, because a variable sized allocation hasn't been seen
2207 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002208 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2209 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002210 if (*I == Reg) {
2211 // We found a matching register class. Keep looking at others in case
2212 // we find one with larger registers that this physreg is also in.
2213 FoundRC = RC;
2214 FoundVT = ThisVT;
2215 break;
2216 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002217 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002218 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002219}
2220
2221RegsForValue SelectionDAGLowering::
2222GetRegistersForValue(const std::string &ConstrCode,
2223 MVT::ValueType VT, bool isOutReg, bool isInReg,
2224 std::set<unsigned> &OutputRegs,
2225 std::set<unsigned> &InputRegs) {
2226 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2227 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2228 std::vector<unsigned> Regs;
2229
2230 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2231 MVT::ValueType RegVT;
2232 MVT::ValueType ValueVT = VT;
2233
Chris Lattner2a821602006-11-02 01:41:49 +00002234 // If this is a constraint for a specific physical register, like {r17},
2235 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002236 if (PhysReg.first) {
2237 if (VT == MVT::Other)
2238 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002239
2240 // Get the actual register value type. This is important, because the user
2241 // may have asked for (e.g.) the AX register in i32 type. We need to
2242 // remember that AX is actually i16 to get the right extension.
2243 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002244
2245 // This is a explicit reference to a physical register.
2246 Regs.push_back(PhysReg.first);
2247
2248 // If this is an expanded reference, add the rest of the regs to Regs.
2249 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002250 TargetRegisterClass::iterator I = PhysReg.second->begin();
2251 TargetRegisterClass::iterator E = PhysReg.second->end();
2252 for (; *I != PhysReg.first; ++I)
2253 assert(I != E && "Didn't find reg!");
2254
2255 // Already added the first reg.
2256 --NumRegs; ++I;
2257 for (; NumRegs; --NumRegs, ++I) {
2258 assert(I != E && "Ran out of registers to allocate!");
2259 Regs.push_back(*I);
2260 }
2261 }
2262 return RegsForValue(Regs, RegVT, ValueVT);
2263 }
2264
Chris Lattner2a821602006-11-02 01:41:49 +00002265 // Otherwise, if this was a reference to an LLVM register class, create vregs
2266 // for this reference.
2267 std::vector<unsigned> RegClassRegs;
2268 if (PhysReg.second) {
2269 // If this is an early clobber or tied register, our regalloc doesn't know
2270 // how to maintain the constraint. If it isn't, go ahead and create vreg
2271 // and let the regalloc do the right thing.
2272 if (!isOutReg || !isInReg) {
2273 if (VT == MVT::Other)
2274 ValueVT = *PhysReg.second->vt_begin();
2275 RegVT = *PhysReg.second->vt_begin();
2276
2277 // Create the appropriate number of virtual registers.
2278 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2279 for (; NumRegs; --NumRegs)
2280 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2281
2282 return RegsForValue(Regs, RegVT, ValueVT);
2283 }
2284
2285 // Otherwise, we can't allocate it. Let the code below figure out how to
2286 // maintain these constraints.
2287 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2288
2289 } else {
2290 // This is a reference to a register class that doesn't directly correspond
2291 // to an LLVM register class. Allocate NumRegs consecutive, available,
2292 // registers from the class.
2293 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2294 }
Chris Lattner864635a2006-02-22 22:37:12 +00002295
2296 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2297 MachineFunction &MF = *CurMBB->getParent();
2298 unsigned NumAllocated = 0;
2299 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2300 unsigned Reg = RegClassRegs[i];
2301 // See if this register is available.
2302 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2303 (isInReg && InputRegs.count(Reg))) { // Already used.
2304 // Make sure we find consecutive registers.
2305 NumAllocated = 0;
2306 continue;
2307 }
2308
2309 // Check to see if this register is allocatable (i.e. don't give out the
2310 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002311 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002312 if (!RC) {
2313 // Make sure we find consecutive registers.
2314 NumAllocated = 0;
2315 continue;
2316 }
2317
2318 // Okay, this register is good, we can use it.
2319 ++NumAllocated;
2320
2321 // If we allocated enough consecutive
2322 if (NumAllocated == NumRegs) {
2323 unsigned RegStart = (i-NumAllocated)+1;
2324 unsigned RegEnd = i+1;
2325 // Mark all of the allocated registers used.
2326 for (unsigned i = RegStart; i != RegEnd; ++i) {
2327 unsigned Reg = RegClassRegs[i];
2328 Regs.push_back(Reg);
2329 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2330 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2331 }
2332
2333 return RegsForValue(Regs, *RC->vt_begin(), VT);
2334 }
2335 }
2336
2337 // Otherwise, we couldn't allocate enough registers for this.
2338 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002339}
2340
Chris Lattner864635a2006-02-22 22:37:12 +00002341
Chris Lattnerce7518c2006-01-26 22:24:51 +00002342/// visitInlineAsm - Handle a call to an InlineAsm object.
2343///
2344void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2345 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2346
2347 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2348 MVT::Other);
2349
2350 // Note, we treat inline asms both with and without side-effects as the same.
2351 // If an inline asm doesn't have side effects and doesn't access memory, we
2352 // could not choose to not chain it.
2353 bool hasSideEffects = IA->hasSideEffects();
2354
Chris Lattner2cc2f662006-02-01 01:28:23 +00002355 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002356 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002357
2358 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2359 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2360 /// if it is a def of that register.
2361 std::vector<SDOperand> AsmNodeOperands;
2362 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2363 AsmNodeOperands.push_back(AsmStr);
2364
2365 SDOperand Chain = getRoot();
2366 SDOperand Flag;
2367
Chris Lattner4e4b5762006-02-01 18:59:47 +00002368 // We fully assign registers here at isel time. This is not optimal, but
2369 // should work. For register classes that correspond to LLVM classes, we
2370 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2371 // over the constraints, collecting fixed registers that we know we can't use.
2372 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002373 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002374 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2375 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2376 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002377
Chris Lattner1efa40f2006-02-22 00:56:39 +00002378 MVT::ValueType OpVT;
2379
2380 // Compute the value type for each operand and add it to ConstraintVTs.
2381 switch (Constraints[i].Type) {
2382 case InlineAsm::isOutput:
2383 if (!Constraints[i].isIndirectOutput) {
2384 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2385 OpVT = TLI.getValueType(I.getType());
2386 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002387 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002388 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2389 OpNum++; // Consumes a call operand.
2390 }
2391 break;
2392 case InlineAsm::isInput:
2393 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2394 OpNum++; // Consumes a call operand.
2395 break;
2396 case InlineAsm::isClobber:
2397 OpVT = MVT::Other;
2398 break;
2399 }
2400
2401 ConstraintVTs.push_back(OpVT);
2402
Chris Lattner864635a2006-02-22 22:37:12 +00002403 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2404 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002405
Chris Lattner864635a2006-02-22 22:37:12 +00002406 // Build a list of regs that this operand uses. This always has a single
2407 // element for promoted/expanded operands.
2408 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2409 false, false,
2410 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002411
2412 switch (Constraints[i].Type) {
2413 case InlineAsm::isOutput:
2414 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002415 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002416 // If this is an early-clobber output, it cannot be assigned to the same
2417 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002418 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002419 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002420 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002421 case InlineAsm::isInput:
2422 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002423 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002424 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002425 case InlineAsm::isClobber:
2426 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002427 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2428 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002429 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002430 }
2431 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002432
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002433 // Loop over all of the inputs, copying the operand values into the
2434 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002435 RegsForValue RetValRegs;
2436 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002437 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002438
Chris Lattner6656dd12006-01-31 02:03:41 +00002439 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002440 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2441 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002442
Chris Lattner2cc2f662006-02-01 01:28:23 +00002443 switch (Constraints[i].Type) {
2444 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002445 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2446 if (ConstraintCode.size() == 1) // not a physreg name.
2447 CTy = TLI.getConstraintType(ConstraintCode[0]);
2448
2449 if (CTy == TargetLowering::C_Memory) {
2450 // Memory output.
2451 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2452
2453 // Check that the operand (the address to store to) isn't a float.
2454 if (!MVT::isInteger(InOperandVal.getValueType()))
2455 assert(0 && "MATCH FAIL!");
2456
2457 if (!Constraints[i].isIndirectOutput)
2458 assert(0 && "MATCH FAIL!");
2459
2460 OpNum++; // Consumes a call operand.
2461
2462 // Extend/truncate to the right pointer type if needed.
2463 MVT::ValueType PtrType = TLI.getPointerTy();
2464 if (InOperandVal.getValueType() < PtrType)
2465 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2466 else if (InOperandVal.getValueType() > PtrType)
2467 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2468
2469 // Add information to the INLINEASM node to know about this output.
2470 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2471 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2472 AsmNodeOperands.push_back(InOperandVal);
2473 break;
2474 }
2475
2476 // Otherwise, this is a register output.
2477 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2478
Chris Lattner864635a2006-02-22 22:37:12 +00002479 // If this is an early-clobber output, or if there is an input
2480 // constraint that matches this, we need to reserve the input register
2481 // so no other inputs allocate to it.
2482 bool UsesInputRegister = false;
2483 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2484 UsesInputRegister = true;
2485
2486 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002487 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002488 RegsForValue Regs =
2489 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2490 true, UsesInputRegister,
2491 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002492 if (Regs.Regs.empty()) {
2493 std::cerr << "Couldn't allocate output reg for contraint '"
2494 << ConstraintCode << "'!\n";
2495 exit(1);
2496 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002497
Chris Lattner2cc2f662006-02-01 01:28:23 +00002498 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002499 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002500 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002501 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002502 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002503 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002504 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2505 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002506 OpNum++; // Consumes a call operand.
2507 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002508
2509 // Add information to the INLINEASM node to know that this register is
2510 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002511 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002512 break;
2513 }
2514 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002515 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002516 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002517
Chris Lattner2223aea2006-02-02 00:25:23 +00002518 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2519 // If this is required to match an output register we have already set,
2520 // just use its register.
2521 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002522
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002523 // Scan until we find the definition we already emitted of this operand.
2524 // When we find it, create a RegsForValue operand.
2525 unsigned CurOp = 2; // The first operand.
2526 for (; OperandNo; --OperandNo) {
2527 // Advance to the next operand.
2528 unsigned NumOps =
2529 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002530 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2531 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002532 "Skipped past definitions?");
2533 CurOp += (NumOps>>3)+1;
2534 }
2535
2536 unsigned NumOps =
2537 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2538 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2539 "Skipped past definitions?");
2540
2541 // Add NumOps>>3 registers to MatchedRegs.
2542 RegsForValue MatchedRegs;
2543 MatchedRegs.ValueVT = InOperandVal.getValueType();
2544 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2545 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2546 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2547 MatchedRegs.Regs.push_back(Reg);
2548 }
2549
2550 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002551 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2552 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002553 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002554 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002555 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002556
2557 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2558 if (ConstraintCode.size() == 1) // not a physreg name.
2559 CTy = TLI.getConstraintType(ConstraintCode[0]);
2560
2561 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002562 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2563 ConstraintCode[0], DAG);
2564 if (!InOperandVal.Val) {
2565 std::cerr << "Invalid operand for inline asm constraint '"
2566 << ConstraintCode << "'!\n";
2567 exit(1);
2568 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002569
2570 // Add information to the INLINEASM node to know about this input.
2571 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2572 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2573 AsmNodeOperands.push_back(InOperandVal);
2574 break;
2575 } else if (CTy == TargetLowering::C_Memory) {
2576 // Memory input.
2577
2578 // Check that the operand isn't a float.
2579 if (!MVT::isInteger(InOperandVal.getValueType()))
2580 assert(0 && "MATCH FAIL!");
2581
2582 // Extend/truncate to the right pointer type if needed.
2583 MVT::ValueType PtrType = TLI.getPointerTy();
2584 if (InOperandVal.getValueType() < PtrType)
2585 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2586 else if (InOperandVal.getValueType() > PtrType)
2587 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2588
2589 // Add information to the INLINEASM node to know about this input.
2590 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2591 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2592 AsmNodeOperands.push_back(InOperandVal);
2593 break;
2594 }
2595
2596 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2597
2598 // Copy the input into the appropriate registers.
2599 RegsForValue InRegs =
2600 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2601 false, true, OutputRegs, InputRegs);
2602 // FIXME: should be match fail.
2603 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2604
Evan Chenga8441262006-06-15 08:11:54 +00002605 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002606
2607 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002608 break;
2609 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002610 case InlineAsm::isClobber: {
2611 RegsForValue ClobberedRegs =
2612 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2613 OutputRegs, InputRegs);
2614 // Add the clobbered value to the operand list, so that the register
2615 // allocator is aware that the physreg got clobbered.
2616 if (!ClobberedRegs.Regs.empty())
2617 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002618 break;
2619 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002620 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002621 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002622
2623 // Finish up input operands.
2624 AsmNodeOperands[0] = Chain;
2625 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2626
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002627 Chain = DAG.getNode(ISD::INLINEASM,
2628 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002629 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002630 Flag = Chain.getValue(1);
2631
Chris Lattner6656dd12006-01-31 02:03:41 +00002632 // If this asm returns a register value, copy the result from that register
2633 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002634 if (!RetValRegs.Regs.empty())
2635 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002636
Chris Lattner6656dd12006-01-31 02:03:41 +00002637 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2638
2639 // Process indirect outputs, first output all of the flagged copies out of
2640 // physregs.
2641 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002642 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002643 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002644 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2645 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002646 }
2647
2648 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002649 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002650 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002651 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002652 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002653 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002654 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002655 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2656 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002657 DAG.setRoot(Chain);
2658}
2659
2660
Chris Lattner1c08c712005-01-07 07:47:53 +00002661void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2662 SDOperand Src = getValue(I.getOperand(0));
2663
2664 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002665
2666 if (IntPtr < Src.getValueType())
2667 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2668 else if (IntPtr > Src.getValueType())
2669 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002670
2671 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002672 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002673 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2674 Src, getIntPtrConstant(ElementSize));
2675
2676 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002677 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002678
2679 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002680 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002681 DAG.getExternalSymbol("malloc", IntPtr),
2682 Args, DAG);
2683 setValue(&I, Result.first); // Pointers always fit in registers
2684 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002685}
2686
2687void SelectionDAGLowering::visitFree(FreeInst &I) {
2688 std::vector<std::pair<SDOperand, const Type*> > Args;
2689 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002690 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002691 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002692 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002693 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002694 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2695 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002696}
2697
Chris Lattner025c39b2005-08-26 20:54:47 +00002698// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2699// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2700// instructions are special in various ways, which require special support to
2701// insert. The specified MachineInstr is created but not inserted into any
2702// basic blocks, and the scheduler passes ownership of it to this method.
2703MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2704 MachineBasicBlock *MBB) {
2705 std::cerr << "If a target marks an instruction with "
2706 "'usesCustomDAGSchedInserter', it must implement "
2707 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2708 abort();
2709 return 0;
2710}
2711
Chris Lattner39ae3622005-01-09 00:00:49 +00002712void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002713 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2714 getValue(I.getOperand(1)),
2715 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002716}
2717
2718void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002719 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2720 getValue(I.getOperand(0)),
2721 DAG.getSrcValue(I.getOperand(0)));
2722 setValue(&I, V);
2723 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002724}
2725
2726void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002727 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2728 getValue(I.getOperand(1)),
2729 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002730}
2731
2732void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002733 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2734 getValue(I.getOperand(1)),
2735 getValue(I.getOperand(2)),
2736 DAG.getSrcValue(I.getOperand(1)),
2737 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002738}
2739
Chris Lattnerfdfded52006-04-12 16:20:43 +00002740/// TargetLowering::LowerArguments - This is the default LowerArguments
2741/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002742/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2743/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002744std::vector<SDOperand>
2745TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2746 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2747 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002748 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002749 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2750 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2751
2752 // Add one result value for each formal argument.
2753 std::vector<MVT::ValueType> RetVals;
2754 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2755 MVT::ValueType VT = getValueType(I->getType());
2756
2757 switch (getTypeAction(VT)) {
2758 default: assert(0 && "Unknown type action!");
2759 case Legal:
2760 RetVals.push_back(VT);
2761 break;
2762 case Promote:
2763 RetVals.push_back(getTypeToTransformTo(VT));
2764 break;
2765 case Expand:
2766 if (VT != MVT::Vector) {
2767 // If this is a large integer, it needs to be broken up into small
2768 // integers. Figure out what the destination type is and how many small
2769 // integers it turns into.
2770 MVT::ValueType NVT = getTypeToTransformTo(VT);
2771 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2772 for (unsigned i = 0; i != NumVals; ++i)
2773 RetVals.push_back(NVT);
2774 } else {
2775 // Otherwise, this is a vector type. We only support legal vectors
2776 // right now.
2777 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2778 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002779
Chris Lattnerfdfded52006-04-12 16:20:43 +00002780 // Figure out if there is a Packed type corresponding to this Vector
2781 // type. If so, convert to the packed type.
2782 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2783 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2784 RetVals.push_back(TVT);
2785 } else {
2786 assert(0 && "Don't support illegal by-val vector arguments yet!");
2787 }
2788 }
2789 break;
2790 }
2791 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002792
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002793 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002794
2795 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002796 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2797 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002798 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002799
2800 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002801
2802 // Set up the return result vector.
2803 Ops.clear();
2804 unsigned i = 0;
2805 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2806 MVT::ValueType VT = getValueType(I->getType());
2807
2808 switch (getTypeAction(VT)) {
2809 default: assert(0 && "Unknown type action!");
2810 case Legal:
2811 Ops.push_back(SDOperand(Result, i++));
2812 break;
2813 case Promote: {
2814 SDOperand Op(Result, i++);
2815 if (MVT::isInteger(VT)) {
2816 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2817 : ISD::AssertZext;
2818 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2819 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2820 } else {
2821 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2822 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2823 }
2824 Ops.push_back(Op);
2825 break;
2826 }
2827 case Expand:
2828 if (VT != MVT::Vector) {
2829 // If this is a large integer, it needs to be reassembled from small
2830 // integers. Figure out what the source elt type is and how many small
2831 // integers it is.
2832 MVT::ValueType NVT = getTypeToTransformTo(VT);
2833 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2834 if (NumVals == 2) {
2835 SDOperand Lo = SDOperand(Result, i++);
2836 SDOperand Hi = SDOperand(Result, i++);
2837
2838 if (!isLittleEndian())
2839 std::swap(Lo, Hi);
2840
2841 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2842 } else {
2843 // Value scalarized into many values. Unimp for now.
2844 assert(0 && "Cannot expand i64 -> i16 yet!");
2845 }
2846 } else {
2847 // Otherwise, this is a vector type. We only support legal vectors
2848 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002849 const PackedType *PTy = cast<PackedType>(I->getType());
2850 unsigned NumElems = PTy->getNumElements();
2851 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002852
Chris Lattnerfdfded52006-04-12 16:20:43 +00002853 // Figure out if there is a Packed type corresponding to this Vector
2854 // type. If so, convert to the packed type.
2855 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002856 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002857 SDOperand N = SDOperand(Result, i++);
2858 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002859 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2860 DAG.getConstant(NumElems, MVT::i32),
2861 DAG.getValueType(getValueType(EltTy)));
2862 Ops.push_back(N);
2863 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002864 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002865 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002866 }
2867 }
2868 break;
2869 }
2870 }
2871 return Ops;
2872}
2873
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002874
2875/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2876/// implementation, which just inserts an ISD::CALL node, which is later custom
2877/// lowered by the target to something concrete. FIXME: When all targets are
2878/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2879std::pair<SDOperand, SDOperand>
2880TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2881 unsigned CallingConv, bool isTailCall,
2882 SDOperand Callee,
2883 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00002884 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002885 Ops.push_back(Chain); // Op#0 - Chain
2886 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2887 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2888 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2889 Ops.push_back(Callee);
2890
2891 // Handle all of the outgoing arguments.
2892 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2893 MVT::ValueType VT = getValueType(Args[i].second);
2894 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00002895 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002896 switch (getTypeAction(VT)) {
2897 default: assert(0 && "Unknown type action!");
2898 case Legal:
2899 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002900 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002901 break;
2902 case Promote:
2903 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00002904 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002905 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2906 } else {
2907 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2908 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2909 }
2910 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002911 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002912 break;
2913 case Expand:
2914 if (VT != MVT::Vector) {
2915 // If this is a large integer, it needs to be broken down into small
2916 // integers. Figure out what the source elt type is and how many small
2917 // integers it is.
2918 MVT::ValueType NVT = getTypeToTransformTo(VT);
2919 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2920 if (NumVals == 2) {
2921 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2922 DAG.getConstant(0, getPointerTy()));
2923 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2924 DAG.getConstant(1, getPointerTy()));
2925 if (!isLittleEndian())
2926 std::swap(Lo, Hi);
2927
2928 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00002929 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002930 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00002931 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002932 } else {
2933 // Value scalarized into many values. Unimp for now.
2934 assert(0 && "Cannot expand i64 -> i16 yet!");
2935 }
2936 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002937 // Otherwise, this is a vector type. We only support legal vectors
2938 // right now.
2939 const PackedType *PTy = cast<PackedType>(Args[i].second);
2940 unsigned NumElems = PTy->getNumElements();
2941 const Type *EltTy = PTy->getElementType();
2942
2943 // Figure out if there is a Packed type corresponding to this Vector
2944 // type. If so, convert to the packed type.
2945 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00002946 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2947 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2948 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2949 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002950 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00002951 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002952 assert(0 && "Don't support illegal by-val vector call args yet!");
2953 abort();
2954 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002955 }
2956 break;
2957 }
2958 }
2959
2960 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00002961 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002962
2963 if (RetTy != Type::VoidTy) {
2964 MVT::ValueType VT = getValueType(RetTy);
2965 switch (getTypeAction(VT)) {
2966 default: assert(0 && "Unknown type action!");
2967 case Legal:
2968 RetTys.push_back(VT);
2969 break;
2970 case Promote:
2971 RetTys.push_back(getTypeToTransformTo(VT));
2972 break;
2973 case Expand:
2974 if (VT != MVT::Vector) {
2975 // If this is a large integer, it needs to be reassembled from small
2976 // integers. Figure out what the source elt type is and how many small
2977 // integers it is.
2978 MVT::ValueType NVT = getTypeToTransformTo(VT);
2979 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2980 for (unsigned i = 0; i != NumVals; ++i)
2981 RetTys.push_back(NVT);
2982 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002983 // Otherwise, this is a vector type. We only support legal vectors
2984 // right now.
2985 const PackedType *PTy = cast<PackedType>(RetTy);
2986 unsigned NumElems = PTy->getNumElements();
2987 const Type *EltTy = PTy->getElementType();
2988
2989 // Figure out if there is a Packed type corresponding to this Vector
2990 // type. If so, convert to the packed type.
2991 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2992 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2993 RetTys.push_back(TVT);
2994 } else {
2995 assert(0 && "Don't support illegal by-val vector call results yet!");
2996 abort();
2997 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002998 }
2999 }
3000 }
3001
3002 RetTys.push_back(MVT::Other); // Always has a chain.
3003
3004 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003005 SDOperand Res = DAG.getNode(ISD::CALL,
3006 DAG.getVTList(&RetTys[0], RetTys.size()),
3007 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003008
3009 // This returns a pair of operands. The first element is the
3010 // return value for the function (if RetTy is not VoidTy). The second
3011 // element is the outgoing token chain.
3012 SDOperand ResVal;
3013 if (RetTys.size() != 1) {
3014 MVT::ValueType VT = getValueType(RetTy);
3015 if (RetTys.size() == 2) {
3016 ResVal = Res;
3017
3018 // If this value was promoted, truncate it down.
3019 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003020 if (VT == MVT::Vector) {
3021 // Insert a VBITCONVERT to convert from the packed result type to the
3022 // MVT::Vector type.
3023 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3024 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3025
3026 // Figure out if there is a Packed type corresponding to this Vector
3027 // type. If so, convert to the packed type.
3028 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3029 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003030 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3031 // "N x PTyElementVT" MVT::Vector type.
3032 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003033 DAG.getConstant(NumElems, MVT::i32),
3034 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003035 } else {
3036 abort();
3037 }
3038 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003039 unsigned AssertOp = RetTy->isSigned() ?
3040 ISD::AssertSext : ISD::AssertZext;
3041 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3042 DAG.getValueType(VT));
3043 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3044 } else {
3045 assert(MVT::isFloatingPoint(VT));
3046 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3047 }
3048 }
3049 } else if (RetTys.size() == 3) {
3050 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3051 Res.getValue(0), Res.getValue(1));
3052
3053 } else {
3054 assert(0 && "Case not handled yet!");
3055 }
3056 }
3057
3058 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3059}
3060
3061
3062
Chris Lattner39ae3622005-01-09 00:00:49 +00003063// It is always conservatively correct for llvm.returnaddress and
3064// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003065//
3066// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3067// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00003068std::pair<SDOperand, SDOperand>
3069TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3070 unsigned Depth, SelectionDAG &DAG) {
3071 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00003072}
3073
Chris Lattner50381b62005-05-14 05:50:48 +00003074SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003075 assert(0 && "LowerOperation not implemented for this target!");
3076 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003077 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003078}
3079
Nate Begeman0aed7842006-01-28 03:14:31 +00003080SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3081 SelectionDAG &DAG) {
3082 assert(0 && "CustomPromoteOperation not implemented for this target!");
3083 abort();
3084 return SDOperand();
3085}
3086
Chris Lattner39ae3622005-01-09 00:00:49 +00003087void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003088 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003089 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003090 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003091 setValue(&I, Result.first);
3092 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003093}
3094
Evan Cheng74d0aa92006-02-15 21:59:04 +00003095/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003096/// operand.
3097static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003098 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003099 MVT::ValueType CurVT = VT;
3100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3101 uint64_t Val = C->getValue() & 255;
3102 unsigned Shift = 8;
3103 while (CurVT != MVT::i8) {
3104 Val = (Val << Shift) | Val;
3105 Shift <<= 1;
3106 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003107 }
3108 return DAG.getConstant(Val, VT);
3109 } else {
3110 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3111 unsigned Shift = 8;
3112 while (CurVT != MVT::i8) {
3113 Value =
3114 DAG.getNode(ISD::OR, VT,
3115 DAG.getNode(ISD::SHL, VT, Value,
3116 DAG.getConstant(Shift, MVT::i8)), Value);
3117 Shift <<= 1;
3118 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003119 }
3120
3121 return Value;
3122 }
3123}
3124
Evan Cheng74d0aa92006-02-15 21:59:04 +00003125/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3126/// used when a memcpy is turned into a memset when the source is a constant
3127/// string ptr.
3128static SDOperand getMemsetStringVal(MVT::ValueType VT,
3129 SelectionDAG &DAG, TargetLowering &TLI,
3130 std::string &Str, unsigned Offset) {
3131 MVT::ValueType CurVT = VT;
3132 uint64_t Val = 0;
3133 unsigned MSB = getSizeInBits(VT) / 8;
3134 if (TLI.isLittleEndian())
3135 Offset = Offset + MSB - 1;
3136 for (unsigned i = 0; i != MSB; ++i) {
3137 Val = (Val << 8) | Str[Offset];
3138 Offset += TLI.isLittleEndian() ? -1 : 1;
3139 }
3140 return DAG.getConstant(Val, VT);
3141}
3142
Evan Cheng1db92f92006-02-14 08:22:34 +00003143/// getMemBasePlusOffset - Returns base and offset node for the
3144static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3145 SelectionDAG &DAG, TargetLowering &TLI) {
3146 MVT::ValueType VT = Base.getValueType();
3147 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3148}
3149
Evan Chengc4f8eee2006-02-14 20:12:38 +00003150/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003151/// to replace the memset / memcpy is below the threshold. It also returns the
3152/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003153static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3154 unsigned Limit, uint64_t Size,
3155 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003156 MVT::ValueType VT;
3157
3158 if (TLI.allowsUnalignedMemoryAccesses()) {
3159 VT = MVT::i64;
3160 } else {
3161 switch (Align & 7) {
3162 case 0:
3163 VT = MVT::i64;
3164 break;
3165 case 4:
3166 VT = MVT::i32;
3167 break;
3168 case 2:
3169 VT = MVT::i16;
3170 break;
3171 default:
3172 VT = MVT::i8;
3173 break;
3174 }
3175 }
3176
Evan Cheng80e89d72006-02-14 09:11:59 +00003177 MVT::ValueType LVT = MVT::i64;
3178 while (!TLI.isTypeLegal(LVT))
3179 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3180 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003181
Evan Cheng80e89d72006-02-14 09:11:59 +00003182 if (VT > LVT)
3183 VT = LVT;
3184
Evan Chengdea72452006-02-14 23:05:54 +00003185 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003186 while (Size != 0) {
3187 unsigned VTSize = getSizeInBits(VT) / 8;
3188 while (VTSize > Size) {
3189 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003190 VTSize >>= 1;
3191 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003192 assert(MVT::isInteger(VT));
3193
3194 if (++NumMemOps > Limit)
3195 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003196 MemOps.push_back(VT);
3197 Size -= VTSize;
3198 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003199
3200 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003201}
3202
Chris Lattner7041ee32005-01-11 05:56:49 +00003203void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003204 SDOperand Op1 = getValue(I.getOperand(1));
3205 SDOperand Op2 = getValue(I.getOperand(2));
3206 SDOperand Op3 = getValue(I.getOperand(3));
3207 SDOperand Op4 = getValue(I.getOperand(4));
3208 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3209 if (Align == 0) Align = 1;
3210
3211 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3212 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003213
3214 // Expand memset / memcpy to a series of load / store ops
3215 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003216 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003217 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003218 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003219 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003220 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3221 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003222 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003223 unsigned Offset = 0;
3224 for (unsigned i = 0; i < NumMemOps; i++) {
3225 MVT::ValueType VT = MemOps[i];
3226 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003227 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003228 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003229 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003230 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003231 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003232 Offset += VTSize;
3233 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003234 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003235 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003236 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003237 case ISD::MEMCPY: {
3238 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3239 Size->getValue(), Align, TLI)) {
3240 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003241 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003242 GlobalAddressSDNode *G = NULL;
3243 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003244 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003245
3246 if (Op2.getOpcode() == ISD::GlobalAddress)
3247 G = cast<GlobalAddressSDNode>(Op2);
3248 else if (Op2.getOpcode() == ISD::ADD &&
3249 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3250 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3251 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003252 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003253 }
3254 if (G) {
3255 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00003256 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00003257 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003258 if (!Str.empty()) {
3259 CopyFromStr = true;
3260 SrcOff += SrcDelta;
3261 }
3262 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003263 }
3264
Evan Chengc080d6f2006-02-15 01:54:51 +00003265 for (unsigned i = 0; i < NumMemOps; i++) {
3266 MVT::ValueType VT = MemOps[i];
3267 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003268 SDOperand Value, Chain, Store;
3269
Evan Chengcffbb512006-02-16 23:11:42 +00003270 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003271 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3272 Chain = getRoot();
3273 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003274 DAG.getStore(Chain, Value,
3275 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003276 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003277 } else {
3278 Value = DAG.getLoad(VT, getRoot(),
3279 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003280 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003281 Chain = Value.getValue(1);
3282 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003283 DAG.getStore(Chain, Value,
3284 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003285 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003286 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003287 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003288 SrcOff += VTSize;
3289 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003290 }
3291 }
3292 break;
3293 }
3294 }
3295
3296 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003297 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3298 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003299 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003300 }
3301 }
3302
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003303 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003304}
3305
Chris Lattner7041ee32005-01-11 05:56:49 +00003306//===----------------------------------------------------------------------===//
3307// SelectionDAGISel code
3308//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003309
3310unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3311 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3312}
3313
Chris Lattner495a0b52005-08-17 06:37:43 +00003314void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003315 // FIXME: we only modify the CFG to split critical edges. This
3316 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003317 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003318}
Chris Lattner1c08c712005-01-07 07:47:53 +00003319
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003320
Chris Lattner90323642006-05-05 21:17:49 +00003321/// OptimizeNoopCopyExpression - We have determined that the specified cast
3322/// instruction is a noop copy (e.g. it's casting from one pointer type to
3323/// another, int->uint, or int->sbyte on PPC.
3324///
3325/// Return true if any changes are made.
3326static bool OptimizeNoopCopyExpression(CastInst *CI) {
3327 BasicBlock *DefBB = CI->getParent();
3328
3329 /// InsertedCasts - Only insert a cast in each block once.
3330 std::map<BasicBlock*, CastInst*> InsertedCasts;
3331
3332 bool MadeChange = false;
3333 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3334 UI != E; ) {
3335 Use &TheUse = UI.getUse();
3336 Instruction *User = cast<Instruction>(*UI);
3337
3338 // Figure out which BB this cast is used in. For PHI's this is the
3339 // appropriate predecessor block.
3340 BasicBlock *UserBB = User->getParent();
3341 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3342 unsigned OpVal = UI.getOperandNo()/2;
3343 UserBB = PN->getIncomingBlock(OpVal);
3344 }
3345
3346 // Preincrement use iterator so we don't invalidate it.
3347 ++UI;
3348
3349 // If this user is in the same block as the cast, don't change the cast.
3350 if (UserBB == DefBB) continue;
3351
3352 // If we have already inserted a cast into this block, use it.
3353 CastInst *&InsertedCast = InsertedCasts[UserBB];
3354
3355 if (!InsertedCast) {
3356 BasicBlock::iterator InsertPt = UserBB->begin();
3357 while (isa<PHINode>(InsertPt)) ++InsertPt;
3358
3359 InsertedCast =
3360 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3361 MadeChange = true;
3362 }
3363
3364 // Replace a use of the cast with a use of the new casat.
3365 TheUse = InsertedCast;
3366 }
3367
3368 // If we removed all uses, nuke the cast.
3369 if (CI->use_empty())
3370 CI->eraseFromParent();
3371
3372 return MadeChange;
3373}
3374
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003375/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3376/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003377static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3378 Instruction *GEPI, Value *Ptr,
3379 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003380 if (V) return V; // Already computed.
3381
3382 BasicBlock::iterator InsertPt;
3383 if (BB == GEPI->getParent()) {
3384 // If insert into the GEP's block, insert right after the GEP.
3385 InsertPt = GEPI;
3386 ++InsertPt;
3387 } else {
3388 // Otherwise, insert at the top of BB, after any PHI nodes
3389 InsertPt = BB->begin();
3390 while (isa<PHINode>(InsertPt)) ++InsertPt;
3391 }
3392
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003393 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3394 // BB so that there is only one value live across basic blocks (the cast
3395 // operand).
3396 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3397 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3398 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3399
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003400 // Add the offset, cast it to the right type.
3401 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003402 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003403}
3404
Chris Lattner90323642006-05-05 21:17:49 +00003405/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3406/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3407/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3408/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3409/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3410/// the constant add into a load or store instruction. Additionally, if a user
3411/// is a pointer-pointer cast, we look through it to find its users.
3412static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3413 Constant *PtrOffset, BasicBlock *DefBB,
3414 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003415 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003416 while (!RepPtr->use_empty()) {
3417 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003418
Chris Lattner90323642006-05-05 21:17:49 +00003419 // If the user is a Pointer-Pointer cast, recurse.
3420 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3421 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003422
Chris Lattner90323642006-05-05 21:17:49 +00003423 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3424 // could invalidate an iterator.
3425 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3426 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003427 }
3428
Chris Lattner90323642006-05-05 21:17:49 +00003429 // If this is a load of the pointer, or a store through the pointer, emit
3430 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003431 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003432 if (isa<LoadInst>(User) ||
3433 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3434 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3435 User->getParent(), GEPI,
3436 Ptr, PtrOffset);
3437 } else {
3438 // If this use is not foldable into the addressing mode, use a version
3439 // emitted in the GEP block.
3440 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3441 Ptr, PtrOffset);
3442 }
3443
Chris Lattnerf0df8822006-05-06 09:10:37 +00003444 if (GEPI->getType() != RepPtr->getType()) {
3445 BasicBlock::iterator IP = NewVal;
3446 ++IP;
3447 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3448 }
Chris Lattner90323642006-05-05 21:17:49 +00003449 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003450 }
3451}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003452
Chris Lattner90323642006-05-05 21:17:49 +00003453
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003454/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3455/// selection, we want to be a bit careful about some things. In particular, if
3456/// we have a GEP instruction that is used in a different block than it is
3457/// defined, the addressing expression of the GEP cannot be folded into loads or
3458/// stores that use it. In this case, decompose the GEP and move constant
3459/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003460static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003461 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003462 // If this GEP is only used inside the block it is defined in, there is no
3463 // need to rewrite it.
3464 bool isUsedOutsideDefBB = false;
3465 BasicBlock *DefBB = GEPI->getParent();
3466 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3467 UI != E; ++UI) {
3468 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3469 isUsedOutsideDefBB = true;
3470 break;
3471 }
3472 }
Chris Lattner90323642006-05-05 21:17:49 +00003473 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003474
3475 // If this GEP has no non-zero constant indices, there is nothing we can do,
3476 // ignore it.
3477 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003478 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003479 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3480 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003481 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003482 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003483 hasConstantIndex = true;
3484 break;
3485 }
Chris Lattner90323642006-05-05 21:17:49 +00003486 } else {
3487 hasVariableIndex = true;
3488 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003489 }
Chris Lattner90323642006-05-05 21:17:49 +00003490
3491 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3492 if (!hasConstantIndex && !hasVariableIndex) {
3493 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3494 GEPI->getName(), GEPI);
3495 GEPI->replaceAllUsesWith(NC);
3496 GEPI->eraseFromParent();
3497 return true;
3498 }
3499
Chris Lattner3802c252005-12-11 09:05:13 +00003500 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003501 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3502 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003503
3504 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3505 // constant offset (which we now know is non-zero) and deal with it later.
3506 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003507 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003508 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3509 const Type *Ty = GEPI->getOperand(0)->getType();
3510
3511 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3512 E = GEPI->op_end(); OI != E; ++OI) {
3513 Value *Idx = *OI;
3514 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003515 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003516 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003517 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003518 Ty = StTy->getElementType(Field);
3519 } else {
3520 Ty = cast<SequentialType>(Ty)->getElementType();
3521
3522 // Handle constant subscripts.
3523 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003524 if (CI->getZExtValue() == 0) continue;
3525 if (CI->getType()->isSigned())
3526 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003527 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003528 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003529 continue;
3530 }
3531
3532 // Ptr = Ptr + Idx * ElementSize;
3533
3534 // Cast Idx to UIntPtrTy if needed.
3535 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3536
Owen Andersona69571c2006-05-03 01:29:57 +00003537 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003538 // Mask off bits that should not be set.
3539 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003540 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003541
3542 // Multiply by the element size and add to the base.
3543 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3544 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3545 }
3546 }
3547
3548 // Make sure that the offset fits in uintptr_t.
3549 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003550 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003551
3552 // Okay, we have now emitted all of the variable index parts to the BB that
3553 // the GEP is defined in. Loop over all of the using instructions, inserting
3554 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003555 // instruction to use the newly computed value, making GEPI dead. When the
3556 // user is a load or store instruction address, we emit the add into the user
3557 // block, otherwise we use a canonical version right next to the gep (these
3558 // won't be foldable as addresses, so we might as well share the computation).
3559
Chris Lattnerf0df8822006-05-06 09:10:37 +00003560 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003561 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003562
3563 // Finally, the GEP is dead, remove it.
3564 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003565
3566 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003567}
3568
Chris Lattnerbad7f482006-10-28 19:22:10 +00003569
3570/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3571/// successor if it will improve codegen. We only do this if the successor has
3572/// phi nodes (otherwise critical edges are ok). If there is already another
3573/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3574/// instead of introducing a new block.
3575static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3576 BasicBlock *TIBB = TI->getParent();
3577 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3578 assert(isa<PHINode>(Dest->begin()) &&
3579 "This should only be called if Dest has a PHI!");
3580
3581 /// TIPHIValues - This array is lazily computed to determine the values of
3582 /// PHIs in Dest that TI would provide.
3583 std::vector<Value*> TIPHIValues;
3584
3585 // Check to see if Dest has any blocks that can be used as a split edge for
3586 // this terminator.
3587 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3588 BasicBlock *Pred = *PI;
3589 // To be usable, the pred has to end with an uncond branch to the dest.
3590 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3591 if (!PredBr || !PredBr->isUnconditional() ||
3592 // Must be empty other than the branch.
3593 &Pred->front() != PredBr)
3594 continue;
3595
3596 // Finally, since we know that Dest has phi nodes in it, we have to make
3597 // sure that jumping to Pred will have the same affect as going to Dest in
3598 // terms of PHI values.
3599 PHINode *PN;
3600 unsigned PHINo = 0;
3601 bool FoundMatch = true;
3602 for (BasicBlock::iterator I = Dest->begin();
3603 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3604 if (PHINo == TIPHIValues.size())
3605 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3606
3607 // If the PHI entry doesn't work, we can't use this pred.
3608 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3609 FoundMatch = false;
3610 break;
3611 }
3612 }
3613
3614 // If we found a workable predecessor, change TI to branch to Succ.
3615 if (FoundMatch) {
3616 Dest->removePredecessor(TIBB);
3617 TI->setSuccessor(SuccNum, Pred);
3618 return;
3619 }
3620 }
3621
3622 SplitCriticalEdge(TI, SuccNum, P, true);
3623}
3624
3625
Chris Lattner1c08c712005-01-07 07:47:53 +00003626bool SelectionDAGISel::runOnFunction(Function &Fn) {
3627 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3628 RegMap = MF.getSSARegMap();
3629 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3630
Chris Lattner47e32e62006-10-28 17:04:37 +00003631 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003632 //
Chris Lattner7e598092006-05-05 01:04:50 +00003633 // In this pass we also look for GEP and cast instructions that are used
3634 // across basic blocks and rewrite them to improve basic-block-at-a-time
3635 // selection.
3636 //
Chris Lattner90323642006-05-05 21:17:49 +00003637 bool MadeChange = true;
3638 while (MadeChange) {
3639 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003640 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003641 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003642 TerminatorInst *BBTI = BB->getTerminator();
3643 if (BBTI->getNumSuccessors() > 1) {
3644 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003645 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3646 isCriticalEdge(BBTI, i, true))
3647 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003648 }
3649
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003650
Chris Lattner57f9a432006-09-28 06:17:10 +00003651 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003652 Instruction *I = BBI++;
3653 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003654 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003655 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003656 // If the source of the cast is a constant, then this should have
3657 // already been constant folded. The only reason NOT to constant fold
3658 // it is if something (e.g. LSR) was careful to place the constant
3659 // evaluation in a block other than then one that uses it (e.g. to hoist
3660 // the address of globals out of a loop). If this is the case, we don't
3661 // want to forward-subst the cast.
3662 if (isa<Constant>(CI->getOperand(0)))
3663 continue;
3664
Chris Lattner7e598092006-05-05 01:04:50 +00003665 // If this is a noop copy, sink it into user blocks to reduce the number
3666 // of virtual registers that must be created and coallesced.
3667 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3668 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3669
3670 // This is an fp<->int conversion?
3671 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3672 continue;
3673
3674 // If this is an extension, it will be a zero or sign extension, which
3675 // isn't a noop.
3676 if (SrcVT < DstVT) continue;
3677
3678 // If these values will be promoted, find out what they will be promoted
3679 // to. This helps us consider truncates on PPC as noop copies when they
3680 // are.
3681 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3682 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3683 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3684 DstVT = TLI.getTypeToTransformTo(DstVT);
3685
3686 // If, after promotion, these are the same types, this is a noop copy.
3687 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003688 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003689 }
3690 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003691 }
Chris Lattner90323642006-05-05 21:17:49 +00003692 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003693
Chris Lattner1c08c712005-01-07 07:47:53 +00003694 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3695
3696 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3697 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003698
Chris Lattner1c08c712005-01-07 07:47:53 +00003699 return true;
3700}
3701
Chris Lattner571e4342006-10-27 21:36:01 +00003702SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3703 unsigned Reg) {
3704 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003705 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003706 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003707 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003708
3709 // If this type is not legal, we must make sure to not create an invalid
3710 // register use.
3711 MVT::ValueType SrcVT = Op.getValueType();
3712 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003713 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003714 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003715 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003716 // Handle copies from generic vectors to registers.
3717 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3718 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3719 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003720
Chris Lattner70c2a612006-03-31 02:06:56 +00003721 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3722 // MVT::Vector type.
3723 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3724 DAG.getConstant(NE, MVT::i32),
3725 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003726
Chris Lattner70c2a612006-03-31 02:06:56 +00003727 // Loop over all of the elements of the resultant vector,
3728 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3729 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003730 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003731 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003732 for (unsigned i = 0; i != NE; ++i) {
3733 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003734 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003735 if (PTyElementVT == PTyLegalElementVT) {
3736 // Elements are legal.
3737 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3738 } else if (PTyLegalElementVT > PTyElementVT) {
3739 // Elements are promoted.
3740 if (MVT::isFloatingPoint(PTyLegalElementVT))
3741 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3742 else
3743 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3744 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3745 } else {
3746 // Elements are expanded.
3747 // The src value is expanded into multiple registers.
3748 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003749 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003750 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003751 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003752 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3753 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3754 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003755 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003756 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3757 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003758 } else if (SrcVT < DestVT) {
3759 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003760 if (MVT::isFloatingPoint(SrcVT))
3761 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3762 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003763 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003764 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003765 } else {
3766 // The src value is expanded into multiple registers.
3767 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003768 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003769 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003770 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003771 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003772 return DAG.getCopyToReg(Op, Reg+1, Hi);
3773 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003774}
3775
Chris Lattner068a81e2005-01-17 17:15:02 +00003776void SelectionDAGISel::
3777LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3778 std::vector<SDOperand> &UnorderedChains) {
3779 // If this is the entry block, emit arguments.
3780 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003781 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003782 SDOperand OldRoot = SDL.DAG.getRoot();
3783 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003784
Chris Lattnerbf209482005-10-30 19:42:35 +00003785 unsigned a = 0;
3786 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3787 AI != E; ++AI, ++a)
3788 if (!AI->use_empty()) {
3789 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003790
Chris Lattnerbf209482005-10-30 19:42:35 +00003791 // If this argument is live outside of the entry block, insert a copy from
3792 // whereever we got it to the vreg that other BB's will reference it as.
3793 if (FuncInfo.ValueMap.count(AI)) {
3794 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003795 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003796 UnorderedChains.push_back(Copy);
3797 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003798 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003799
Chris Lattnerbf209482005-10-30 19:42:35 +00003800 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003801 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003802 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003803}
3804
Chris Lattner1c08c712005-01-07 07:47:53 +00003805void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3806 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003807 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003808 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003809
3810 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003811
Chris Lattnerbf209482005-10-30 19:42:35 +00003812 // Lower any arguments needed in this block if this is the entry block.
3813 if (LLVMBB == &LLVMBB->getParent()->front())
3814 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003815
3816 BB = FuncInfo.MBBMap[LLVMBB];
3817 SDL.setCurrentBasicBlock(BB);
3818
3819 // Lower all of the non-terminator instructions.
3820 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3821 I != E; ++I)
3822 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003823
Chris Lattner1c08c712005-01-07 07:47:53 +00003824 // Ensure that all instructions which are used outside of their defining
3825 // blocks are available as virtual registers.
3826 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003827 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003828 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003829 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003830 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003831 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003832 }
3833
3834 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3835 // ensure constants are generated when needed. Remember the virtual registers
3836 // that need to be added to the Machine PHI nodes as input. We cannot just
3837 // directly add them, because expansion might result in multiple MBB's for one
3838 // BB. As such, the start of the BB might correspond to a different MBB than
3839 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003840 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00003841 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00003842
3843 // Emit constants only once even if used by multiple PHI nodes.
3844 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003845
Chris Lattner8c494ab2006-10-27 23:50:33 +00003846 // Vector bool would be better, but vector<bool> is really slow.
3847 std::vector<unsigned char> SuccsHandled;
3848 if (TI->getNumSuccessors())
3849 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3850
Chris Lattner1c08c712005-01-07 07:47:53 +00003851 // Check successor nodes PHI nodes that expect a constant to be available from
3852 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00003853 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3854 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003855 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00003856 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003857
Chris Lattner8c494ab2006-10-27 23:50:33 +00003858 // If this terminator has multiple identical successors (common for
3859 // switches), only handle each succ once.
3860 unsigned SuccMBBNo = SuccMBB->getNumber();
3861 if (SuccsHandled[SuccMBBNo]) continue;
3862 SuccsHandled[SuccMBBNo] = true;
3863
3864 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00003865 PHINode *PN;
3866
3867 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3868 // nodes and Machine PHI nodes, but the incoming operands have not been
3869 // emitted yet.
3870 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00003871 (PN = dyn_cast<PHINode>(I)); ++I) {
3872 // Ignore dead phi's.
3873 if (PN->use_empty()) continue;
3874
3875 unsigned Reg;
3876 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3877 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3878 unsigned &RegOut = ConstantsOut[C];
3879 if (RegOut == 0) {
3880 RegOut = FuncInfo.CreateRegForValue(C);
3881 UnorderedChains.push_back(
3882 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00003883 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00003884 Reg = RegOut;
3885 } else {
3886 Reg = FuncInfo.ValueMap[PHIOp];
3887 if (Reg == 0) {
3888 assert(isa<AllocaInst>(PHIOp) &&
3889 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3890 "Didn't codegen value into a register!??");
3891 Reg = FuncInfo.CreateRegForValue(PHIOp);
3892 UnorderedChains.push_back(
3893 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00003894 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003895 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00003896
3897 // Remember that this register needs to added to the machine PHI node as
3898 // the input for this MBB.
3899 MVT::ValueType VT = TLI.getValueType(PN->getType());
3900 unsigned NumElements;
3901 if (VT != MVT::Vector)
3902 NumElements = TLI.getNumElements(VT);
3903 else {
3904 MVT::ValueType VT1,VT2;
3905 NumElements =
3906 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3907 VT1, VT2);
3908 }
3909 for (unsigned i = 0, e = NumElements; i != e; ++i)
3910 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3911 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003912 }
3913 ConstantsOut.clear();
3914
Chris Lattnerddb870b2005-01-13 17:59:43 +00003915 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00003916 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00003917 SDOperand Root = SDL.getRoot();
3918 if (Root.getOpcode() != ISD::EntryToken) {
3919 unsigned i = 0, e = UnorderedChains.size();
3920 for (; i != e; ++i) {
3921 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3922 if (UnorderedChains[i].Val->getOperand(0) == Root)
3923 break; // Don't add the root if we already indirectly depend on it.
3924 }
3925
3926 if (i == e)
3927 UnorderedChains.push_back(Root);
3928 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003929 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3930 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00003931 }
3932
Chris Lattner1c08c712005-01-07 07:47:53 +00003933 // Lower the terminator after the copies are emitted.
3934 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00003935
Nate Begemanf15485a2006-03-27 01:32:24 +00003936 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00003937 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00003938 SwitchCases.clear();
3939 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00003940 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00003941
Chris Lattnera651cf62005-01-17 19:43:36 +00003942 // Make sure the root of the DAG is up-to-date.
3943 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00003944}
3945
Nate Begemanf15485a2006-03-27 01:32:24 +00003946void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003947 // Get alias analysis for load/store combining.
3948 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3949
Chris Lattneraf21d552005-10-10 16:47:10 +00003950 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003951 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003952
Chris Lattner1c08c712005-01-07 07:47:53 +00003953 DEBUG(std::cerr << "Lowered selection DAG:\n");
3954 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003955
Chris Lattner1c08c712005-01-07 07:47:53 +00003956 // Second step, hack on the DAG until it only uses operations and types that
3957 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00003958 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00003959
Chris Lattner1c08c712005-01-07 07:47:53 +00003960 DEBUG(std::cerr << "Legalized selection DAG:\n");
3961 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003962
Chris Lattneraf21d552005-10-10 16:47:10 +00003963 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003964 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003965
Evan Chenga9c20912006-01-21 02:32:06 +00003966 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00003967
Chris Lattnera33ef482005-03-30 01:10:47 +00003968 // Third, instruction select all of the operations to machine code, adding the
3969 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00003970 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00003971
Chris Lattner1c08c712005-01-07 07:47:53 +00003972 DEBUG(std::cerr << "Selected machine code:\n");
3973 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003974}
Chris Lattner1c08c712005-01-07 07:47:53 +00003975
Nate Begemanf15485a2006-03-27 01:32:24 +00003976void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3977 FunctionLoweringInfo &FuncInfo) {
3978 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3979 {
3980 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3981 CurDAG = &DAG;
3982
3983 // First step, lower LLVM code to some DAG. This DAG may use operations and
3984 // types that are not supported by the target.
3985 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3986
3987 // Second step, emit the lowered DAG as machine code.
3988 CodeGenAndEmitDAG(DAG);
3989 }
3990
Chris Lattnera33ef482005-03-30 01:10:47 +00003991 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00003992 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00003993 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00003994 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3995 MachineInstr *PHI = PHINodesToUpdate[i].first;
3996 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3997 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00003998 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00003999 PHI->addMachineBasicBlockOperand(BB);
4000 }
4001 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004002 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004003
Nate Begeman9453eea2006-04-23 06:26:20 +00004004 // If the JumpTable record is filled in, then we need to emit a jump table.
4005 // Updating the PHI nodes is tricky in this case, since we need to determine
4006 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004007 if (JT.Reg) {
4008 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4009 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4010 CurDAG = &SDAG;
4011 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004012 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004013 // Set the current basic block to the mbb we wish to insert the code into
4014 BB = JT.MBB;
4015 SDL.setCurrentBasicBlock(BB);
4016 // Emit the code
4017 SDL.visitJumpTable(JT);
4018 SDAG.setRoot(SDL.getRoot());
4019 CodeGenAndEmitDAG(SDAG);
4020 // Update PHI Nodes
4021 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4022 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4023 MachineBasicBlock *PHIBB = PHI->getParent();
4024 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4025 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004026 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004027 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004028 PHI->addMachineBasicBlockOperand(RangeBB);
4029 }
4030 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004031 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004032 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004033 }
4034 }
4035 return;
4036 }
4037
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004038 // If the switch block involved a branch to one of the actual successors, we
4039 // need to update PHI nodes in that block.
4040 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4041 MachineInstr *PHI = PHINodesToUpdate[i].first;
4042 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4043 "This is not a machine PHI node that we are updating!");
4044 if (BB->isSuccessor(PHI->getParent())) {
4045 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4046 PHI->addMachineBasicBlockOperand(BB);
4047 }
4048 }
4049
Nate Begemanf15485a2006-03-27 01:32:24 +00004050 // If we generated any switch lowering information, build and codegen any
4051 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004052 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004053 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4054 CurDAG = &SDAG;
4055 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004056
Nate Begemanf15485a2006-03-27 01:32:24 +00004057 // Set the current basic block to the mbb we wish to insert the code into
4058 BB = SwitchCases[i].ThisBB;
4059 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004060
Nate Begemanf15485a2006-03-27 01:32:24 +00004061 // Emit the code
4062 SDL.visitSwitchCase(SwitchCases[i]);
4063 SDAG.setRoot(SDL.getRoot());
4064 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004065
4066 // Handle any PHI nodes in successors of this chunk, as if we were coming
4067 // from the original BB before switch expansion. Note that PHI nodes can
4068 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4069 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004070 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004071 for (MachineBasicBlock::iterator Phi = BB->begin();
4072 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4073 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4074 for (unsigned pn = 0; ; ++pn) {
4075 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4076 if (PHINodesToUpdate[pn].first == Phi) {
4077 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4078 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4079 break;
4080 }
4081 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004082 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004083
4084 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004085 if (BB == SwitchCases[i].FalseBB)
4086 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004087
4088 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004089 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004090 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004091 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004092 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004093 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004094}
Evan Chenga9c20912006-01-21 02:32:06 +00004095
Jim Laskey13ec7022006-08-01 14:21:23 +00004096
Evan Chenga9c20912006-01-21 02:32:06 +00004097//===----------------------------------------------------------------------===//
4098/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4099/// target node in the graph.
4100void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4101 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004102
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004103 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004104
4105 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004106 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004107 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004108 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004109
Jim Laskey9ff542f2006-08-01 18:29:48 +00004110 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004111 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004112 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004113}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004114
Chris Lattner03fc53c2006-03-06 00:22:00 +00004115
Jim Laskey9ff542f2006-08-01 18:29:48 +00004116HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4117 return new HazardRecognizer();
4118}
4119
Chris Lattner75548062006-10-11 03:58:02 +00004120//===----------------------------------------------------------------------===//
4121// Helper functions used by the generated instruction selector.
4122//===----------------------------------------------------------------------===//
4123// Calls to these methods are generated by tblgen.
4124
4125/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4126/// the dag combiner simplified the 255, we still want to match. RHS is the
4127/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4128/// specified in the .td file (e.g. 255).
4129bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4130 int64_t DesiredMaskS) {
4131 uint64_t ActualMask = RHS->getValue();
4132 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4133
4134 // If the actual mask exactly matches, success!
4135 if (ActualMask == DesiredMask)
4136 return true;
4137
4138 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4139 if (ActualMask & ~DesiredMask)
4140 return false;
4141
4142 // Otherwise, the DAG Combiner may have proven that the value coming in is
4143 // either already zero or is not demanded. Check for known zero input bits.
4144 uint64_t NeededMask = DesiredMask & ~ActualMask;
4145 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4146 return true;
4147
4148 // TODO: check to see if missing bits are just not demanded.
4149
4150 // Otherwise, this pattern doesn't match.
4151 return false;
4152}
4153
4154/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4155/// the dag combiner simplified the 255, we still want to match. RHS is the
4156/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4157/// specified in the .td file (e.g. 255).
4158bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4159 int64_t DesiredMaskS) {
4160 uint64_t ActualMask = RHS->getValue();
4161 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4162
4163 // If the actual mask exactly matches, success!
4164 if (ActualMask == DesiredMask)
4165 return true;
4166
4167 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4168 if (ActualMask & ~DesiredMask)
4169 return false;
4170
4171 // Otherwise, the DAG Combiner may have proven that the value coming in is
4172 // either already zero or is not demanded. Check for known zero input bits.
4173 uint64_t NeededMask = DesiredMask & ~ActualMask;
4174
4175 uint64_t KnownZero, KnownOne;
4176 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4177
4178 // If all the missing bits in the or are already known to be set, match!
4179 if ((NeededMask & KnownOne) == NeededMask)
4180 return true;
4181
4182 // TODO: check to see if missing bits are just not demanded.
4183
4184 // Otherwise, this pattern doesn't match.
4185 return false;
4186}
4187
Jim Laskey9ff542f2006-08-01 18:29:48 +00004188
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004189/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4190/// by tblgen. Others should not call it.
4191void SelectionDAGISel::
4192SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4193 std::vector<SDOperand> InOps;
4194 std::swap(InOps, Ops);
4195
4196 Ops.push_back(InOps[0]); // input chain.
4197 Ops.push_back(InOps[1]); // input asm string.
4198
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004199 unsigned i = 2, e = InOps.size();
4200 if (InOps[e-1].getValueType() == MVT::Flag)
4201 --e; // Don't process a flag operand if it is here.
4202
4203 while (i != e) {
4204 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4205 if ((Flags & 7) != 4 /*MEM*/) {
4206 // Just skip over this operand, copying the operands verbatim.
4207 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4208 i += (Flags >> 3) + 1;
4209 } else {
4210 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4211 // Otherwise, this is a memory operand. Ask the target to select it.
4212 std::vector<SDOperand> SelOps;
4213 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4214 std::cerr << "Could not match memory address. Inline asm failure!\n";
4215 exit(1);
4216 }
4217
4218 // Add this to the output node.
4219 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4220 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4221 i += 2;
4222 }
4223 }
4224
4225 // Add the flag input back if present.
4226 if (e != InOps.size())
4227 Ops.push_back(InOps.back());
4228}