blob: 635455bc130741d0f5faba605905c21a1863e478 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-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 Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattner975f5c92005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Cheng739a6a42006-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 Lattnere05a4612005-01-12 03:41:21 +000058#else
Chris Lattneref598052006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000060#endif
61
Jim Laskey29e635d2006-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 Chengc1e1d972006-01-23 07:01:07 +000075namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000076 cl::opt<RegisterScheduler::FunctionPassCtor, false,
77 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000079 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 cl::desc("Instruction schedulers available:"));
81
Jim Laskey03593f72006-08-01 18:29:48 +000082 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000083 defaultListDAGScheduler("default", " Best scheduler for the target",
84 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000085} // namespace
86
Chris Lattner6f87d182006-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 Lattner996795b2006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-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 Chengef9e07d2006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000135 };
136}
Evan Chengc1e1d972006-01-23 07:01:07 +0000137
Chris Lattner7a60d912005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-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 Lattner7a60d912005-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 Lattnerd0061952005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner7a60d912005-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 Lattnered0110b2006-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 Brukman835702a2005-04-21 22:36:52 +0000191
Chris Lattner49409cb2006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner7a60d912005-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 Begemaned728c12006-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 Lattner7a60d912005-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 Begemaned728c12006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattner6871b232005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-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 Lattner6871b232005-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 Begemaned728c12006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner7a60d912005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattner6871b232005-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 Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-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 Spencere0fc4df2006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000247 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000248 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000250
Reid Spencere0fc4df2006-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 Lattnercbefe722005-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 Spencere0fc4df2006-10-20 07:07:24 +0000259 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000260 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000262 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000263 }
264
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000265 for (; BB != EB; ++BB)
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000275 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-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 Lattner84a03502006-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 Lattner8ea875f2005-01-07 21:34:19 +0000295 }
Chris Lattner84a03502006-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 Lattner7a60d912005-01-07 07:47:53 +0000301 }
302}
303
Chris Lattner49409cb2006-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 Lattner7ececaa2006-03-16 23:05:19 +0000327 if (NumElts == 1)
328 VT = EltTy;
329 else
330 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-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 Lattner7a60d912005-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 Lattner4d9651c2005-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 Begemaned728c12006-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 Spencere0fc4df2006-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 Begemaned728c12006-03-27 01:32:24 +0000406
Reid Spencere0fc4df2006-10-20 07:07:24 +0000407 return cast<const ConstantInt>(C1.first)->getSExtValue() <
408 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000409 }
410 };
411
Chris Lattner7a60d912005-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 Anderson20a631f2006-05-03 01:29:57 +0000418 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000419
Nate Begemaned728c12006-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 Begeman4ca2ea52006-04-22 18:53:45 +0000423 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000424
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000430 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000431 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000432 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 }
434
Chris Lattner4108bb02005-01-17 19:43:36 +0000435 /// getRoot - Return the current virtual root of the Selection DAG.
436 ///
437 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000438 if (PendingLoads.empty())
439 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000440
Chris Lattner4d9651c2005-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 Lattnerc24a1d32006-08-08 02:23:42 +0000449 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
450 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000451 PendingLoads.clear();
452 DAG.setRoot(Root);
453 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000454 }
455
Chris Lattnered0110b2006-10-27 21:36:01 +0000456 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457
Chris Lattner7a60d912005-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 Lattner4024c002006-03-15 22:19:46 +0000473 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000474 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000475 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000476
477 SDOperand getIntPtrConstant(uint64_t Val) {
478 return DAG.getConstant(Val, TLI.getPointerTy());
479 }
480
Chris Lattner8471b152006-03-16 19:57:50 +0000481 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-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 Lattner1558fc62006-02-01 18:59:47 +0000488
Chris Lattner6f87d182006-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 Begemaned728c12006-03-27 01:32:24 +0000494
Chris Lattnered0110b2006-10-27 21:36:01 +0000495 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
496 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
497 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000498 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000499 void ExportFromCurrentBlock(Value *V);
500
Chris Lattner7a60d912005-01-07 07:47:53 +0000501 // Terminator instructions.
502 void visitRet(ReturnInst &I);
503 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000504 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000505 void visitUnreachable(UnreachableInst &I) { /* noop */ }
506
Nate Begemaned728c12006-03-27 01:32:24 +0000507 // Helper for visitSwitch
508 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000509 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000510
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
513 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
514
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000515 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
516 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000517 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000518 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-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 Lattner6f3b5772005-09-28 22:28:18 +0000523 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000524 void visitSub(User &I);
Reid Spencer7e80b0b2006-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 Lattner6f3b5772005-09-28 22:28:18 +0000530 }
Reid Spencer7e80b0b2006-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 Lattner7a60d912005-01-07 07:47:53 +0000534 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000535 const Type *Ty = I.getType();
Reid Spencer7e80b0b2006-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 Lattner7a60d912005-01-07 07:47:53 +0000540 }
Reid Spencer7e80b0b2006-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 Begeman127321b2005-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 Lattner7a60d912005-01-07 07:47:53 +0000547 }
548
Evan Cheng1c5b7d12006-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 Lattner7a60d912005-01-07 07:47:53 +0000563
Chris Lattner67271862006-03-29 00:11:43 +0000564 void visitExtractElement(User &I);
565 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000566 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000567
Chris Lattner7a60d912005-01-07 07:47:53 +0000568 void visitGetElementPtr(User &I);
569 void visitCast(User &I);
570 void visitSelect(User &I);
Chris Lattner7a60d912005-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 Lattner476e67b2006-01-26 22:24:51 +0000579 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000580 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000581 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000582
Chris Lattner7a60d912005-01-07 07:47:53 +0000583 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000584 void visitVAArg(VAArgInst &I);
585 void visitVAEnd(CallInst &I);
586 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000587 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000588
Chris Lattner875def92005-01-11 05:56:49 +0000589 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-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 Lattner8471b152006-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 Lattnerc16b05e2006-03-19 00:20:20 +0000618 if (!isa<PackedType>(VTy))
619 return N = DAG.getNode(ISD::UNDEF, VT);
620
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000621 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000626 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000632 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
633 &Ops[0], Ops.size());
Chris Lattner8471b152006-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 Lattner8471b152006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000643 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000644 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000645 for (unsigned i = 0; i != NumElements; ++i)
646 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-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 Lattnerf4e1a532006-03-19 00:52:58 +0000657 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000658 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
659 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000660 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000661 } else {
662 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000663 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-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 Lattner5fe1f542006-03-31 02:06:56 +0000681 if (VT != MVT::Vector) {
682 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000683
Chris Lattner5fe1f542006-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 Lattner8471b152006-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 Lattner5fe1f542006-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 Lattner4a2413a2006-04-05 06:54:42 +0000700 const PackedType *PTy = cast<PackedType>(VTy);
701 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000702 PTyLegalElementVT);
703
704 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000705 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000736 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-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 Lattner8471b152006-03-16 19:57:50 +0000744 }
745
746 return N;
747}
748
749
Chris Lattner7a60d912005-01-07 07:47:53 +0000750void SelectionDAGLowering::visitRet(ReturnInst &I) {
751 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000752 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000753 return;
754 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000755 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-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 Chenga2e99532006-05-26 23:09:09 +0000759 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-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 Chenga2e99532006-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 Begeman8c47c3a2006-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 Lattner7a60d912005-01-07 07:47:53 +0000773
Evan Chenga2e99532006-05-26 23:09:09 +0000774 if (isSigned)
Nate Begeman8c47c3a2006-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 Chenga2e99532006-05-26 23:09:09 +0000780 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000784}
785
Chris Lattnered0110b2006-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 Lattner84a03502006-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 Lattnere60ae822006-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 Lattnered0110b2006-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 Lattnered0110b2006-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 Lattnere60ae822006-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 Lattnered0110b2006-10-27 21:36:01 +0000846 const BasicBlock *BB = CurBB->getBasicBlock();
847
Chris Lattner427301f2006-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 Lattnered0110b2006-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 Lattnerf31b9ef2006-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 Lattnered0110b2006-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 Lattnered0110b2006-10-27 21:36:01 +0000929 return;
930 }
931
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000932
933 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-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 Lattnerf1b54fd2006-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 Lattnered0110b2006-10-27 21:36:01 +0000946
Chris Lattnerf1b54fd2006-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 Lattnered0110b2006-10-27 21:36:01 +0000969}
970
Chris Lattner427301f2006-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
978 return true;
979}
980
Chris Lattner7a60d912005-01-07 07:47:53 +0000981void SelectionDAGLowering::visitBr(BranchInst &I) {
982 // Update machine-CFG edges.
983 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000984
985 // Figure out which block is immediately after the current one.
986 MachineBasicBlock *NextBlock = 0;
987 MachineFunction::iterator BBI = CurMBB;
988 if (++BBI != CurMBB->getParent()->end())
989 NextBlock = BBI;
990
991 if (I.isUnconditional()) {
992 // If this is not a fall-through branch, emit the branch.
993 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000994 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000995 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000996
Chris Lattner963ddad2006-10-24 17:57:59 +0000997 // Update machine-CFG edges.
998 CurMBB->addSuccessor(Succ0MBB);
999
1000 return;
1001 }
1002
1003 // If this condition is one of the special cases we handle, do special stuff
1004 // now.
1005 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001006 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001007
1008 // If this is a series of conditions that are or'd or and'd together, emit
1009 // this as a sequence of branches instead of setcc's with and/or operations.
1010 // For example, instead of something like:
1011 // cmp A, B
1012 // C = seteq
1013 // cmp D, E
1014 // F = setle
1015 // or C, F
1016 // jnz foo
1017 // Emit:
1018 // cmp A, B
1019 // je foo
1020 // cmp D, E
1021 // jle foo
1022 //
1023 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1024 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001025 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001026 BOp->getOpcode() == Instruction::Or)) {
1027 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001028
Chris Lattner427301f2006-10-31 22:37:42 +00001029 // Allow some cases to be rejected.
1030 if (ShouldEmitAsBranches(SwitchCases)) {
1031 // If the compares in later blocks need to use values not currently
1032 // exported from this block, export them now. This block should always
1033 // be the first entry.
1034 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1035
1036 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1037 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1038 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1039 }
1040
1041 // Emit the branch for this block.
1042 visitSwitchCase(SwitchCases[0]);
1043 SwitchCases.erase(SwitchCases.begin());
1044 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001045 }
1046
Chris Lattner427301f2006-10-31 22:37:42 +00001047 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001048 }
1049 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001050
1051 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +00001052 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001053 Succ0MBB, Succ1MBB, CurMBB);
1054 // Use visitSwitchCase to actually insert the fast branch sequence for this
1055 // cond branch.
1056 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001057}
1058
Nate Begemaned728c12006-03-27 01:32:24 +00001059/// visitSwitchCase - Emits the necessary code to represent a single node in
1060/// the binary search tree resulting from lowering a switch instruction.
1061void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001062 SDOperand Cond;
1063 SDOperand CondLHS = getValue(CB.CmpLHS);
1064
Chris Lattnered0110b2006-10-27 21:36:01 +00001065 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1066 // handle common cases produced by branch lowering.
1067 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001068 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001069 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1070 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1071 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1072 } else
1073 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001074
1075 // Set NextBlock to be the MBB immediately after the current one, if any.
1076 // This is used to avoid emitting unnecessary branches to the next block.
1077 MachineBasicBlock *NextBlock = 0;
1078 MachineFunction::iterator BBI = CurMBB;
1079 if (++BBI != CurMBB->getParent()->end())
1080 NextBlock = BBI;
1081
1082 // If the lhs block is the next block, invert the condition so that we can
1083 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001084 if (CB.TrueBB == NextBlock) {
1085 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001086 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1087 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1088 }
1089 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001090 DAG.getBasicBlock(CB.TrueBB));
1091 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001092 DAG.setRoot(BrCond);
1093 else
1094 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001095 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001096 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001097 CurMBB->addSuccessor(CB.TrueBB);
1098 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001099}
1100
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001101void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001102 // Emit the code for the jump table
1103 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001104 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1105 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1106 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1107 Table, Index));
1108 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001109}
1110
Nate Begemaned728c12006-03-27 01:32:24 +00001111void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1112 // Figure out which block is immediately after the current one.
1113 MachineBasicBlock *NextBlock = 0;
1114 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001115
Nate Begemaned728c12006-03-27 01:32:24 +00001116 if (++BBI != CurMBB->getParent()->end())
1117 NextBlock = BBI;
1118
Chris Lattner6d6fc262006-10-22 21:36:53 +00001119 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1120
Nate Begemaned728c12006-03-27 01:32:24 +00001121 // If there is only the default destination, branch to it if it is not the
1122 // next basic block. Otherwise, just fall through.
1123 if (I.getNumOperands() == 2) {
1124 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001125
Nate Begemaned728c12006-03-27 01:32:24 +00001126 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001127 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001128 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001129 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001130
Chris Lattner6d6fc262006-10-22 21:36:53 +00001131 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001132 return;
1133 }
1134
1135 // If there are any non-default case statements, create a vector of Cases
1136 // representing each one, and sort the vector so that we can efficiently
1137 // create a binary search tree from them.
1138 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001139
Nate Begemaned728c12006-03-27 01:32:24 +00001140 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1141 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1142 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1143 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001144
Nate Begemaned728c12006-03-27 01:32:24 +00001145 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1146
1147 // Get the Value to be switched on and default basic blocks, which will be
1148 // inserted into CaseBlock records, representing basic blocks in the binary
1149 // search tree.
1150 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001151
1152 // Get the MachineFunction which holds the current MBB. This is used during
1153 // emission of jump tables, and when inserting any additional MBBs necessary
1154 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001155 MachineFunction *CurMF = CurMBB->getParent();
1156 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001157
1158 // If the switch has few cases (two or less) emit a series of specific
1159 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001160 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001161 // TODO: If any two of the cases has the same destination, and if one value
1162 // is the same as the other, but has one bit unset that the other has set,
1163 // use bit manipulation to do two compares at once. For example:
1164 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1165
Chris Lattner4c931502006-10-23 18:38:22 +00001166 // Rearrange the case blocks so that the last one falls through if possible.
1167 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1168 // The last case block won't fall through into 'NextBlock' if we emit the
1169 // branches in this order. See if rearranging a case value would help.
1170 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1171 if (Cases[i].second == NextBlock) {
1172 std::swap(Cases[i], Cases.back());
1173 break;
1174 }
1175 }
1176 }
1177
Chris Lattner6d6fc262006-10-22 21:36:53 +00001178 // Create a CaseBlock record representing a conditional branch to
1179 // the Case's target mbb if the value being switched on SV is equal
1180 // to C.
1181 MachineBasicBlock *CurBlock = CurMBB;
1182 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1183 MachineBasicBlock *FallThrough;
1184 if (i != e-1) {
1185 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1186 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1187 } else {
1188 // If the last case doesn't match, go to the default block.
1189 FallThrough = Default;
1190 }
1191
1192 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1193 Cases[i].second, FallThrough, CurBlock);
1194
1195 // If emitting the first comparison, just call visitSwitchCase to emit the
1196 // code into the current block. Otherwise, push the CaseBlock onto the
1197 // vector to be later processed by SDISel, and insert the node's MBB
1198 // before the next MBB.
1199 if (CurBlock == CurMBB)
1200 visitSwitchCase(CB);
1201 else
1202 SwitchCases.push_back(CB);
1203
1204 CurBlock = FallThrough;
1205 }
1206 return;
1207 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001208
Nate Begemand7a19102006-05-08 16:51:36 +00001209 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1210 // target supports indirect branches, then emit a jump table rather than
1211 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001212 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1213 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001214 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001215 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1216 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001217 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1218
Nate Begemand7a19102006-05-08 16:51:36 +00001219 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001220 // Create a new basic block to hold the code for loading the address
1221 // of the jump table, and jumping to it. Update successor information;
1222 // we will either branch to the default case for the switch, or the jump
1223 // table.
1224 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1225 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1226 CurMBB->addSuccessor(Default);
1227 CurMBB->addSuccessor(JumpTableBB);
1228
1229 // Subtract the lowest switch case value from the value being switched on
1230 // and conditional branch to default mbb if the result is greater than the
1231 // difference between smallest and largest cases.
1232 SDOperand SwitchOp = getValue(SV);
1233 MVT::ValueType VT = SwitchOp.getValueType();
1234 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1235 DAG.getConstant(First, VT));
1236
1237 // The SDNode we just created, which holds the value being switched on
1238 // minus the the smallest case value, needs to be copied to a virtual
1239 // register so it can be used as an index into the jump table in a
1240 // subsequent basic block. This value may be smaller or larger than the
1241 // target's pointer type, and therefore require extension or truncating.
1242 if (VT > TLI.getPointerTy())
1243 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1244 else
1245 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001246
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001247 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1248 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1249
1250 // Emit the range check for the jump table, and branch to the default
1251 // block for the switch statement if the value being switched on exceeds
1252 // the largest case in the switch.
1253 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1254 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1255 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1256 DAG.getBasicBlock(Default)));
1257
Nate Begemandf488392006-05-03 03:48:02 +00001258 // Build a vector of destination BBs, corresponding to each target
1259 // of the jump table. If the value of the jump table slot corresponds to
1260 // a case statement, push the case's BB onto the vector, otherwise, push
1261 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001262 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001263 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001264 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001265 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001266 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001267 ++ii;
1268 } else {
1269 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001270 }
Nate Begemandf488392006-05-03 03:48:02 +00001271
Chris Lattner84a03502006-10-27 23:50:33 +00001272 // Update successor info. Add one edge to each unique successor.
1273 // Vector bool would be better, but vector<bool> is really slow.
1274 std::vector<unsigned char> SuccsHandled;
1275 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1276
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001277 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001278 E = DestBBs.end(); I != E; ++I) {
1279 if (!SuccsHandled[(*I)->getNumber()]) {
1280 SuccsHandled[(*I)->getNumber()] = true;
1281 JumpTableBB->addSuccessor(*I);
1282 }
1283 }
Nate Begemandf488392006-05-03 03:48:02 +00001284
1285 // Create a jump table index for this jump table, or return an existing
1286 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001287 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1288
1289 // Set the jump table information so that we can codegen it as a second
1290 // MachineBasicBlock
1291 JT.Reg = JumpTableReg;
1292 JT.JTI = JTI;
1293 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001294 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001295 return;
1296 }
1297 }
Nate Begemaned728c12006-03-27 01:32:24 +00001298
1299 // Push the initial CaseRec onto the worklist
1300 std::vector<CaseRec> CaseVec;
1301 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1302
1303 while (!CaseVec.empty()) {
1304 // Grab a record representing a case range to process off the worklist
1305 CaseRec CR = CaseVec.back();
1306 CaseVec.pop_back();
1307
1308 // Size is the number of Cases represented by this range. If Size is 1,
1309 // then we are processing a leaf of the binary search tree. Otherwise,
1310 // we need to pick a pivot, and push left and right ranges onto the
1311 // worklist.
1312 unsigned Size = CR.Range.second - CR.Range.first;
1313
1314 if (Size == 1) {
1315 // Create a CaseBlock record representing a conditional branch to
1316 // the Case's target mbb if the value being switched on SV is equal
1317 // to C. Otherwise, branch to default.
1318 Constant *C = CR.Range.first->first;
1319 MachineBasicBlock *Target = CR.Range.first->second;
1320 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1321 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001322
Nate Begemaned728c12006-03-27 01:32:24 +00001323 // If the MBB representing the leaf node is the current MBB, then just
1324 // call visitSwitchCase to emit the code into the current block.
1325 // Otherwise, push the CaseBlock onto the vector to be later processed
1326 // by SDISel, and insert the node's MBB before the next MBB.
1327 if (CR.CaseBB == CurMBB)
1328 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001329 else
Nate Begemaned728c12006-03-27 01:32:24 +00001330 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001331 } else {
1332 // split case range at pivot
1333 CaseItr Pivot = CR.Range.first + (Size / 2);
1334 CaseRange LHSR(CR.Range.first, Pivot);
1335 CaseRange RHSR(Pivot, CR.Range.second);
1336 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001337 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001338
Nate Begemaned728c12006-03-27 01:32:24 +00001339 // We know that we branch to the LHS if the Value being switched on is
1340 // less than the Pivot value, C. We use this to optimize our binary
1341 // tree a bit, by recognizing that if SV is greater than or equal to the
1342 // LHS's Case Value, and that Case Value is exactly one less than the
1343 // Pivot's Value, then we can branch directly to the LHS's Target,
1344 // rather than creating a leaf node for it.
1345 if ((LHSR.second - LHSR.first) == 1 &&
1346 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001347 cast<ConstantIntegral>(C)->getZExtValue() ==
1348 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001349 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001350 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001351 TrueBB = new MachineBasicBlock(LLVMBB);
1352 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1353 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001354 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001355
Nate Begemaned728c12006-03-27 01:32:24 +00001356 // Similar to the optimization above, if the Value being switched on is
1357 // known to be less than the Constant CR.LT, and the current Case Value
1358 // is CR.LT - 1, then we can branch directly to the target block for
1359 // the current Case Value, rather than emitting a RHS leaf node for it.
1360 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001361 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1362 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001363 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001364 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001365 FalseBB = new MachineBasicBlock(LLVMBB);
1366 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1367 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001368 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001369
Nate Begemaned728c12006-03-27 01:32:24 +00001370 // Create a CaseBlock record representing a conditional branch to
1371 // the LHS node if the value being switched on SV is less than C.
1372 // Otherwise, branch to LHS.
1373 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001374 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001375
Nate Begemaned728c12006-03-27 01:32:24 +00001376 if (CR.CaseBB == CurMBB)
1377 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001378 else
Nate Begemaned728c12006-03-27 01:32:24 +00001379 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001380 }
1381 }
1382}
1383
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001384void SelectionDAGLowering::visitSub(User &I) {
1385 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001386 if (I.getType()->isFloatingPoint()) {
1387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1388 if (CFP->isExactlyValue(-0.0)) {
1389 SDOperand Op2 = getValue(I.getOperand(1));
1390 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1391 return;
1392 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001393 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1394 } else
1395 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001396}
1397
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001398void
1399SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001400 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001401 SDOperand Op1 = getValue(I.getOperand(0));
1402 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001403
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001404 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001405 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1406 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1407 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001408 } else {
1409 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1410 }
1411}
1412
1413void
1414SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1415 const Type *Ty = I.getType();
1416 SDOperand Op1 = getValue(I.getOperand(0));
1417 SDOperand Op2 = getValue(I.getOperand(1));
1418
1419 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1420 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1421 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1422 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1423 } else {
1424 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001425 }
Nate Begeman127321b2005-11-18 07:42:56 +00001426}
Chris Lattner96c26752005-01-19 22:31:21 +00001427
Nate Begeman127321b2005-11-18 07:42:56 +00001428void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1429 SDOperand Op1 = getValue(I.getOperand(0));
1430 SDOperand Op2 = getValue(I.getOperand(1));
1431
1432 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1433
Chris Lattner7a60d912005-01-07 07:47:53 +00001434 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1435}
1436
1437void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001438 ISD::CondCode UnsignedOpcode,
1439 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001440 SDOperand Op1 = getValue(I.getOperand(0));
1441 SDOperand Op2 = getValue(I.getOperand(1));
1442 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001443 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001444 Opcode = FPOpcode;
1445 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001446 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001447 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001448}
1449
1450void SelectionDAGLowering::visitSelect(User &I) {
1451 SDOperand Cond = getValue(I.getOperand(0));
1452 SDOperand TrueVal = getValue(I.getOperand(1));
1453 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001454 if (!isa<PackedType>(I.getType())) {
1455 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1456 TrueVal, FalseVal));
1457 } else {
1458 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1459 *(TrueVal.Val->op_end()-2),
1460 *(TrueVal.Val->op_end()-1)));
1461 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001462}
1463
1464void SelectionDAGLowering::visitCast(User &I) {
1465 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001466 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001467 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001468
Chris Lattner2f4119a2006-03-22 20:09:35 +00001469 if (DestVT == MVT::Vector) {
1470 // This is a cast to a vector from something else. This is always a bit
1471 // convert. Get information about the input vector.
1472 const PackedType *DestTy = cast<PackedType>(I.getType());
1473 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1474 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1475 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1476 DAG.getValueType(EltVT)));
1477 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001478 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001479 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001480 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001481 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001482 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001483 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001484 } else if (isInteger(SrcVT)) {
1485 if (isInteger(DestVT)) { // Int -> Int cast
1486 if (DestVT < SrcVT) // Truncating cast?
1487 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001488 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001489 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001490 else
Chris Lattner4024c002006-03-15 22:19:46 +00001491 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001492 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001493 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001494 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001495 else
Chris Lattner4024c002006-03-15 22:19:46 +00001496 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001497 } else {
1498 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001499 }
Chris Lattner4024c002006-03-15 22:19:46 +00001500 } else if (isFloatingPoint(SrcVT)) {
1501 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1502 if (DestVT < SrcVT) // Rounding cast?
1503 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001504 else
Chris Lattner4024c002006-03-15 22:19:46 +00001505 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001506 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001507 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001508 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001509 else
Chris Lattner4024c002006-03-15 22:19:46 +00001510 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001511 } else {
1512 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001513 }
1514 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001515 assert(SrcVT == MVT::Vector && "Unknown cast!");
1516 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1517 // This is a cast from a vector to something else. This is always a bit
1518 // convert. Get information about the input vector.
1519 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001520 }
1521}
1522
Chris Lattner67271862006-03-29 00:11:43 +00001523void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001524 SDOperand InVec = getValue(I.getOperand(0));
1525 SDOperand InVal = getValue(I.getOperand(1));
1526 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1527 getValue(I.getOperand(2)));
1528
Chris Lattner29b23012006-03-19 01:17:20 +00001529 SDOperand Num = *(InVec.Val->op_end()-2);
1530 SDOperand Typ = *(InVec.Val->op_end()-1);
1531 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1532 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001533}
1534
Chris Lattner67271862006-03-29 00:11:43 +00001535void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001536 SDOperand InVec = getValue(I.getOperand(0));
1537 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1538 getValue(I.getOperand(1)));
1539 SDOperand Typ = *(InVec.Val->op_end()-1);
1540 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1541 TLI.getValueType(I.getType()), InVec, InIdx));
1542}
Chris Lattner32206f52006-03-18 01:44:44 +00001543
Chris Lattner098c01e2006-04-08 04:15:24 +00001544void SelectionDAGLowering::visitShuffleVector(User &I) {
1545 SDOperand V1 = getValue(I.getOperand(0));
1546 SDOperand V2 = getValue(I.getOperand(1));
1547 SDOperand Mask = getValue(I.getOperand(2));
1548
1549 SDOperand Num = *(V1.Val->op_end()-2);
1550 SDOperand Typ = *(V2.Val->op_end()-1);
1551 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1552 V1, V2, Mask, Num, Typ));
1553}
1554
1555
Chris Lattner7a60d912005-01-07 07:47:53 +00001556void SelectionDAGLowering::visitGetElementPtr(User &I) {
1557 SDOperand N = getValue(I.getOperand(0));
1558 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001559
1560 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1561 OI != E; ++OI) {
1562 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001563 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001564 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001565 if (Field) {
1566 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001567 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001568 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001569 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001570 }
1571 Ty = StTy->getElementType(Field);
1572 } else {
1573 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001574
Chris Lattner43535a12005-11-09 04:45:33 +00001575 // If this is a constant subscript, handle it quickly.
1576 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001577 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001578 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001579 if (CI->getType()->isSigned())
1580 Offs = (int64_t)
1581 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001582 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001583 Offs =
1584 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001585 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1586 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001587 }
Chris Lattner43535a12005-11-09 04:45:33 +00001588
1589 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001590 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001591 SDOperand IdxN = getValue(Idx);
1592
1593 // If the index is smaller or larger than intptr_t, truncate or extend
1594 // it.
1595 if (IdxN.getValueType() < N.getValueType()) {
1596 if (Idx->getType()->isSigned())
1597 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1598 else
1599 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1600 } else if (IdxN.getValueType() > N.getValueType())
1601 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1602
1603 // If this is a multiply by a power of two, turn it into a shl
1604 // immediately. This is a very common case.
1605 if (isPowerOf2_64(ElementSize)) {
1606 unsigned Amt = Log2_64(ElementSize);
1607 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001608 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001609 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1610 continue;
1611 }
1612
1613 SDOperand Scale = getIntPtrConstant(ElementSize);
1614 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1615 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001616 }
1617 }
1618 setValue(&I, N);
1619}
1620
1621void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1622 // If this is a fixed sized alloca in the entry block of the function,
1623 // allocate it statically on the stack.
1624 if (FuncInfo.StaticAllocaMap.count(&I))
1625 return; // getValue will auto-populate this.
1626
1627 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001628 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1629 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001630 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001631
1632 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001633 MVT::ValueType IntPtr = TLI.getPointerTy();
1634 if (IntPtr < AllocSize.getValueType())
1635 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1636 else if (IntPtr > AllocSize.getValueType())
1637 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001638
Chris Lattnereccb73d2005-01-22 23:04:37 +00001639 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001640 getIntPtrConstant(TySize));
1641
1642 // Handle alignment. If the requested alignment is less than or equal to the
1643 // stack alignment, ignore it and round the size of the allocation up to the
1644 // stack alignment size. If the size is greater than the stack alignment, we
1645 // note this in the DYNAMIC_STACKALLOC node.
1646 unsigned StackAlign =
1647 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1648 if (Align <= StackAlign) {
1649 Align = 0;
1650 // Add SA-1 to the size.
1651 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1652 getIntPtrConstant(StackAlign-1));
1653 // Mask out the low bits for alignment purposes.
1654 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1655 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1656 }
1657
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001658 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001659 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1660 MVT::Other);
1661 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001662 DAG.setRoot(setValue(&I, DSA).getValue(1));
1663
1664 // Inform the Frame Information that we have just allocated a variable-sized
1665 // object.
1666 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1667}
1668
Chris Lattner7a60d912005-01-07 07:47:53 +00001669void SelectionDAGLowering::visitLoad(LoadInst &I) {
1670 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001671
Chris Lattner4d9651c2005-01-17 22:19:26 +00001672 SDOperand Root;
1673 if (I.isVolatile())
1674 Root = getRoot();
1675 else {
1676 // Do not serialize non-volatile loads against each other.
1677 Root = DAG.getRoot();
1678 }
Chris Lattner4024c002006-03-15 22:19:46 +00001679
Evan Chenge71fe34d2006-10-09 20:57:25 +00001680 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001681 Root, I.isVolatile()));
1682}
1683
1684SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001685 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001686 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001687 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001688 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001689 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001690 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1691 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001692 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001693 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001694 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001695
Chris Lattner4024c002006-03-15 22:19:46 +00001696 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001697 DAG.setRoot(L.getValue(1));
1698 else
1699 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001700
1701 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001702}
1703
1704
1705void SelectionDAGLowering::visitStore(StoreInst &I) {
1706 Value *SrcV = I.getOperand(0);
1707 SDOperand Src = getValue(SrcV);
1708 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001709 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1710 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001711}
1712
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001713/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1714/// access memory and has no other side effects at all.
1715static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1716#define GET_NO_MEMORY_INTRINSICS
1717#include "llvm/Intrinsics.gen"
1718#undef GET_NO_MEMORY_INTRINSICS
1719 return false;
1720}
1721
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001722// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1723// have any side-effects or if it only reads memory.
1724static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1725#define GET_SIDE_EFFECT_INFO
1726#include "llvm/Intrinsics.gen"
1727#undef GET_SIDE_EFFECT_INFO
1728 return false;
1729}
1730
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001731/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1732/// node.
1733void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1734 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001735 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001736 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001737
1738 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001739 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001740 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1741 if (OnlyLoad) {
1742 // We don't need to serialize loads against other loads.
1743 Ops.push_back(DAG.getRoot());
1744 } else {
1745 Ops.push_back(getRoot());
1746 }
1747 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001748
1749 // Add the intrinsic ID as an integer operand.
1750 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1751
1752 // Add all operands of the call to the operand list.
1753 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1754 SDOperand Op = getValue(I.getOperand(i));
1755
1756 // If this is a vector type, force it to the right packed type.
1757 if (Op.getValueType() == MVT::Vector) {
1758 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1759 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1760
1761 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1762 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1763 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1764 }
1765
1766 assert(TLI.isTypeLegal(Op.getValueType()) &&
1767 "Intrinsic uses a non-legal type?");
1768 Ops.push_back(Op);
1769 }
1770
1771 std::vector<MVT::ValueType> VTs;
1772 if (I.getType() != Type::VoidTy) {
1773 MVT::ValueType VT = TLI.getValueType(I.getType());
1774 if (VT == MVT::Vector) {
1775 const PackedType *DestTy = cast<PackedType>(I.getType());
1776 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1777
1778 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1779 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1780 }
1781
1782 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1783 VTs.push_back(VT);
1784 }
1785 if (HasChain)
1786 VTs.push_back(MVT::Other);
1787
Chris Lattnerbd887772006-08-14 23:53:35 +00001788 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1789
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001790 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001791 SDOperand Result;
1792 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001793 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1794 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001795 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001796 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1797 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001798 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001799 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1800 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001801
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001802 if (HasChain) {
1803 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1804 if (OnlyLoad)
1805 PendingLoads.push_back(Chain);
1806 else
1807 DAG.setRoot(Chain);
1808 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001809 if (I.getType() != Type::VoidTy) {
1810 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1811 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1812 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1813 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1814 DAG.getValueType(EVT));
1815 }
1816 setValue(&I, Result);
1817 }
1818}
1819
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001820/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1821/// we want to emit this as a call to a named external function, return the name
1822/// otherwise lower it and return null.
1823const char *
1824SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1825 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001826 default:
1827 // By default, turn this into a target intrinsic node.
1828 visitTargetIntrinsic(I, Intrinsic);
1829 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001830 case Intrinsic::vastart: visitVAStart(I); return 0;
1831 case Intrinsic::vaend: visitVAEnd(I); return 0;
1832 case Intrinsic::vacopy: visitVACopy(I); return 0;
1833 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1834 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1835 case Intrinsic::setjmp:
1836 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1837 break;
1838 case Intrinsic::longjmp:
1839 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1840 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001841 case Intrinsic::memcpy_i32:
1842 case Intrinsic::memcpy_i64:
1843 visitMemIntrinsic(I, ISD::MEMCPY);
1844 return 0;
1845 case Intrinsic::memset_i32:
1846 case Intrinsic::memset_i64:
1847 visitMemIntrinsic(I, ISD::MEMSET);
1848 return 0;
1849 case Intrinsic::memmove_i32:
1850 case Intrinsic::memmove_i64:
1851 visitMemIntrinsic(I, ISD::MEMMOVE);
1852 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001853
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001854 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001855 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001856 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001857 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001858 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001859
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001860 Ops[0] = getRoot();
1861 Ops[1] = getValue(SPI.getLineValue());
1862 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001863
Jim Laskeya8bdac82006-03-23 18:06:46 +00001864 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001865 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001866 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1867
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001868 Ops[3] = DAG.getString(CompileUnit->getFileName());
1869 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001870
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001871 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001872 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001873
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001874 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001875 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001876 case Intrinsic::dbg_region_start: {
1877 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1878 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001879 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001880 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001881 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1882 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001883 }
1884
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001885 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001886 }
1887 case Intrinsic::dbg_region_end: {
1888 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1889 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001890 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001891 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001892 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1893 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001894 }
1895
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001896 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001897 }
1898 case Intrinsic::dbg_func_start: {
1899 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1900 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001901 if (DebugInfo && FSI.getSubprogram() &&
1902 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001903 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001904 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1905 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001906 }
1907
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001908 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001909 }
1910 case Intrinsic::dbg_declare: {
1911 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1912 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001913 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001914 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001915 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001916 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001917 }
1918
1919 return 0;
1920 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001921
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001922 case Intrinsic::isunordered_f32:
1923 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001924 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1925 getValue(I.getOperand(2)), ISD::SETUO));
1926 return 0;
1927
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001928 case Intrinsic::sqrt_f32:
1929 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001930 setValue(&I, DAG.getNode(ISD::FSQRT,
1931 getValue(I.getOperand(1)).getValueType(),
1932 getValue(I.getOperand(1))));
1933 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001934 case Intrinsic::powi_f32:
1935 case Intrinsic::powi_f64:
1936 setValue(&I, DAG.getNode(ISD::FPOWI,
1937 getValue(I.getOperand(1)).getValueType(),
1938 getValue(I.getOperand(1)),
1939 getValue(I.getOperand(2))));
1940 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001941 case Intrinsic::pcmarker: {
1942 SDOperand Tmp = getValue(I.getOperand(1));
1943 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1944 return 0;
1945 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001946 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001947 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001948 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1949 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1950 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001951 setValue(&I, Tmp);
1952 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001953 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001954 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001955 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001956 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001957 case Intrinsic::bswap_i64:
1958 setValue(&I, DAG.getNode(ISD::BSWAP,
1959 getValue(I.getOperand(1)).getValueType(),
1960 getValue(I.getOperand(1))));
1961 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001962 case Intrinsic::cttz_i8:
1963 case Intrinsic::cttz_i16:
1964 case Intrinsic::cttz_i32:
1965 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001966 setValue(&I, DAG.getNode(ISD::CTTZ,
1967 getValue(I.getOperand(1)).getValueType(),
1968 getValue(I.getOperand(1))));
1969 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001970 case Intrinsic::ctlz_i8:
1971 case Intrinsic::ctlz_i16:
1972 case Intrinsic::ctlz_i32:
1973 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001974 setValue(&I, DAG.getNode(ISD::CTLZ,
1975 getValue(I.getOperand(1)).getValueType(),
1976 getValue(I.getOperand(1))));
1977 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001978 case Intrinsic::ctpop_i8:
1979 case Intrinsic::ctpop_i16:
1980 case Intrinsic::ctpop_i32:
1981 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001982 setValue(&I, DAG.getNode(ISD::CTPOP,
1983 getValue(I.getOperand(1)).getValueType(),
1984 getValue(I.getOperand(1))));
1985 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001986 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001987 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001988 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1989 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001990 setValue(&I, Tmp);
1991 DAG.setRoot(Tmp.getValue(1));
1992 return 0;
1993 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001994 case Intrinsic::stackrestore: {
1995 SDOperand Tmp = getValue(I.getOperand(1));
1996 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001997 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001998 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001999 case Intrinsic::prefetch:
2000 // FIXME: Currently discarding prefetches.
2001 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002002 }
2003}
2004
2005
Chris Lattner7a60d912005-01-07 07:47:53 +00002006void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002007 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002008 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00002009 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002010 if (unsigned IID = F->getIntrinsicID()) {
2011 RenameFn = visitIntrinsicCall(I, IID);
2012 if (!RenameFn)
2013 return;
2014 } else { // Not an LLVM intrinsic.
2015 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002016 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2017 if (I.getNumOperands() == 3 && // Basic sanity checks.
2018 I.getOperand(1)->getType()->isFloatingPoint() &&
2019 I.getType() == I.getOperand(1)->getType() &&
2020 I.getType() == I.getOperand(2)->getType()) {
2021 SDOperand LHS = getValue(I.getOperand(1));
2022 SDOperand RHS = getValue(I.getOperand(2));
2023 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2024 LHS, RHS));
2025 return;
2026 }
2027 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002028 if (I.getNumOperands() == 2 && // Basic sanity checks.
2029 I.getOperand(1)->getType()->isFloatingPoint() &&
2030 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002031 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002032 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2033 return;
2034 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002035 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002036 if (I.getNumOperands() == 2 && // Basic sanity checks.
2037 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002038 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002039 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002040 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2041 return;
2042 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002043 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002044 if (I.getNumOperands() == 2 && // Basic sanity checks.
2045 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002046 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002047 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002048 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2049 return;
2050 }
2051 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002052 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002053 } else if (isa<InlineAsm>(I.getOperand(0))) {
2054 visitInlineAsm(I);
2055 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002056 }
Misha Brukman835702a2005-04-21 22:36:52 +00002057
Chris Lattner18d2b342005-01-08 22:48:57 +00002058 SDOperand Callee;
2059 if (!RenameFn)
2060 Callee = getValue(I.getOperand(0));
2061 else
2062 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002063 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002064 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002065 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2066 Value *Arg = I.getOperand(i);
2067 SDOperand ArgNode = getValue(Arg);
2068 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2069 }
Misha Brukman835702a2005-04-21 22:36:52 +00002070
Nate Begemanf6565252005-03-26 01:29:23 +00002071 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2072 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002073
Chris Lattner1f45cd72005-01-08 19:26:18 +00002074 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002075 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002076 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002077 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002078 setValue(&I, Result.first);
2079 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002080}
2081
Chris Lattner6f87d182006-02-22 22:37:12 +00002082SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002083 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002084 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2085 Chain = Val.getValue(1);
2086 Flag = Val.getValue(2);
2087
2088 // If the result was expanded, copy from the top part.
2089 if (Regs.size() > 1) {
2090 assert(Regs.size() == 2 &&
2091 "Cannot expand to more than 2 elts yet!");
2092 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002093 Chain = Hi.getValue(1);
2094 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002095 if (DAG.getTargetLoweringInfo().isLittleEndian())
2096 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2097 else
2098 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002099 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002100
Chris Lattner705948d2006-06-08 18:22:48 +00002101 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002102 // appropriate type.
2103 if (RegVT == ValueVT)
2104 return Val;
2105
Chris Lattner705948d2006-06-08 18:22:48 +00002106 if (MVT::isInteger(RegVT)) {
2107 if (ValueVT < RegVT)
2108 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2109 else
2110 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2111 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002112 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002113 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002114}
2115
Chris Lattner571d9642006-02-23 19:21:04 +00002116/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2117/// specified value into the registers specified by this object. This uses
2118/// Chain/Flag as the input and updates them for the output Chain/Flag.
2119void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002120 SDOperand &Chain, SDOperand &Flag,
2121 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002122 if (Regs.size() == 1) {
2123 // If there is a single register and the types differ, this must be
2124 // a promotion.
2125 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002126 if (MVT::isInteger(RegVT)) {
2127 if (RegVT < ValueVT)
2128 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2129 else
2130 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2131 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002132 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2133 }
2134 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2135 Flag = Chain.getValue(1);
2136 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002137 std::vector<unsigned> R(Regs);
2138 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2139 std::reverse(R.begin(), R.end());
2140
2141 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002142 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002143 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002144 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002145 Flag = Chain.getValue(1);
2146 }
2147 }
2148}
Chris Lattner6f87d182006-02-22 22:37:12 +00002149
Chris Lattner571d9642006-02-23 19:21:04 +00002150/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2151/// operand list. This adds the code marker and includes the number of
2152/// values added into it.
2153void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002154 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002155 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2156 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2157 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2158}
Chris Lattner6f87d182006-02-22 22:37:12 +00002159
2160/// isAllocatableRegister - If the specified register is safe to allocate,
2161/// i.e. it isn't a stack pointer or some other special register, return the
2162/// register class for the register. Otherwise, return null.
2163static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002164isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2165 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002166 MVT::ValueType FoundVT = MVT::Other;
2167 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002168 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2169 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002170 MVT::ValueType ThisVT = MVT::Other;
2171
Chris Lattnerb1124f32006-02-22 23:09:03 +00002172 const TargetRegisterClass *RC = *RCI;
2173 // If none of the the value types for this register class are valid, we
2174 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002175 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2176 I != E; ++I) {
2177 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002178 // If we have already found this register in a different register class,
2179 // choose the one with the largest VT specified. For example, on
2180 // PowerPC, we favor f64 register classes over f32.
2181 if (FoundVT == MVT::Other ||
2182 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2183 ThisVT = *I;
2184 break;
2185 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002186 }
2187 }
2188
Chris Lattnerbec582f2006-04-02 00:24:45 +00002189 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002190
Chris Lattner6f87d182006-02-22 22:37:12 +00002191 // NOTE: This isn't ideal. In particular, this might allocate the
2192 // frame pointer in functions that need it (due to them not being taken
2193 // out of allocation, because a variable sized allocation hasn't been seen
2194 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002195 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2196 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002197 if (*I == Reg) {
2198 // We found a matching register class. Keep looking at others in case
2199 // we find one with larger registers that this physreg is also in.
2200 FoundRC = RC;
2201 FoundVT = ThisVT;
2202 break;
2203 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002204 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002205 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002206}
2207
2208RegsForValue SelectionDAGLowering::
2209GetRegistersForValue(const std::string &ConstrCode,
2210 MVT::ValueType VT, bool isOutReg, bool isInReg,
2211 std::set<unsigned> &OutputRegs,
2212 std::set<unsigned> &InputRegs) {
2213 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2214 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2215 std::vector<unsigned> Regs;
2216
2217 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2218 MVT::ValueType RegVT;
2219 MVT::ValueType ValueVT = VT;
2220
2221 if (PhysReg.first) {
2222 if (VT == MVT::Other)
2223 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002224
2225 // Get the actual register value type. This is important, because the user
2226 // may have asked for (e.g.) the AX register in i32 type. We need to
2227 // remember that AX is actually i16 to get the right extension.
2228 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002229
2230 // This is a explicit reference to a physical register.
2231 Regs.push_back(PhysReg.first);
2232
2233 // If this is an expanded reference, add the rest of the regs to Regs.
2234 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002235 TargetRegisterClass::iterator I = PhysReg.second->begin();
2236 TargetRegisterClass::iterator E = PhysReg.second->end();
2237 for (; *I != PhysReg.first; ++I)
2238 assert(I != E && "Didn't find reg!");
2239
2240 // Already added the first reg.
2241 --NumRegs; ++I;
2242 for (; NumRegs; --NumRegs, ++I) {
2243 assert(I != E && "Ran out of registers to allocate!");
2244 Regs.push_back(*I);
2245 }
2246 }
2247 return RegsForValue(Regs, RegVT, ValueVT);
2248 }
2249
2250 // This is a reference to a register class. Allocate NumRegs consecutive,
2251 // available, registers from the class.
2252 std::vector<unsigned> RegClassRegs =
2253 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2254
2255 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2256 MachineFunction &MF = *CurMBB->getParent();
2257 unsigned NumAllocated = 0;
2258 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2259 unsigned Reg = RegClassRegs[i];
2260 // See if this register is available.
2261 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2262 (isInReg && InputRegs.count(Reg))) { // Already used.
2263 // Make sure we find consecutive registers.
2264 NumAllocated = 0;
2265 continue;
2266 }
2267
2268 // Check to see if this register is allocatable (i.e. don't give out the
2269 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002270 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002271 if (!RC) {
2272 // Make sure we find consecutive registers.
2273 NumAllocated = 0;
2274 continue;
2275 }
2276
2277 // Okay, this register is good, we can use it.
2278 ++NumAllocated;
2279
2280 // If we allocated enough consecutive
2281 if (NumAllocated == NumRegs) {
2282 unsigned RegStart = (i-NumAllocated)+1;
2283 unsigned RegEnd = i+1;
2284 // Mark all of the allocated registers used.
2285 for (unsigned i = RegStart; i != RegEnd; ++i) {
2286 unsigned Reg = RegClassRegs[i];
2287 Regs.push_back(Reg);
2288 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2289 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2290 }
2291
2292 return RegsForValue(Regs, *RC->vt_begin(), VT);
2293 }
2294 }
2295
2296 // Otherwise, we couldn't allocate enough registers for this.
2297 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002298}
2299
Chris Lattner6f87d182006-02-22 22:37:12 +00002300
Chris Lattner476e67b2006-01-26 22:24:51 +00002301/// visitInlineAsm - Handle a call to an InlineAsm object.
2302///
2303void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2304 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2305
2306 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2307 MVT::Other);
2308
2309 // Note, we treat inline asms both with and without side-effects as the same.
2310 // If an inline asm doesn't have side effects and doesn't access memory, we
2311 // could not choose to not chain it.
2312 bool hasSideEffects = IA->hasSideEffects();
2313
Chris Lattner3a5ed552006-02-01 01:28:23 +00002314 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002315 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002316
2317 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2318 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2319 /// if it is a def of that register.
2320 std::vector<SDOperand> AsmNodeOperands;
2321 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2322 AsmNodeOperands.push_back(AsmStr);
2323
2324 SDOperand Chain = getRoot();
2325 SDOperand Flag;
2326
Chris Lattner1558fc62006-02-01 18:59:47 +00002327 // We fully assign registers here at isel time. This is not optimal, but
2328 // should work. For register classes that correspond to LLVM classes, we
2329 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2330 // over the constraints, collecting fixed registers that we know we can't use.
2331 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002332 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002333 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2334 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2335 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002336
Chris Lattner7ad77df2006-02-22 00:56:39 +00002337 MVT::ValueType OpVT;
2338
2339 // Compute the value type for each operand and add it to ConstraintVTs.
2340 switch (Constraints[i].Type) {
2341 case InlineAsm::isOutput:
2342 if (!Constraints[i].isIndirectOutput) {
2343 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2344 OpVT = TLI.getValueType(I.getType());
2345 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002346 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002347 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2348 OpNum++; // Consumes a call operand.
2349 }
2350 break;
2351 case InlineAsm::isInput:
2352 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2353 OpNum++; // Consumes a call operand.
2354 break;
2355 case InlineAsm::isClobber:
2356 OpVT = MVT::Other;
2357 break;
2358 }
2359
2360 ConstraintVTs.push_back(OpVT);
2361
Chris Lattner6f87d182006-02-22 22:37:12 +00002362 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2363 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002364
Chris Lattner6f87d182006-02-22 22:37:12 +00002365 // Build a list of regs that this operand uses. This always has a single
2366 // element for promoted/expanded operands.
2367 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2368 false, false,
2369 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002370
2371 switch (Constraints[i].Type) {
2372 case InlineAsm::isOutput:
2373 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002374 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002375 // If this is an early-clobber output, it cannot be assigned to the same
2376 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002377 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002378 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002379 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002380 case InlineAsm::isInput:
2381 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002382 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002383 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002384 case InlineAsm::isClobber:
2385 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002386 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2387 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002388 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002389 }
2390 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002391
Chris Lattner5c79f982006-02-21 23:12:12 +00002392 // Loop over all of the inputs, copying the operand values into the
2393 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002394 RegsForValue RetValRegs;
2395 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002396 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002397
Chris Lattner2e56e892006-01-31 02:03:41 +00002398 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002399 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2400 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002401
Chris Lattner3a5ed552006-02-01 01:28:23 +00002402 switch (Constraints[i].Type) {
2403 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002404 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2405 if (ConstraintCode.size() == 1) // not a physreg name.
2406 CTy = TLI.getConstraintType(ConstraintCode[0]);
2407
2408 if (CTy == TargetLowering::C_Memory) {
2409 // Memory output.
2410 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2411
2412 // Check that the operand (the address to store to) isn't a float.
2413 if (!MVT::isInteger(InOperandVal.getValueType()))
2414 assert(0 && "MATCH FAIL!");
2415
2416 if (!Constraints[i].isIndirectOutput)
2417 assert(0 && "MATCH FAIL!");
2418
2419 OpNum++; // Consumes a call operand.
2420
2421 // Extend/truncate to the right pointer type if needed.
2422 MVT::ValueType PtrType = TLI.getPointerTy();
2423 if (InOperandVal.getValueType() < PtrType)
2424 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2425 else if (InOperandVal.getValueType() > PtrType)
2426 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2427
2428 // Add information to the INLINEASM node to know about this output.
2429 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2430 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2431 AsmNodeOperands.push_back(InOperandVal);
2432 break;
2433 }
2434
2435 // Otherwise, this is a register output.
2436 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2437
Chris Lattner6f87d182006-02-22 22:37:12 +00002438 // If this is an early-clobber output, or if there is an input
2439 // constraint that matches this, we need to reserve the input register
2440 // so no other inputs allocate to it.
2441 bool UsesInputRegister = false;
2442 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2443 UsesInputRegister = true;
2444
2445 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002446 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002447 RegsForValue Regs =
2448 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2449 true, UsesInputRegister,
2450 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002451 if (Regs.Regs.empty()) {
2452 std::cerr << "Couldn't allocate output reg for contraint '"
2453 << ConstraintCode << "'!\n";
2454 exit(1);
2455 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002456
Chris Lattner3a5ed552006-02-01 01:28:23 +00002457 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002458 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002459 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002460 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002461 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002462 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002463 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2464 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002465 OpNum++; // Consumes a call operand.
2466 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002467
2468 // Add information to the INLINEASM node to know that this register is
2469 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002470 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002471 break;
2472 }
2473 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002474 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002475 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002476
Chris Lattner7f5880b2006-02-02 00:25:23 +00002477 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2478 // If this is required to match an output register we have already set,
2479 // just use its register.
2480 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002481
Chris Lattner571d9642006-02-23 19:21:04 +00002482 // Scan until we find the definition we already emitted of this operand.
2483 // When we find it, create a RegsForValue operand.
2484 unsigned CurOp = 2; // The first operand.
2485 for (; OperandNo; --OperandNo) {
2486 // Advance to the next operand.
2487 unsigned NumOps =
2488 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002489 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2490 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002491 "Skipped past definitions?");
2492 CurOp += (NumOps>>3)+1;
2493 }
2494
2495 unsigned NumOps =
2496 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2497 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2498 "Skipped past definitions?");
2499
2500 // Add NumOps>>3 registers to MatchedRegs.
2501 RegsForValue MatchedRegs;
2502 MatchedRegs.ValueVT = InOperandVal.getValueType();
2503 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2504 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2505 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2506 MatchedRegs.Regs.push_back(Reg);
2507 }
2508
2509 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002510 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2511 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002512 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002513 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002514 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002515
2516 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2517 if (ConstraintCode.size() == 1) // not a physreg name.
2518 CTy = TLI.getConstraintType(ConstraintCode[0]);
2519
2520 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002521 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2522 ConstraintCode[0], DAG);
2523 if (!InOperandVal.Val) {
2524 std::cerr << "Invalid operand for inline asm constraint '"
2525 << ConstraintCode << "'!\n";
2526 exit(1);
2527 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002528
2529 // Add information to the INLINEASM node to know about this input.
2530 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2531 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2532 AsmNodeOperands.push_back(InOperandVal);
2533 break;
2534 } else if (CTy == TargetLowering::C_Memory) {
2535 // Memory input.
2536
2537 // Check that the operand isn't a float.
2538 if (!MVT::isInteger(InOperandVal.getValueType()))
2539 assert(0 && "MATCH FAIL!");
2540
2541 // Extend/truncate to the right pointer type if needed.
2542 MVT::ValueType PtrType = TLI.getPointerTy();
2543 if (InOperandVal.getValueType() < PtrType)
2544 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2545 else if (InOperandVal.getValueType() > PtrType)
2546 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2547
2548 // Add information to the INLINEASM node to know about this input.
2549 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2550 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2551 AsmNodeOperands.push_back(InOperandVal);
2552 break;
2553 }
2554
2555 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2556
2557 // Copy the input into the appropriate registers.
2558 RegsForValue InRegs =
2559 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2560 false, true, OutputRegs, InputRegs);
2561 // FIXME: should be match fail.
2562 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2563
Evan Chengef9e07d2006-06-15 08:11:54 +00002564 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002565
2566 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002567 break;
2568 }
Chris Lattner571d9642006-02-23 19:21:04 +00002569 case InlineAsm::isClobber: {
2570 RegsForValue ClobberedRegs =
2571 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2572 OutputRegs, InputRegs);
2573 // Add the clobbered value to the operand list, so that the register
2574 // allocator is aware that the physreg got clobbered.
2575 if (!ClobberedRegs.Regs.empty())
2576 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002577 break;
2578 }
Chris Lattner571d9642006-02-23 19:21:04 +00002579 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002580 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002581
2582 // Finish up input operands.
2583 AsmNodeOperands[0] = Chain;
2584 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2585
Chris Lattnerbd887772006-08-14 23:53:35 +00002586 Chain = DAG.getNode(ISD::INLINEASM,
2587 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002588 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002589 Flag = Chain.getValue(1);
2590
Chris Lattner2e56e892006-01-31 02:03:41 +00002591 // If this asm returns a register value, copy the result from that register
2592 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002593 if (!RetValRegs.Regs.empty())
2594 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002595
Chris Lattner2e56e892006-01-31 02:03:41 +00002596 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2597
2598 // Process indirect outputs, first output all of the flagged copies out of
2599 // physregs.
2600 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002601 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002602 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002603 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2604 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002605 }
2606
2607 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002608 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002609 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002610 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002611 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002612 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002613 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002614 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2615 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002616 DAG.setRoot(Chain);
2617}
2618
2619
Chris Lattner7a60d912005-01-07 07:47:53 +00002620void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2621 SDOperand Src = getValue(I.getOperand(0));
2622
2623 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002624
2625 if (IntPtr < Src.getValueType())
2626 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2627 else if (IntPtr > Src.getValueType())
2628 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002629
2630 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002631 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002632 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2633 Src, getIntPtrConstant(ElementSize));
2634
2635 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002636 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002637
2638 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002639 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002640 DAG.getExternalSymbol("malloc", IntPtr),
2641 Args, DAG);
2642 setValue(&I, Result.first); // Pointers always fit in registers
2643 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002644}
2645
2646void SelectionDAGLowering::visitFree(FreeInst &I) {
2647 std::vector<std::pair<SDOperand, const Type*> > Args;
2648 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002649 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002650 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002651 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002652 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002653 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2654 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002655}
2656
Chris Lattner13d7c252005-08-26 20:54:47 +00002657// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2658// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2659// instructions are special in various ways, which require special support to
2660// insert. The specified MachineInstr is created but not inserted into any
2661// basic blocks, and the scheduler passes ownership of it to this method.
2662MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2663 MachineBasicBlock *MBB) {
2664 std::cerr << "If a target marks an instruction with "
2665 "'usesCustomDAGSchedInserter', it must implement "
2666 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2667 abort();
2668 return 0;
2669}
2670
Chris Lattner58cfd792005-01-09 00:00:49 +00002671void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002672 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2673 getValue(I.getOperand(1)),
2674 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002675}
2676
2677void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002678 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2679 getValue(I.getOperand(0)),
2680 DAG.getSrcValue(I.getOperand(0)));
2681 setValue(&I, V);
2682 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002683}
2684
2685void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002686 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2687 getValue(I.getOperand(1)),
2688 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002689}
2690
2691void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002692 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2693 getValue(I.getOperand(1)),
2694 getValue(I.getOperand(2)),
2695 DAG.getSrcValue(I.getOperand(1)),
2696 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002697}
2698
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002699/// TargetLowering::LowerArguments - This is the default LowerArguments
2700/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002701/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2702/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002703std::vector<SDOperand>
2704TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2705 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2706 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002707 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002708 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2709 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2710
2711 // Add one result value for each formal argument.
2712 std::vector<MVT::ValueType> RetVals;
2713 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2714 MVT::ValueType VT = getValueType(I->getType());
2715
2716 switch (getTypeAction(VT)) {
2717 default: assert(0 && "Unknown type action!");
2718 case Legal:
2719 RetVals.push_back(VT);
2720 break;
2721 case Promote:
2722 RetVals.push_back(getTypeToTransformTo(VT));
2723 break;
2724 case Expand:
2725 if (VT != MVT::Vector) {
2726 // If this is a large integer, it needs to be broken up into small
2727 // integers. Figure out what the destination type is and how many small
2728 // integers it turns into.
2729 MVT::ValueType NVT = getTypeToTransformTo(VT);
2730 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2731 for (unsigned i = 0; i != NumVals; ++i)
2732 RetVals.push_back(NVT);
2733 } else {
2734 // Otherwise, this is a vector type. We only support legal vectors
2735 // right now.
2736 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2737 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002738
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002739 // Figure out if there is a Packed type corresponding to this Vector
2740 // type. If so, convert to the packed type.
2741 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2742 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2743 RetVals.push_back(TVT);
2744 } else {
2745 assert(0 && "Don't support illegal by-val vector arguments yet!");
2746 }
2747 }
2748 break;
2749 }
2750 }
Evan Cheng9618df12006-04-25 23:03:35 +00002751
Chris Lattner3d826992006-05-16 06:45:34 +00002752 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002753
2754 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002755 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2756 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002757 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002758
2759 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002760
2761 // Set up the return result vector.
2762 Ops.clear();
2763 unsigned i = 0;
2764 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2765 MVT::ValueType VT = getValueType(I->getType());
2766
2767 switch (getTypeAction(VT)) {
2768 default: assert(0 && "Unknown type action!");
2769 case Legal:
2770 Ops.push_back(SDOperand(Result, i++));
2771 break;
2772 case Promote: {
2773 SDOperand Op(Result, i++);
2774 if (MVT::isInteger(VT)) {
2775 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2776 : ISD::AssertZext;
2777 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2778 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2779 } else {
2780 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2781 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2782 }
2783 Ops.push_back(Op);
2784 break;
2785 }
2786 case Expand:
2787 if (VT != MVT::Vector) {
2788 // If this is a large integer, it needs to be reassembled from small
2789 // integers. Figure out what the source elt type is and how many small
2790 // integers it is.
2791 MVT::ValueType NVT = getTypeToTransformTo(VT);
2792 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2793 if (NumVals == 2) {
2794 SDOperand Lo = SDOperand(Result, i++);
2795 SDOperand Hi = SDOperand(Result, i++);
2796
2797 if (!isLittleEndian())
2798 std::swap(Lo, Hi);
2799
2800 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2801 } else {
2802 // Value scalarized into many values. Unimp for now.
2803 assert(0 && "Cannot expand i64 -> i16 yet!");
2804 }
2805 } else {
2806 // Otherwise, this is a vector type. We only support legal vectors
2807 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002808 const PackedType *PTy = cast<PackedType>(I->getType());
2809 unsigned NumElems = PTy->getNumElements();
2810 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002811
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002812 // Figure out if there is a Packed type corresponding to this Vector
2813 // type. If so, convert to the packed type.
2814 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002815 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002816 SDOperand N = SDOperand(Result, i++);
2817 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002818 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2819 DAG.getConstant(NumElems, MVT::i32),
2820 DAG.getValueType(getValueType(EltTy)));
2821 Ops.push_back(N);
2822 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002823 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002824 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002825 }
2826 }
2827 break;
2828 }
2829 }
2830 return Ops;
2831}
2832
Chris Lattneraaa23d92006-05-16 22:53:20 +00002833
2834/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2835/// implementation, which just inserts an ISD::CALL node, which is later custom
2836/// lowered by the target to something concrete. FIXME: When all targets are
2837/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2838std::pair<SDOperand, SDOperand>
2839TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2840 unsigned CallingConv, bool isTailCall,
2841 SDOperand Callee,
2842 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002843 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002844 Ops.push_back(Chain); // Op#0 - Chain
2845 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2846 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2847 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2848 Ops.push_back(Callee);
2849
2850 // Handle all of the outgoing arguments.
2851 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2852 MVT::ValueType VT = getValueType(Args[i].second);
2853 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002854 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002855 switch (getTypeAction(VT)) {
2856 default: assert(0 && "Unknown type action!");
2857 case Legal:
2858 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002859 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002860 break;
2861 case Promote:
2862 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002863 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002864 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2865 } else {
2866 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2867 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2868 }
2869 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002870 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002871 break;
2872 case Expand:
2873 if (VT != MVT::Vector) {
2874 // If this is a large integer, it needs to be broken down into small
2875 // integers. Figure out what the source elt type is and how many small
2876 // integers it is.
2877 MVT::ValueType NVT = getTypeToTransformTo(VT);
2878 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2879 if (NumVals == 2) {
2880 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2881 DAG.getConstant(0, getPointerTy()));
2882 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2883 DAG.getConstant(1, getPointerTy()));
2884 if (!isLittleEndian())
2885 std::swap(Lo, Hi);
2886
2887 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002888 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002889 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002890 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002891 } else {
2892 // Value scalarized into many values. Unimp for now.
2893 assert(0 && "Cannot expand i64 -> i16 yet!");
2894 }
2895 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002896 // Otherwise, this is a vector type. We only support legal vectors
2897 // right now.
2898 const PackedType *PTy = cast<PackedType>(Args[i].second);
2899 unsigned NumElems = PTy->getNumElements();
2900 const Type *EltTy = PTy->getElementType();
2901
2902 // Figure out if there is a Packed type corresponding to this Vector
2903 // type. If so, convert to the packed type.
2904 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002905 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2906 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2907 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2908 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002909 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002910 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002911 assert(0 && "Don't support illegal by-val vector call args yet!");
2912 abort();
2913 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002914 }
2915 break;
2916 }
2917 }
2918
2919 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002920 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002921
2922 if (RetTy != Type::VoidTy) {
2923 MVT::ValueType VT = getValueType(RetTy);
2924 switch (getTypeAction(VT)) {
2925 default: assert(0 && "Unknown type action!");
2926 case Legal:
2927 RetTys.push_back(VT);
2928 break;
2929 case Promote:
2930 RetTys.push_back(getTypeToTransformTo(VT));
2931 break;
2932 case Expand:
2933 if (VT != MVT::Vector) {
2934 // If this is a large integer, it needs to be reassembled from small
2935 // integers. Figure out what the source elt type is and how many small
2936 // integers it is.
2937 MVT::ValueType NVT = getTypeToTransformTo(VT);
2938 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2939 for (unsigned i = 0; i != NumVals; ++i)
2940 RetTys.push_back(NVT);
2941 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002942 // Otherwise, this is a vector type. We only support legal vectors
2943 // right now.
2944 const PackedType *PTy = cast<PackedType>(RetTy);
2945 unsigned NumElems = PTy->getNumElements();
2946 const Type *EltTy = PTy->getElementType();
2947
2948 // Figure out if there is a Packed type corresponding to this Vector
2949 // type. If so, convert to the packed type.
2950 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2951 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2952 RetTys.push_back(TVT);
2953 } else {
2954 assert(0 && "Don't support illegal by-val vector call results yet!");
2955 abort();
2956 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002957 }
2958 }
2959 }
2960
2961 RetTys.push_back(MVT::Other); // Always has a chain.
2962
2963 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002964 SDOperand Res = DAG.getNode(ISD::CALL,
2965 DAG.getVTList(&RetTys[0], RetTys.size()),
2966 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002967
2968 // This returns a pair of operands. The first element is the
2969 // return value for the function (if RetTy is not VoidTy). The second
2970 // element is the outgoing token chain.
2971 SDOperand ResVal;
2972 if (RetTys.size() != 1) {
2973 MVT::ValueType VT = getValueType(RetTy);
2974 if (RetTys.size() == 2) {
2975 ResVal = Res;
2976
2977 // If this value was promoted, truncate it down.
2978 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002979 if (VT == MVT::Vector) {
2980 // Insert a VBITCONVERT to convert from the packed result type to the
2981 // MVT::Vector type.
2982 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2983 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2984
2985 // Figure out if there is a Packed type corresponding to this Vector
2986 // type. If so, convert to the packed type.
2987 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2988 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002989 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2990 // "N x PTyElementVT" MVT::Vector type.
2991 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002992 DAG.getConstant(NumElems, MVT::i32),
2993 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002994 } else {
2995 abort();
2996 }
2997 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002998 unsigned AssertOp = RetTy->isSigned() ?
2999 ISD::AssertSext : ISD::AssertZext;
3000 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3001 DAG.getValueType(VT));
3002 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3003 } else {
3004 assert(MVT::isFloatingPoint(VT));
3005 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3006 }
3007 }
3008 } else if (RetTys.size() == 3) {
3009 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3010 Res.getValue(0), Res.getValue(1));
3011
3012 } else {
3013 assert(0 && "Case not handled yet!");
3014 }
3015 }
3016
3017 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3018}
3019
3020
3021
Chris Lattner58cfd792005-01-09 00:00:49 +00003022// It is always conservatively correct for llvm.returnaddress and
3023// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00003024//
3025// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3026// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00003027std::pair<SDOperand, SDOperand>
3028TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3029 unsigned Depth, SelectionDAG &DAG) {
3030 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00003031}
3032
Chris Lattner29dcc712005-05-14 05:50:48 +00003033SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003034 assert(0 && "LowerOperation not implemented for this target!");
3035 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003036 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003037}
3038
Nate Begeman595ec732006-01-28 03:14:31 +00003039SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3040 SelectionDAG &DAG) {
3041 assert(0 && "CustomPromoteOperation not implemented for this target!");
3042 abort();
3043 return SDOperand();
3044}
3045
Chris Lattner58cfd792005-01-09 00:00:49 +00003046void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003047 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00003048 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00003049 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00003050 setValue(&I, Result.first);
3051 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003052}
3053
Evan Cheng6781b6e2006-02-15 21:59:04 +00003054/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003055/// operand.
3056static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003057 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003058 MVT::ValueType CurVT = VT;
3059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3060 uint64_t Val = C->getValue() & 255;
3061 unsigned Shift = 8;
3062 while (CurVT != MVT::i8) {
3063 Val = (Val << Shift) | Val;
3064 Shift <<= 1;
3065 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003066 }
3067 return DAG.getConstant(Val, VT);
3068 } else {
3069 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3070 unsigned Shift = 8;
3071 while (CurVT != MVT::i8) {
3072 Value =
3073 DAG.getNode(ISD::OR, VT,
3074 DAG.getNode(ISD::SHL, VT, Value,
3075 DAG.getConstant(Shift, MVT::i8)), Value);
3076 Shift <<= 1;
3077 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003078 }
3079
3080 return Value;
3081 }
3082}
3083
Evan Cheng6781b6e2006-02-15 21:59:04 +00003084/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3085/// used when a memcpy is turned into a memset when the source is a constant
3086/// string ptr.
3087static SDOperand getMemsetStringVal(MVT::ValueType VT,
3088 SelectionDAG &DAG, TargetLowering &TLI,
3089 std::string &Str, unsigned Offset) {
3090 MVT::ValueType CurVT = VT;
3091 uint64_t Val = 0;
3092 unsigned MSB = getSizeInBits(VT) / 8;
3093 if (TLI.isLittleEndian())
3094 Offset = Offset + MSB - 1;
3095 for (unsigned i = 0; i != MSB; ++i) {
3096 Val = (Val << 8) | Str[Offset];
3097 Offset += TLI.isLittleEndian() ? -1 : 1;
3098 }
3099 return DAG.getConstant(Val, VT);
3100}
3101
Evan Cheng81fcea82006-02-14 08:22:34 +00003102/// getMemBasePlusOffset - Returns base and offset node for the
3103static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3104 SelectionDAG &DAG, TargetLowering &TLI) {
3105 MVT::ValueType VT = Base.getValueType();
3106 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3107}
3108
Evan Chengdb2a7a72006-02-14 20:12:38 +00003109/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003110/// to replace the memset / memcpy is below the threshold. It also returns the
3111/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003112static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3113 unsigned Limit, uint64_t Size,
3114 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003115 MVT::ValueType VT;
3116
3117 if (TLI.allowsUnalignedMemoryAccesses()) {
3118 VT = MVT::i64;
3119 } else {
3120 switch (Align & 7) {
3121 case 0:
3122 VT = MVT::i64;
3123 break;
3124 case 4:
3125 VT = MVT::i32;
3126 break;
3127 case 2:
3128 VT = MVT::i16;
3129 break;
3130 default:
3131 VT = MVT::i8;
3132 break;
3133 }
3134 }
3135
Evan Chengd5026102006-02-14 09:11:59 +00003136 MVT::ValueType LVT = MVT::i64;
3137 while (!TLI.isTypeLegal(LVT))
3138 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3139 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003140
Evan Chengd5026102006-02-14 09:11:59 +00003141 if (VT > LVT)
3142 VT = LVT;
3143
Evan Cheng04514992006-02-14 23:05:54 +00003144 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003145 while (Size != 0) {
3146 unsigned VTSize = getSizeInBits(VT) / 8;
3147 while (VTSize > Size) {
3148 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003149 VTSize >>= 1;
3150 }
Evan Chengd5026102006-02-14 09:11:59 +00003151 assert(MVT::isInteger(VT));
3152
3153 if (++NumMemOps > Limit)
3154 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003155 MemOps.push_back(VT);
3156 Size -= VTSize;
3157 }
Evan Chengd5026102006-02-14 09:11:59 +00003158
3159 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003160}
3161
Chris Lattner875def92005-01-11 05:56:49 +00003162void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003163 SDOperand Op1 = getValue(I.getOperand(1));
3164 SDOperand Op2 = getValue(I.getOperand(2));
3165 SDOperand Op3 = getValue(I.getOperand(3));
3166 SDOperand Op4 = getValue(I.getOperand(4));
3167 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3168 if (Align == 0) Align = 1;
3169
3170 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3171 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003172
3173 // Expand memset / memcpy to a series of load / store ops
3174 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003175 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003176 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003177 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003178 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003179 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3180 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003181 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003182 unsigned Offset = 0;
3183 for (unsigned i = 0; i < NumMemOps; i++) {
3184 MVT::ValueType VT = MemOps[i];
3185 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003186 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003187 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003188 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003189 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003190 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003191 Offset += VTSize;
3192 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003193 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003194 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003195 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003196 case ISD::MEMCPY: {
3197 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3198 Size->getValue(), Align, TLI)) {
3199 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003200 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003201 GlobalAddressSDNode *G = NULL;
3202 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003203 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003204
3205 if (Op2.getOpcode() == ISD::GlobalAddress)
3206 G = cast<GlobalAddressSDNode>(Op2);
3207 else if (Op2.getOpcode() == ISD::ADD &&
3208 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3209 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3210 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003211 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003212 }
3213 if (G) {
3214 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003215 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00003216 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003217 if (!Str.empty()) {
3218 CopyFromStr = true;
3219 SrcOff += SrcDelta;
3220 }
3221 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003222 }
3223
Evan Chenge2038bd2006-02-15 01:54:51 +00003224 for (unsigned i = 0; i < NumMemOps; i++) {
3225 MVT::ValueType VT = MemOps[i];
3226 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003227 SDOperand Value, Chain, Store;
3228
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003229 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003230 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3231 Chain = getRoot();
3232 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003233 DAG.getStore(Chain, Value,
3234 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003235 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003236 } else {
3237 Value = DAG.getLoad(VT, getRoot(),
3238 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003239 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003240 Chain = Value.getValue(1);
3241 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003242 DAG.getStore(Chain, Value,
3243 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003244 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003245 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003246 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003247 SrcOff += VTSize;
3248 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003249 }
3250 }
3251 break;
3252 }
3253 }
3254
3255 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003256 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3257 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003258 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003259 }
3260 }
3261
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003262 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003263}
3264
Chris Lattner875def92005-01-11 05:56:49 +00003265//===----------------------------------------------------------------------===//
3266// SelectionDAGISel code
3267//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003268
3269unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3270 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3271}
3272
Chris Lattnerc9950c12005-08-17 06:37:43 +00003273void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003274 // FIXME: we only modify the CFG to split critical edges. This
3275 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003276 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003277}
Chris Lattner7a60d912005-01-07 07:47:53 +00003278
Chris Lattner35397782005-12-05 07:10:48 +00003279
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003280/// OptimizeNoopCopyExpression - We have determined that the specified cast
3281/// instruction is a noop copy (e.g. it's casting from one pointer type to
3282/// another, int->uint, or int->sbyte on PPC.
3283///
3284/// Return true if any changes are made.
3285static bool OptimizeNoopCopyExpression(CastInst *CI) {
3286 BasicBlock *DefBB = CI->getParent();
3287
3288 /// InsertedCasts - Only insert a cast in each block once.
3289 std::map<BasicBlock*, CastInst*> InsertedCasts;
3290
3291 bool MadeChange = false;
3292 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3293 UI != E; ) {
3294 Use &TheUse = UI.getUse();
3295 Instruction *User = cast<Instruction>(*UI);
3296
3297 // Figure out which BB this cast is used in. For PHI's this is the
3298 // appropriate predecessor block.
3299 BasicBlock *UserBB = User->getParent();
3300 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3301 unsigned OpVal = UI.getOperandNo()/2;
3302 UserBB = PN->getIncomingBlock(OpVal);
3303 }
3304
3305 // Preincrement use iterator so we don't invalidate it.
3306 ++UI;
3307
3308 // If this user is in the same block as the cast, don't change the cast.
3309 if (UserBB == DefBB) continue;
3310
3311 // If we have already inserted a cast into this block, use it.
3312 CastInst *&InsertedCast = InsertedCasts[UserBB];
3313
3314 if (!InsertedCast) {
3315 BasicBlock::iterator InsertPt = UserBB->begin();
3316 while (isa<PHINode>(InsertPt)) ++InsertPt;
3317
3318 InsertedCast =
3319 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3320 MadeChange = true;
3321 }
3322
3323 // Replace a use of the cast with a use of the new casat.
3324 TheUse = InsertedCast;
3325 }
3326
3327 // If we removed all uses, nuke the cast.
3328 if (CI->use_empty())
3329 CI->eraseFromParent();
3330
3331 return MadeChange;
3332}
3333
Chris Lattner35397782005-12-05 07:10:48 +00003334/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3335/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003336static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3337 Instruction *GEPI, Value *Ptr,
3338 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003339 if (V) return V; // Already computed.
3340
3341 BasicBlock::iterator InsertPt;
3342 if (BB == GEPI->getParent()) {
3343 // If insert into the GEP's block, insert right after the GEP.
3344 InsertPt = GEPI;
3345 ++InsertPt;
3346 } else {
3347 // Otherwise, insert at the top of BB, after any PHI nodes
3348 InsertPt = BB->begin();
3349 while (isa<PHINode>(InsertPt)) ++InsertPt;
3350 }
3351
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003352 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3353 // BB so that there is only one value live across basic blocks (the cast
3354 // operand).
3355 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3356 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3357 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3358
Chris Lattner35397782005-12-05 07:10:48 +00003359 // Add the offset, cast it to the right type.
3360 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003361 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003362}
3363
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003364/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3365/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3366/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3367/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3368/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3369/// the constant add into a load or store instruction. Additionally, if a user
3370/// is a pointer-pointer cast, we look through it to find its users.
3371static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3372 Constant *PtrOffset, BasicBlock *DefBB,
3373 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003374 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003375 while (!RepPtr->use_empty()) {
3376 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003377
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003378 // If the user is a Pointer-Pointer cast, recurse.
3379 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3380 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003381
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003382 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3383 // could invalidate an iterator.
3384 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3385 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003386 }
3387
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003388 // If this is a load of the pointer, or a store through the pointer, emit
3389 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003390 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003391 if (isa<LoadInst>(User) ||
3392 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3393 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3394 User->getParent(), GEPI,
3395 Ptr, PtrOffset);
3396 } else {
3397 // If this use is not foldable into the addressing mode, use a version
3398 // emitted in the GEP block.
3399 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3400 Ptr, PtrOffset);
3401 }
3402
Chris Lattner21cd9902006-05-06 09:10:37 +00003403 if (GEPI->getType() != RepPtr->getType()) {
3404 BasicBlock::iterator IP = NewVal;
3405 ++IP;
3406 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3407 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003408 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003409 }
3410}
Chris Lattner35397782005-12-05 07:10:48 +00003411
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003412
Chris Lattner35397782005-12-05 07:10:48 +00003413/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3414/// selection, we want to be a bit careful about some things. In particular, if
3415/// we have a GEP instruction that is used in a different block than it is
3416/// defined, the addressing expression of the GEP cannot be folded into loads or
3417/// stores that use it. In this case, decompose the GEP and move constant
3418/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003419static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003420 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003421 // If this GEP is only used inside the block it is defined in, there is no
3422 // need to rewrite it.
3423 bool isUsedOutsideDefBB = false;
3424 BasicBlock *DefBB = GEPI->getParent();
3425 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3426 UI != E; ++UI) {
3427 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3428 isUsedOutsideDefBB = true;
3429 break;
3430 }
3431 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003432 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003433
3434 // If this GEP has no non-zero constant indices, there is nothing we can do,
3435 // ignore it.
3436 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003437 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003438 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3439 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003440 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003441 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003442 hasConstantIndex = true;
3443 break;
3444 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003445 } else {
3446 hasVariableIndex = true;
3447 }
Chris Lattner35397782005-12-05 07:10:48 +00003448 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003449
3450 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3451 if (!hasConstantIndex && !hasVariableIndex) {
3452 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3453 GEPI->getName(), GEPI);
3454 GEPI->replaceAllUsesWith(NC);
3455 GEPI->eraseFromParent();
3456 return true;
3457 }
3458
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003459 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003460 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3461 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003462
3463 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3464 // constant offset (which we now know is non-zero) and deal with it later.
3465 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003466 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003467 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3468 const Type *Ty = GEPI->getOperand(0)->getType();
3469
3470 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3471 E = GEPI->op_end(); OI != E; ++OI) {
3472 Value *Idx = *OI;
3473 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003474 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003475 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003476 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003477 Ty = StTy->getElementType(Field);
3478 } else {
3479 Ty = cast<SequentialType>(Ty)->getElementType();
3480
3481 // Handle constant subscripts.
3482 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003483 if (CI->getZExtValue() == 0) continue;
3484 if (CI->getType()->isSigned())
3485 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003486 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003487 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003488 continue;
3489 }
3490
3491 // Ptr = Ptr + Idx * ElementSize;
3492
3493 // Cast Idx to UIntPtrTy if needed.
3494 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3495
Owen Anderson20a631f2006-05-03 01:29:57 +00003496 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003497 // Mask off bits that should not be set.
3498 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003499 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003500
3501 // Multiply by the element size and add to the base.
3502 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3503 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3504 }
3505 }
3506
3507 // Make sure that the offset fits in uintptr_t.
3508 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003509 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003510
3511 // Okay, we have now emitted all of the variable index parts to the BB that
3512 // the GEP is defined in. Loop over all of the using instructions, inserting
3513 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003514 // instruction to use the newly computed value, making GEPI dead. When the
3515 // user is a load or store instruction address, we emit the add into the user
3516 // block, otherwise we use a canonical version right next to the gep (these
3517 // won't be foldable as addresses, so we might as well share the computation).
3518
Chris Lattner21cd9902006-05-06 09:10:37 +00003519 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003520 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003521
3522 // Finally, the GEP is dead, remove it.
3523 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003524
3525 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003526}
3527
Chris Lattnerbba52192006-10-28 19:22:10 +00003528
3529/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3530/// successor if it will improve codegen. We only do this if the successor has
3531/// phi nodes (otherwise critical edges are ok). If there is already another
3532/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3533/// instead of introducing a new block.
3534static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3535 BasicBlock *TIBB = TI->getParent();
3536 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3537 assert(isa<PHINode>(Dest->begin()) &&
3538 "This should only be called if Dest has a PHI!");
3539
3540 /// TIPHIValues - This array is lazily computed to determine the values of
3541 /// PHIs in Dest that TI would provide.
3542 std::vector<Value*> TIPHIValues;
3543
3544 // Check to see if Dest has any blocks that can be used as a split edge for
3545 // this terminator.
3546 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3547 BasicBlock *Pred = *PI;
3548 // To be usable, the pred has to end with an uncond branch to the dest.
3549 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3550 if (!PredBr || !PredBr->isUnconditional() ||
3551 // Must be empty other than the branch.
3552 &Pred->front() != PredBr)
3553 continue;
3554
3555 // Finally, since we know that Dest has phi nodes in it, we have to make
3556 // sure that jumping to Pred will have the same affect as going to Dest in
3557 // terms of PHI values.
3558 PHINode *PN;
3559 unsigned PHINo = 0;
3560 bool FoundMatch = true;
3561 for (BasicBlock::iterator I = Dest->begin();
3562 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3563 if (PHINo == TIPHIValues.size())
3564 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3565
3566 // If the PHI entry doesn't work, we can't use this pred.
3567 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3568 FoundMatch = false;
3569 break;
3570 }
3571 }
3572
3573 // If we found a workable predecessor, change TI to branch to Succ.
3574 if (FoundMatch) {
3575 Dest->removePredecessor(TIBB);
3576 TI->setSuccessor(SuccNum, Pred);
3577 return;
3578 }
3579 }
3580
3581 SplitCriticalEdge(TI, SuccNum, P, true);
3582}
3583
3584
Chris Lattner7a60d912005-01-07 07:47:53 +00003585bool SelectionDAGISel::runOnFunction(Function &Fn) {
3586 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3587 RegMap = MF.getSSARegMap();
3588 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3589
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003590 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003591 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003592 // In this pass we also look for GEP and cast instructions that are used
3593 // across basic blocks and rewrite them to improve basic-block-at-a-time
3594 // selection.
3595 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003596 bool MadeChange = true;
3597 while (MadeChange) {
3598 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003599 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbba52192006-10-28 19:22:10 +00003600 // Split all critical edges where the dest block has a PHI.
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003601 TerminatorInst *BBTI = BB->getTerminator();
3602 if (BBTI->getNumSuccessors() > 1) {
3603 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00003604 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3605 isCriticalEdge(BBTI, i, true))
3606 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003607 }
3608
Chris Lattner35397782005-12-05 07:10:48 +00003609
Chris Lattnera9caf952006-09-28 06:17:10 +00003610 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003611 Instruction *I = BBI++;
3612 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003613 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003614 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003615 // If the source of the cast is a constant, then this should have
3616 // already been constant folded. The only reason NOT to constant fold
3617 // it is if something (e.g. LSR) was careful to place the constant
3618 // evaluation in a block other than then one that uses it (e.g. to hoist
3619 // the address of globals out of a loop). If this is the case, we don't
3620 // want to forward-subst the cast.
3621 if (isa<Constant>(CI->getOperand(0)))
3622 continue;
3623
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003624 // If this is a noop copy, sink it into user blocks to reduce the number
3625 // of virtual registers that must be created and coallesced.
3626 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3627 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3628
3629 // This is an fp<->int conversion?
3630 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3631 continue;
3632
3633 // If this is an extension, it will be a zero or sign extension, which
3634 // isn't a noop.
3635 if (SrcVT < DstVT) continue;
3636
3637 // If these values will be promoted, find out what they will be promoted
3638 // to. This helps us consider truncates on PPC as noop copies when they
3639 // are.
3640 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3641 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3642 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3643 DstVT = TLI.getTypeToTransformTo(DstVT);
3644
3645 // If, after promotion, these are the same types, this is a noop copy.
3646 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003647 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003648 }
3649 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003650 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003651 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003652
Chris Lattner7a60d912005-01-07 07:47:53 +00003653 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3654
3655 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3656 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003657
Chris Lattner7a60d912005-01-07 07:47:53 +00003658 return true;
3659}
3660
Chris Lattnered0110b2006-10-27 21:36:01 +00003661SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3662 unsigned Reg) {
3663 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003664 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003665 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003666 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003667
3668 // If this type is not legal, we must make sure to not create an invalid
3669 // register use.
3670 MVT::ValueType SrcVT = Op.getValueType();
3671 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003672 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003673 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003674 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003675 // Handle copies from generic vectors to registers.
3676 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3677 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3678 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003679
Chris Lattner5fe1f542006-03-31 02:06:56 +00003680 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3681 // MVT::Vector type.
3682 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3683 DAG.getConstant(NE, MVT::i32),
3684 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003685
Chris Lattner5fe1f542006-03-31 02:06:56 +00003686 // Loop over all of the elements of the resultant vector,
3687 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3688 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003689 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003690 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003691 for (unsigned i = 0; i != NE; ++i) {
3692 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003693 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003694 if (PTyElementVT == PTyLegalElementVT) {
3695 // Elements are legal.
3696 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3697 } else if (PTyLegalElementVT > PTyElementVT) {
3698 // Elements are promoted.
3699 if (MVT::isFloatingPoint(PTyLegalElementVT))
3700 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3701 else
3702 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3703 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3704 } else {
3705 // Elements are expanded.
3706 // The src value is expanded into multiple registers.
3707 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003708 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003709 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003710 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003711 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3712 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3713 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003714 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003715 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3716 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003717 } else if (SrcVT < DestVT) {
3718 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003719 if (MVT::isFloatingPoint(SrcVT))
3720 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3721 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003722 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003723 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003724 } else {
3725 // The src value is expanded into multiple registers.
3726 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003727 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003728 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003729 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003730 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003731 return DAG.getCopyToReg(Op, Reg+1, Hi);
3732 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003733}
3734
Chris Lattner16f64df2005-01-17 17:15:02 +00003735void SelectionDAGISel::
3736LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3737 std::vector<SDOperand> &UnorderedChains) {
3738 // If this is the entry block, emit arguments.
3739 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003740 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003741 SDOperand OldRoot = SDL.DAG.getRoot();
3742 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003743
Chris Lattner6871b232005-10-30 19:42:35 +00003744 unsigned a = 0;
3745 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3746 AI != E; ++AI, ++a)
3747 if (!AI->use_empty()) {
3748 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003749
Chris Lattner6871b232005-10-30 19:42:35 +00003750 // If this argument is live outside of the entry block, insert a copy from
3751 // whereever we got it to the vreg that other BB's will reference it as.
3752 if (FuncInfo.ValueMap.count(AI)) {
3753 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003754 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003755 UnorderedChains.push_back(Copy);
3756 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003757 }
Chris Lattner6871b232005-10-30 19:42:35 +00003758
Chris Lattner6871b232005-10-30 19:42:35 +00003759 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003760 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003761 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003762}
3763
Chris Lattner7a60d912005-01-07 07:47:53 +00003764void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3765 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003766 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003767 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003768
3769 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003770
Chris Lattner6871b232005-10-30 19:42:35 +00003771 // Lower any arguments needed in this block if this is the entry block.
3772 if (LLVMBB == &LLVMBB->getParent()->front())
3773 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003774
3775 BB = FuncInfo.MBBMap[LLVMBB];
3776 SDL.setCurrentBasicBlock(BB);
3777
3778 // Lower all of the non-terminator instructions.
3779 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3780 I != E; ++I)
3781 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003782
Chris Lattner7a60d912005-01-07 07:47:53 +00003783 // Ensure that all instructions which are used outside of their defining
3784 // blocks are available as virtual registers.
3785 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003786 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003787 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003788 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003789 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003790 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003791 }
3792
3793 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3794 // ensure constants are generated when needed. Remember the virtual registers
3795 // that need to be added to the Machine PHI nodes as input. We cannot just
3796 // directly add them, because expansion might result in multiple MBB's for one
3797 // BB. As such, the start of the BB might correspond to a different MBB than
3798 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003799 //
Chris Lattner84a03502006-10-27 23:50:33 +00003800 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00003801
3802 // Emit constants only once even if used by multiple PHI nodes.
3803 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003804
Chris Lattner84a03502006-10-27 23:50:33 +00003805 // Vector bool would be better, but vector<bool> is really slow.
3806 std::vector<unsigned char> SuccsHandled;
3807 if (TI->getNumSuccessors())
3808 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3809
Chris Lattner7a60d912005-01-07 07:47:53 +00003810 // Check successor nodes PHI nodes that expect a constant to be available from
3811 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00003812 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3813 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003814 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00003815 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00003816
Chris Lattner84a03502006-10-27 23:50:33 +00003817 // If this terminator has multiple identical successors (common for
3818 // switches), only handle each succ once.
3819 unsigned SuccMBBNo = SuccMBB->getNumber();
3820 if (SuccsHandled[SuccMBBNo]) continue;
3821 SuccsHandled[SuccMBBNo] = true;
3822
3823 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00003824 PHINode *PN;
3825
3826 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3827 // nodes and Machine PHI nodes, but the incoming operands have not been
3828 // emitted yet.
3829 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00003830 (PN = dyn_cast<PHINode>(I)); ++I) {
3831 // Ignore dead phi's.
3832 if (PN->use_empty()) continue;
3833
3834 unsigned Reg;
3835 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3836 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3837 unsigned &RegOut = ConstantsOut[C];
3838 if (RegOut == 0) {
3839 RegOut = FuncInfo.CreateRegForValue(C);
3840 UnorderedChains.push_back(
3841 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00003842 }
Chris Lattner84a03502006-10-27 23:50:33 +00003843 Reg = RegOut;
3844 } else {
3845 Reg = FuncInfo.ValueMap[PHIOp];
3846 if (Reg == 0) {
3847 assert(isa<AllocaInst>(PHIOp) &&
3848 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3849 "Didn't codegen value into a register!??");
3850 Reg = FuncInfo.CreateRegForValue(PHIOp);
3851 UnorderedChains.push_back(
3852 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00003853 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003854 }
Chris Lattner84a03502006-10-27 23:50:33 +00003855
3856 // Remember that this register needs to added to the machine PHI node as
3857 // the input for this MBB.
3858 MVT::ValueType VT = TLI.getValueType(PN->getType());
3859 unsigned NumElements;
3860 if (VT != MVT::Vector)
3861 NumElements = TLI.getNumElements(VT);
3862 else {
3863 MVT::ValueType VT1,VT2;
3864 NumElements =
3865 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3866 VT1, VT2);
3867 }
3868 for (unsigned i = 0, e = NumElements; i != e; ++i)
3869 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3870 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003871 }
3872 ConstantsOut.clear();
3873
Chris Lattner718b5c22005-01-13 17:59:43 +00003874 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003875 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003876 SDOperand Root = SDL.getRoot();
3877 if (Root.getOpcode() != ISD::EntryToken) {
3878 unsigned i = 0, e = UnorderedChains.size();
3879 for (; i != e; ++i) {
3880 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3881 if (UnorderedChains[i].Val->getOperand(0) == Root)
3882 break; // Don't add the root if we already indirectly depend on it.
3883 }
3884
3885 if (i == e)
3886 UnorderedChains.push_back(Root);
3887 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003888 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3889 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003890 }
3891
Chris Lattner7a60d912005-01-07 07:47:53 +00003892 // Lower the terminator after the copies are emitted.
3893 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003894
Nate Begemaned728c12006-03-27 01:32:24 +00003895 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003896 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003897 SwitchCases.clear();
3898 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003899 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003900
Chris Lattner4108bb02005-01-17 19:43:36 +00003901 // Make sure the root of the DAG is up-to-date.
3902 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003903}
3904
Nate Begemaned728c12006-03-27 01:32:24 +00003905void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003906 // Get alias analysis for load/store combining.
3907 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3908
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003909 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003910 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003911
Chris Lattner7a60d912005-01-07 07:47:53 +00003912 DEBUG(std::cerr << "Lowered selection DAG:\n");
3913 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003914
Chris Lattner7a60d912005-01-07 07:47:53 +00003915 // Second step, hack on the DAG until it only uses operations and types that
3916 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003917 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003918
Chris Lattner7a60d912005-01-07 07:47:53 +00003919 DEBUG(std::cerr << "Legalized selection DAG:\n");
3920 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003921
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003922 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003923 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003924
Evan Cheng739a6a42006-01-21 02:32:06 +00003925 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003926
Chris Lattner5ca31d92005-03-30 01:10:47 +00003927 // Third, instruction select all of the operations to machine code, adding the
3928 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003929 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003930
Chris Lattner7a60d912005-01-07 07:47:53 +00003931 DEBUG(std::cerr << "Selected machine code:\n");
3932 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003933}
Chris Lattner7a60d912005-01-07 07:47:53 +00003934
Nate Begemaned728c12006-03-27 01:32:24 +00003935void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3936 FunctionLoweringInfo &FuncInfo) {
3937 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3938 {
3939 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3940 CurDAG = &DAG;
3941
3942 // First step, lower LLVM code to some DAG. This DAG may use operations and
3943 // types that are not supported by the target.
3944 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3945
3946 // Second step, emit the lowered DAG as machine code.
3947 CodeGenAndEmitDAG(DAG);
3948 }
3949
Chris Lattner5ca31d92005-03-30 01:10:47 +00003950 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003951 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003952 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003953 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3954 MachineInstr *PHI = PHINodesToUpdate[i].first;
3955 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3956 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003957 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003958 PHI->addMachineBasicBlockOperand(BB);
3959 }
3960 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003961 }
Nate Begemaned728c12006-03-27 01:32:24 +00003962
Nate Begeman866b4b42006-04-23 06:26:20 +00003963 // If the JumpTable record is filled in, then we need to emit a jump table.
3964 // Updating the PHI nodes is tricky in this case, since we need to determine
3965 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003966 if (JT.Reg) {
3967 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3968 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3969 CurDAG = &SDAG;
3970 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003971 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003972 // Set the current basic block to the mbb we wish to insert the code into
3973 BB = JT.MBB;
3974 SDL.setCurrentBasicBlock(BB);
3975 // Emit the code
3976 SDL.visitJumpTable(JT);
3977 SDAG.setRoot(SDL.getRoot());
3978 CodeGenAndEmitDAG(SDAG);
3979 // Update PHI Nodes
3980 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3981 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3982 MachineBasicBlock *PHIBB = PHI->getParent();
3983 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3984 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003985 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003986 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003987 PHI->addMachineBasicBlockOperand(RangeBB);
3988 }
3989 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003990 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003991 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003992 }
3993 }
3994 return;
3995 }
3996
Chris Lattner76a7bc82006-10-22 23:00:53 +00003997 // If the switch block involved a branch to one of the actual successors, we
3998 // need to update PHI nodes in that block.
3999 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4000 MachineInstr *PHI = PHINodesToUpdate[i].first;
4001 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4002 "This is not a machine PHI node that we are updating!");
4003 if (BB->isSuccessor(PHI->getParent())) {
4004 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4005 PHI->addMachineBasicBlockOperand(BB);
4006 }
4007 }
4008
Nate Begemaned728c12006-03-27 01:32:24 +00004009 // If we generated any switch lowering information, build and codegen any
4010 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004011 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00004012 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4013 CurDAG = &SDAG;
4014 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004015
Nate Begemaned728c12006-03-27 01:32:24 +00004016 // Set the current basic block to the mbb we wish to insert the code into
4017 BB = SwitchCases[i].ThisBB;
4018 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004019
Nate Begemaned728c12006-03-27 01:32:24 +00004020 // Emit the code
4021 SDL.visitSwitchCase(SwitchCases[i]);
4022 SDAG.setRoot(SDL.getRoot());
4023 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004024
4025 // Handle any PHI nodes in successors of this chunk, as if we were coming
4026 // from the original BB before switch expansion. Note that PHI nodes can
4027 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4028 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004029 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004030 for (MachineBasicBlock::iterator Phi = BB->begin();
4031 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4032 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4033 for (unsigned pn = 0; ; ++pn) {
4034 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4035 if (PHINodesToUpdate[pn].first == Phi) {
4036 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4037 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4038 break;
4039 }
4040 }
Nate Begemaned728c12006-03-27 01:32:24 +00004041 }
Chris Lattner707339a52006-09-07 01:59:34 +00004042
4043 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004044 if (BB == SwitchCases[i].FalseBB)
4045 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004046
4047 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004048 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004049 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004050 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004051 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004052 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004053}
Evan Cheng739a6a42006-01-21 02:32:06 +00004054
Jim Laskey95eda5b2006-08-01 14:21:23 +00004055
Evan Cheng739a6a42006-01-21 02:32:06 +00004056//===----------------------------------------------------------------------===//
4057/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4058/// target node in the graph.
4059void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4060 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004061
Jim Laskey29e635d2006-08-02 12:30:23 +00004062 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004063
4064 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004065 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004066 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004067 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004068
Jim Laskey03593f72006-08-01 18:29:48 +00004069 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004070 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004071 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004072}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004073
Chris Lattner47639db2006-03-06 00:22:00 +00004074
Jim Laskey03593f72006-08-01 18:29:48 +00004075HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4076 return new HazardRecognizer();
4077}
4078
Chris Lattner6df34962006-10-11 03:58:02 +00004079//===----------------------------------------------------------------------===//
4080// Helper functions used by the generated instruction selector.
4081//===----------------------------------------------------------------------===//
4082// Calls to these methods are generated by tblgen.
4083
4084/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4085/// the dag combiner simplified the 255, we still want to match. RHS is the
4086/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4087/// specified in the .td file (e.g. 255).
4088bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4089 int64_t DesiredMaskS) {
4090 uint64_t ActualMask = RHS->getValue();
4091 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4092
4093 // If the actual mask exactly matches, success!
4094 if (ActualMask == DesiredMask)
4095 return true;
4096
4097 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4098 if (ActualMask & ~DesiredMask)
4099 return false;
4100
4101 // Otherwise, the DAG Combiner may have proven that the value coming in is
4102 // either already zero or is not demanded. Check for known zero input bits.
4103 uint64_t NeededMask = DesiredMask & ~ActualMask;
4104 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4105 return true;
4106
4107 // TODO: check to see if missing bits are just not demanded.
4108
4109 // Otherwise, this pattern doesn't match.
4110 return false;
4111}
4112
4113/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4114/// the dag combiner simplified the 255, we still want to match. RHS is the
4115/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4116/// specified in the .td file (e.g. 255).
4117bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4118 int64_t DesiredMaskS) {
4119 uint64_t ActualMask = RHS->getValue();
4120 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4121
4122 // If the actual mask exactly matches, success!
4123 if (ActualMask == DesiredMask)
4124 return true;
4125
4126 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4127 if (ActualMask & ~DesiredMask)
4128 return false;
4129
4130 // Otherwise, the DAG Combiner may have proven that the value coming in is
4131 // either already zero or is not demanded. Check for known zero input bits.
4132 uint64_t NeededMask = DesiredMask & ~ActualMask;
4133
4134 uint64_t KnownZero, KnownOne;
4135 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4136
4137 // If all the missing bits in the or are already known to be set, match!
4138 if ((NeededMask & KnownOne) == NeededMask)
4139 return true;
4140
4141 // TODO: check to see if missing bits are just not demanded.
4142
4143 // Otherwise, this pattern doesn't match.
4144 return false;
4145}
4146
Jim Laskey03593f72006-08-01 18:29:48 +00004147
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004148/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4149/// by tblgen. Others should not call it.
4150void SelectionDAGISel::
4151SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4152 std::vector<SDOperand> InOps;
4153 std::swap(InOps, Ops);
4154
4155 Ops.push_back(InOps[0]); // input chain.
4156 Ops.push_back(InOps[1]); // input asm string.
4157
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004158 unsigned i = 2, e = InOps.size();
4159 if (InOps[e-1].getValueType() == MVT::Flag)
4160 --e; // Don't process a flag operand if it is here.
4161
4162 while (i != e) {
4163 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4164 if ((Flags & 7) != 4 /*MEM*/) {
4165 // Just skip over this operand, copying the operands verbatim.
4166 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4167 i += (Flags >> 3) + 1;
4168 } else {
4169 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4170 // Otherwise, this is a memory operand. Ask the target to select it.
4171 std::vector<SDOperand> SelOps;
4172 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4173 std::cerr << "Could not match memory address. Inline asm failure!\n";
4174 exit(1);
4175 }
4176
4177 // Add this to the output node.
4178 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4179 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4180 i += 2;
4181 }
4182 }
4183
4184 // Add the flag input back if present.
4185 if (e != InOps.size())
4186 Ops.push_back(InOps.back());
4187}