blob: 8b9fa863296a525cf68eb5b99d092bb380f69cba [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"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000036#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetFrameInfo.h"
38#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000041#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000043#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000046#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000254 //
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000258 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000260 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000262 }
263
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
270
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
276 MBBMap[BB] = MBB;
277 MF.getBasicBlockList().push_back(MBB);
278
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
280 // appropriate.
281 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
284
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
289 else {
290 MVT::ValueType VT1,VT2;
291 NumElements =
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
293 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000294 }
Chris Lattner84a03502006-10-27 23:50:33 +0000295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
297 for (unsigned i = 0; i != NumElements; ++i)
298 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
299 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000300 }
301}
302
Chris Lattner49409cb2006-03-16 19:51:18 +0000303/// CreateRegForValue - Allocate the appropriate number of virtual registers of
304/// the correctly promoted or expanded types. Assign these registers
305/// consecutive vreg numbers and return the first assigned number.
306unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
308
309 // The number of multiples of registers that we need, to, e.g., split up
310 // a <2 x int64> -> 4 x i32 registers.
311 unsigned NumVectorRegs = 1;
312
313 // If this is a packed type, figure out what type it will decompose into
314 // and how many of the elements it will use.
315 if (VT == MVT::Vector) {
316 const PackedType *PTy = cast<PackedType>(V->getType());
317 unsigned NumElts = PTy->getNumElements();
318 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
319
320 // Divide the input until we get to a supported size. This will always
321 // end with a scalar if the target doesn't support vectors.
322 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
323 NumElts >>= 1;
324 NumVectorRegs <<= 1;
325 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000326 if (NumElts == 1)
327 VT = EltTy;
328 else
329 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000330 }
331
332 // The common case is that we will only create one register for this
333 // value. If we have that case, create and return the virtual register.
334 unsigned NV = TLI.getNumElements(VT);
335 if (NV == 1) {
336 // If we are promoting this value, pick the next largest supported type.
337 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
338 unsigned Reg = MakeReg(PromotedType);
339 // If this is a vector of supported or promoted types (e.g. 4 x i16),
340 // create all of the registers.
341 for (unsigned i = 1; i != NumVectorRegs; ++i)
342 MakeReg(PromotedType);
343 return Reg;
344 }
345
346 // If this value is represented with multiple target registers, make sure
347 // to create enough consecutive registers of the right (smaller) type.
348 unsigned NT = VT-1; // Find the type to use.
349 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
350 --NT;
351
352 unsigned R = MakeReg((MVT::ValueType)NT);
353 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
354 MakeReg((MVT::ValueType)NT);
355 return R;
356}
Chris Lattner7a60d912005-01-07 07:47:53 +0000357
358//===----------------------------------------------------------------------===//
359/// SelectionDAGLowering - This is the common target-independent lowering
360/// implementation that is parameterized by a TargetLowering object.
361/// Also, targets can overload any lowering method.
362///
363namespace llvm {
364class SelectionDAGLowering {
365 MachineBasicBlock *CurMBB;
366
367 std::map<const Value*, SDOperand> NodeMap;
368
Chris Lattner4d9651c2005-01-17 22:19:26 +0000369 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
370 /// them up and then emit token factor nodes when possible. This allows us to
371 /// get simple disambiguation between loads without worrying about alias
372 /// analysis.
373 std::vector<SDOperand> PendingLoads;
374
Nate Begemaned728c12006-03-27 01:32:24 +0000375 /// Case - A pair of values to record the Value for a switch case, and the
376 /// case's target basic block.
377 typedef std::pair<Constant*, MachineBasicBlock*> Case;
378 typedef std::vector<Case>::iterator CaseItr;
379 typedef std::pair<CaseItr, CaseItr> CaseRange;
380
381 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
382 /// of conditional branches.
383 struct CaseRec {
384 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
385 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
386
387 /// CaseBB - The MBB in which to emit the compare and branch
388 MachineBasicBlock *CaseBB;
389 /// LT, GE - If nonzero, we know the current case value must be less-than or
390 /// greater-than-or-equal-to these Constants.
391 Constant *LT;
392 Constant *GE;
393 /// Range - A pair of iterators representing the range of case values to be
394 /// processed at this point in the binary search tree.
395 CaseRange Range;
396 };
397
398 /// The comparison function for sorting Case values.
399 struct CaseCmp {
400 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000401 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
402 if (I1->getType()->isUnsigned())
403 return I1->getZExtValue() <
404 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000405
Reid Spencere0fc4df2006-10-20 07:07:24 +0000406 return cast<const ConstantInt>(C1.first)->getSExtValue() <
407 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000408 }
409 };
410
Chris Lattner7a60d912005-01-07 07:47:53 +0000411public:
412 // TLI - This is information that describes the available target features we
413 // need for lowering. This indicates when operations are unavailable,
414 // implemented with a libcall, etc.
415 TargetLowering &TLI;
416 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000417 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000418
Nate Begemaned728c12006-03-27 01:32:24 +0000419 /// SwitchCases - Vector of CaseBlock structures used to communicate
420 /// SwitchInst code generation information.
421 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000422 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000423
Chris Lattner7a60d912005-01-07 07:47:53 +0000424 /// FuncInfo - Information about the function as a whole.
425 ///
426 FunctionLoweringInfo &FuncInfo;
427
428 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000429 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000431 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000432 }
433
Chris Lattner4108bb02005-01-17 19:43:36 +0000434 /// getRoot - Return the current virtual root of the Selection DAG.
435 ///
436 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000437 if (PendingLoads.empty())
438 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000439
Chris Lattner4d9651c2005-01-17 22:19:26 +0000440 if (PendingLoads.size() == 1) {
441 SDOperand Root = PendingLoads[0];
442 DAG.setRoot(Root);
443 PendingLoads.clear();
444 return Root;
445 }
446
447 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000448 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
449 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000450 PendingLoads.clear();
451 DAG.setRoot(Root);
452 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000453 }
454
Chris Lattnered0110b2006-10-27 21:36:01 +0000455 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
456
Chris Lattner7a60d912005-01-07 07:47:53 +0000457 void visit(Instruction &I) { visit(I.getOpcode(), I); }
458
459 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000460 // Note: this doesn't use InstVisitor, because it has to work with
461 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000462 switch (Opcode) {
463 default: assert(0 && "Unknown instruction type encountered!");
464 abort();
465 // Build the switch statement using the Instruction.def file.
466#define HANDLE_INST(NUM, OPCODE, CLASS) \
467 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
468#include "llvm/Instruction.def"
469 }
470 }
471
472 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
473
Chris Lattner4024c002006-03-15 22:19:46 +0000474 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000475 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000476 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000477
478 SDOperand getIntPtrConstant(uint64_t Val) {
479 return DAG.getConstant(Val, TLI.getPointerTy());
480 }
481
Chris Lattner8471b152006-03-16 19:57:50 +0000482 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000483
484 const SDOperand &setValue(const Value *V, SDOperand NewN) {
485 SDOperand &N = NodeMap[V];
486 assert(N.Val == 0 && "Already set a value for this node!");
487 return N = NewN;
488 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000489
Chris Lattner6f87d182006-02-22 22:37:12 +0000490 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
491 MVT::ValueType VT,
492 bool OutReg, bool InReg,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000495
Chris Lattnered0110b2006-10-27 21:36:01 +0000496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
498 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000500 void ExportFromCurrentBlock(Value *V);
501
Chris Lattner7a60d912005-01-07 07:47:53 +0000502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000505 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507
Nate Begemaned728c12006-03-27 01:32:24 +0000508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000511
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000518 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 else
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000524 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000525 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 else
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000531 }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000532 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
533 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
534 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000535 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
536 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000537 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000538 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
539 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
540 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000541 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000542 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
543 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000544 void visitICmp(User &I);
545 void visitFCmp(User &I);
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000546 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
547 ISD::CondCode FPOpc);
548 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
549 ISD::SETOEQ); }
550 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
551 ISD::SETUNE); }
552 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
553 ISD::SETOLE); }
554 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
555 ISD::SETOGE); }
556 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
557 ISD::SETOLT); }
558 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
559 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000560
Chris Lattner67271862006-03-29 00:11:43 +0000561 void visitExtractElement(User &I);
562 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000563 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000564
Chris Lattner7a60d912005-01-07 07:47:53 +0000565 void visitGetElementPtr(User &I);
566 void visitCast(User &I);
567 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568
569 void visitMalloc(MallocInst &I);
570 void visitFree(FreeInst &I);
571 void visitAlloca(AllocaInst &I);
572 void visitLoad(LoadInst &I);
573 void visitStore(StoreInst &I);
574 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
575 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000576 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000577 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000578 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000579
Chris Lattner7a60d912005-01-07 07:47:53 +0000580 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000581 void visitVAArg(VAArgInst &I);
582 void visitVAEnd(CallInst &I);
583 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000584 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000585
Chris Lattner875def92005-01-11 05:56:49 +0000586 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000587
588 void visitUserOp1(Instruction &I) {
589 assert(0 && "UserOp1 should not exist at instruction selection time!");
590 abort();
591 }
592 void visitUserOp2(Instruction &I) {
593 assert(0 && "UserOp2 should not exist at instruction selection time!");
594 abort();
595 }
596};
597} // end namespace llvm
598
Chris Lattner8471b152006-03-16 19:57:50 +0000599SDOperand SelectionDAGLowering::getValue(const Value *V) {
600 SDOperand &N = NodeMap[V];
601 if (N.Val) return N;
602
603 const Type *VTy = V->getType();
604 MVT::ValueType VT = TLI.getValueType(VTy);
605 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
607 visit(CE->getOpcode(), *CE);
608 assert(N.Val && "visit didn't populate the ValueMap!");
609 return N;
610 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
611 return N = DAG.getGlobalAddress(GV, VT);
612 } else if (isa<ConstantPointerNull>(C)) {
613 return N = DAG.getConstant(0, TLI.getPointerTy());
614 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000615 if (!isa<PackedType>(VTy))
616 return N = DAG.getNode(ISD::UNDEF, VT);
617
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000618 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000619 const PackedType *PTy = cast<PackedType>(VTy);
620 unsigned NumElements = PTy->getNumElements();
621 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
622
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000623 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000624 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
625
626 // Create a VConstant node with generic Vector type.
627 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
628 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000629 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
630 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000631 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
632 return N = DAG.getConstantFP(CFP->getValue(), VT);
633 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
634 unsigned NumElements = PTy->getNumElements();
635 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000636
637 // Now that we know the number and type of the elements, push a
638 // Constant or ConstantFP node onto the ops list for each element of
639 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000640 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000641 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000642 for (unsigned i = 0; i != NumElements; ++i)
643 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000644 } else {
645 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
646 SDOperand Op;
647 if (MVT::isFloatingPoint(PVT))
648 Op = DAG.getConstantFP(0, PVT);
649 else
650 Op = DAG.getConstant(0, PVT);
651 Ops.assign(NumElements, Op);
652 }
653
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000654 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000655 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
656 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000657 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000658 } else {
659 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000660 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000661 }
662 }
663
664 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
665 std::map<const AllocaInst*, int>::iterator SI =
666 FuncInfo.StaticAllocaMap.find(AI);
667 if (SI != FuncInfo.StaticAllocaMap.end())
668 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
669 }
670
671 std::map<const Value*, unsigned>::const_iterator VMI =
672 FuncInfo.ValueMap.find(V);
673 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
674
675 unsigned InReg = VMI->second;
676
677 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000678 if (VT != MVT::Vector) {
679 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000680
Chris Lattner5fe1f542006-03-31 02:06:56 +0000681 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
682 if (DestVT < VT) {
683 // Source must be expanded. This input value is actually coming from the
684 // register pair VMI->second and VMI->second+1.
685 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
686 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
687 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000688 if (MVT::isFloatingPoint(VT))
689 N = DAG.getNode(ISD::FP_ROUND, VT, N);
690 else
691 N = DAG.getNode(ISD::TRUNCATE, VT, N);
692 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000693 } else {
694 // Otherwise, if this is a vector, make it available as a generic vector
695 // here.
696 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000697 const PackedType *PTy = cast<PackedType>(VTy);
698 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000699 PTyLegalElementVT);
700
701 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000702 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000703 if (PTyElementVT == PTyLegalElementVT) {
704 // If the value types are legal, just VBUILD the CopyFromReg nodes.
705 for (unsigned i = 0; i != NE; ++i)
706 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT));
708 } else if (PTyElementVT < PTyLegalElementVT) {
709 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
710 for (unsigned i = 0; i != NE; ++i) {
711 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
712 PTyElementVT);
713 if (MVT::isFloatingPoint(PTyElementVT))
714 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
715 else
716 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
717 Ops.push_back(Op);
718 }
719 } else {
720 // If the register was expanded, use BUILD_PAIR.
721 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
722 for (unsigned i = 0; i != NE/2; ++i) {
723 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 PTyElementVT);
727 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
728 }
729 }
730
731 Ops.push_back(DAG.getConstant(NE, MVT::i32));
732 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000733 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000734
735 // Finally, use a VBIT_CONVERT to make this available as the appropriate
736 // vector type.
737 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
738 DAG.getConstant(PTy->getNumElements(),
739 MVT::i32),
740 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000741 }
742
743 return N;
744}
745
746
Chris Lattner7a60d912005-01-07 07:47:53 +0000747void SelectionDAGLowering::visitRet(ReturnInst &I) {
748 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000749 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000750 return;
751 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000752 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000753 NewValues.push_back(getRoot());
754 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
755 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000756 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000757
758 // If this is an integer return value, we need to promote it ourselves to
759 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
760 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000761 // FIXME: C calling convention requires the return type to be promoted to
762 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000763 if (MVT::isInteger(RetOp.getValueType()) &&
764 RetOp.getValueType() < MVT::i64) {
765 MVT::ValueType TmpVT;
766 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
767 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
768 else
769 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000770
Evan Chenga2e99532006-05-26 23:09:09 +0000771 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000772 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
773 else
774 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
775 }
776 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000777 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000778 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000779 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
780 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000781}
782
Chris Lattnered0110b2006-10-27 21:36:01 +0000783/// ExportFromCurrentBlock - If this condition isn't known to be exported from
784/// the current basic block, add it to ValueMap now so that we'll get a
785/// CopyTo/FromReg.
786void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
787 // No need to export constants.
788 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
789
790 // Already exported?
791 if (FuncInfo.isExportedInst(V)) return;
792
793 unsigned Reg = FuncInfo.InitializeRegForValue(V);
794 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
795}
796
Chris Lattner84a03502006-10-27 23:50:33 +0000797bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
798 const BasicBlock *FromBB) {
799 // The operands of the setcc have to be in this block. We don't know
800 // how to export them from some other block.
801 if (Instruction *VI = dyn_cast<Instruction>(V)) {
802 // Can export from current BB.
803 if (VI->getParent() == FromBB)
804 return true;
805
806 // Is already exported, noop.
807 return FuncInfo.isExportedInst(V);
808 }
809
810 // If this is an argument, we can export it if the BB is the entry block or
811 // if it is already exported.
812 if (isa<Argument>(V)) {
813 if (FromBB == &FromBB->getParent()->getEntryBlock())
814 return true;
815
816 // Otherwise, can only export this if it is already exported.
817 return FuncInfo.isExportedInst(V);
818 }
819
820 // Otherwise, constants can always be exported.
821 return true;
822}
823
Chris Lattnere60ae822006-10-29 21:01:20 +0000824static bool InBlock(const Value *V, const BasicBlock *BB) {
825 if (const Instruction *I = dyn_cast<Instruction>(V))
826 return I->getParent() == BB;
827 return true;
828}
829
Chris Lattnered0110b2006-10-27 21:36:01 +0000830/// FindMergedConditions - If Cond is an expression like
831void SelectionDAGLowering::FindMergedConditions(Value *Cond,
832 MachineBasicBlock *TBB,
833 MachineBasicBlock *FBB,
834 MachineBasicBlock *CurBB,
835 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000836 // If this node is not part of the or/and tree, emit it as a branch.
837 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
838
839 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000840 BOp->getParent() != CurBB->getBasicBlock() ||
841 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
842 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000843 const BasicBlock *BB = CurBB->getBasicBlock();
844
Chris Lattner427301f2006-10-31 22:37:42 +0000845 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
846 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
847 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
848 // The operands of the setcc have to be in this block. We don't know
849 // how to export them from some other block. If this is the first
850 // block of the sequence, no exporting is needed.
851 (CurBB == CurMBB ||
852 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
853 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
854 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
855 II->getOperand(2), TBB, FBB, CurBB);
856 SwitchCases.push_back(CB);
857 return;
858 }
859
860
Chris Lattnered0110b2006-10-27 21:36:01 +0000861 // If the leaf of the tree is a setcond inst, merge the condition into the
862 // caseblock.
863 if (BOp && isa<SetCondInst>(BOp) &&
864 // The operands of the setcc have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000865 // how to export them from some other block. If this is the first block
866 // of the sequence, no exporting is needed.
867 (CurBB == CurMBB ||
868 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
869 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000870 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
871 switch (BOp->getOpcode()) {
872 default: assert(0 && "Unknown setcc opcode!");
873 case Instruction::SetEQ:
874 SignCond = ISD::SETEQ;
875 UnsCond = ISD::SETEQ;
876 FPCond = ISD::SETOEQ;
877 break;
878 case Instruction::SetNE:
879 SignCond = ISD::SETNE;
880 UnsCond = ISD::SETNE;
881 FPCond = ISD::SETUNE;
882 break;
883 case Instruction::SetLE:
884 SignCond = ISD::SETLE;
885 UnsCond = ISD::SETULE;
886 FPCond = ISD::SETOLE;
887 break;
888 case Instruction::SetGE:
889 SignCond = ISD::SETGE;
890 UnsCond = ISD::SETUGE;
891 FPCond = ISD::SETOGE;
892 break;
893 case Instruction::SetLT:
894 SignCond = ISD::SETLT;
895 UnsCond = ISD::SETULT;
896 FPCond = ISD::SETOLT;
897 break;
898 case Instruction::SetGT:
899 SignCond = ISD::SETGT;
900 UnsCond = ISD::SETUGT;
901 FPCond = ISD::SETOGT;
902 break;
903 }
904
905 const Type *OpType = BOp->getOperand(0)->getType();
906 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
907 OpType = PTy->getElementType();
908
909 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
910 Condition = FPCond;
911 else if (OpType->isUnsigned())
912 Condition = UnsCond;
913 else
914 Condition = SignCond;
915
916 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
917 BOp->getOperand(1), TBB, FBB, CurBB);
918 SwitchCases.push_back(CB);
919 return;
920 }
921
922 // Create a CaseBlock record representing this branch.
923 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
924 TBB, FBB, CurBB);
925 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000926 return;
927 }
928
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000929
930 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000931 MachineFunction::iterator BBI = CurBB;
932 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
933 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
934
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000935 if (Opc == Instruction::Or) {
936 // Codegen X | Y as:
937 // jmp_if_X TBB
938 // jmp TmpBB
939 // TmpBB:
940 // jmp_if_Y TBB
941 // jmp FBB
942 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000943
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000944 // Emit the LHS condition.
945 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
946
947 // Emit the RHS condition into TmpBB.
948 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
949 } else {
950 assert(Opc == Instruction::And && "Unknown merge op!");
951 // Codegen X & Y as:
952 // jmp_if_X TmpBB
953 // jmp FBB
954 // TmpBB:
955 // jmp_if_Y TBB
956 // jmp FBB
957 //
958 // This requires creation of TmpBB after CurBB.
959
960 // Emit the LHS condition.
961 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
962
963 // Emit the RHS condition into TmpBB.
964 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
965 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000966}
967
Chris Lattner427301f2006-10-31 22:37:42 +0000968/// If the set of cases should be emitted as a series of branches, return true.
969/// If we should emit this as a bunch of and/or'd together conditions, return
970/// false.
971static bool
972ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
973 if (Cases.size() != 2) return true;
974
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000975 // If this is two comparisons of the same values or'd or and'd together, they
976 // will get folded into a single comparison, so don't emit two blocks.
977 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
978 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
979 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
980 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
981 return false;
982 }
983
Chris Lattner427301f2006-10-31 22:37:42 +0000984 return true;
985}
986
Chris Lattner7a60d912005-01-07 07:47:53 +0000987void SelectionDAGLowering::visitBr(BranchInst &I) {
988 // Update machine-CFG edges.
989 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000990
991 // Figure out which block is immediately after the current one.
992 MachineBasicBlock *NextBlock = 0;
993 MachineFunction::iterator BBI = CurMBB;
994 if (++BBI != CurMBB->getParent()->end())
995 NextBlock = BBI;
996
997 if (I.isUnconditional()) {
998 // If this is not a fall-through branch, emit the branch.
999 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001000 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001001 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001002
Chris Lattner963ddad2006-10-24 17:57:59 +00001003 // Update machine-CFG edges.
1004 CurMBB->addSuccessor(Succ0MBB);
1005
1006 return;
1007 }
1008
1009 // If this condition is one of the special cases we handle, do special stuff
1010 // now.
1011 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001012 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001013
1014 // If this is a series of conditions that are or'd or and'd together, emit
1015 // this as a sequence of branches instead of setcc's with and/or operations.
1016 // For example, instead of something like:
1017 // cmp A, B
1018 // C = seteq
1019 // cmp D, E
1020 // F = setle
1021 // or C, F
1022 // jnz foo
1023 // Emit:
1024 // cmp A, B
1025 // je foo
1026 // cmp D, E
1027 // jle foo
1028 //
1029 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1030 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001031 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001032 BOp->getOpcode() == Instruction::Or)) {
1033 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001034 // If the compares in later blocks need to use values not currently
1035 // exported from this block, export them now. This block should always
1036 // be the first entry.
1037 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1038
Chris Lattner427301f2006-10-31 22:37:42 +00001039 // Allow some cases to be rejected.
1040 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001041 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1042 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1043 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1044 }
1045
1046 // Emit the branch for this block.
1047 visitSwitchCase(SwitchCases[0]);
1048 SwitchCases.erase(SwitchCases.begin());
1049 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001050 }
1051
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001052 // Okay, we decided not to do this, remove any inserted MBB's and clear
1053 // SwitchCases.
1054 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1055 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1056
Chris Lattner427301f2006-10-31 22:37:42 +00001057 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001058 }
1059 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001060
1061 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +00001062 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001063 Succ0MBB, Succ1MBB, CurMBB);
1064 // Use visitSwitchCase to actually insert the fast branch sequence for this
1065 // cond branch.
1066 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001067}
1068
Nate Begemaned728c12006-03-27 01:32:24 +00001069/// visitSwitchCase - Emits the necessary code to represent a single node in
1070/// the binary search tree resulting from lowering a switch instruction.
1071void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001072 SDOperand Cond;
1073 SDOperand CondLHS = getValue(CB.CmpLHS);
1074
Chris Lattnered0110b2006-10-27 21:36:01 +00001075 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1076 // handle common cases produced by branch lowering.
1077 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001078 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001079 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1080 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1081 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1082 } else
1083 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001084
1085 // Set NextBlock to be the MBB immediately after the current one, if any.
1086 // This is used to avoid emitting unnecessary branches to the next block.
1087 MachineBasicBlock *NextBlock = 0;
1088 MachineFunction::iterator BBI = CurMBB;
1089 if (++BBI != CurMBB->getParent()->end())
1090 NextBlock = BBI;
1091
1092 // If the lhs block is the next block, invert the condition so that we can
1093 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001094 if (CB.TrueBB == NextBlock) {
1095 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001096 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1097 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1098 }
1099 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001100 DAG.getBasicBlock(CB.TrueBB));
1101 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001102 DAG.setRoot(BrCond);
1103 else
1104 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001105 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001106 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001107 CurMBB->addSuccessor(CB.TrueBB);
1108 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001109}
1110
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001111void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001112 // Emit the code for the jump table
1113 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001114 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1115 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1116 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1117 Table, Index));
1118 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001119}
1120
Nate Begemaned728c12006-03-27 01:32:24 +00001121void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1122 // Figure out which block is immediately after the current one.
1123 MachineBasicBlock *NextBlock = 0;
1124 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001125
Nate Begemaned728c12006-03-27 01:32:24 +00001126 if (++BBI != CurMBB->getParent()->end())
1127 NextBlock = BBI;
1128
Chris Lattner6d6fc262006-10-22 21:36:53 +00001129 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1130
Nate Begemaned728c12006-03-27 01:32:24 +00001131 // If there is only the default destination, branch to it if it is not the
1132 // next basic block. Otherwise, just fall through.
1133 if (I.getNumOperands() == 2) {
1134 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001135
Nate Begemaned728c12006-03-27 01:32:24 +00001136 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001137 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001138 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001139 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001140
Chris Lattner6d6fc262006-10-22 21:36:53 +00001141 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001142 return;
1143 }
1144
1145 // If there are any non-default case statements, create a vector of Cases
1146 // representing each one, and sort the vector so that we can efficiently
1147 // create a binary search tree from them.
1148 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001149
Nate Begemaned728c12006-03-27 01:32:24 +00001150 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1151 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1152 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1153 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001154
Nate Begemaned728c12006-03-27 01:32:24 +00001155 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1156
1157 // Get the Value to be switched on and default basic blocks, which will be
1158 // inserted into CaseBlock records, representing basic blocks in the binary
1159 // search tree.
1160 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001161
1162 // Get the MachineFunction which holds the current MBB. This is used during
1163 // emission of jump tables, and when inserting any additional MBBs necessary
1164 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001165 MachineFunction *CurMF = CurMBB->getParent();
1166 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001167
1168 // If the switch has few cases (two or less) emit a series of specific
1169 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001170 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001171 // TODO: If any two of the cases has the same destination, and if one value
1172 // is the same as the other, but has one bit unset that the other has set,
1173 // use bit manipulation to do two compares at once. For example:
1174 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1175
Chris Lattner4c931502006-10-23 18:38:22 +00001176 // Rearrange the case blocks so that the last one falls through if possible.
1177 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1178 // The last case block won't fall through into 'NextBlock' if we emit the
1179 // branches in this order. See if rearranging a case value would help.
1180 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1181 if (Cases[i].second == NextBlock) {
1182 std::swap(Cases[i], Cases.back());
1183 break;
1184 }
1185 }
1186 }
1187
Chris Lattner6d6fc262006-10-22 21:36:53 +00001188 // Create a CaseBlock record representing a conditional branch to
1189 // the Case's target mbb if the value being switched on SV is equal
1190 // to C.
1191 MachineBasicBlock *CurBlock = CurMBB;
1192 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1193 MachineBasicBlock *FallThrough;
1194 if (i != e-1) {
1195 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1196 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1197 } else {
1198 // If the last case doesn't match, go to the default block.
1199 FallThrough = Default;
1200 }
1201
1202 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1203 Cases[i].second, FallThrough, CurBlock);
1204
1205 // If emitting the first comparison, just call visitSwitchCase to emit the
1206 // code into the current block. Otherwise, push the CaseBlock onto the
1207 // vector to be later processed by SDISel, and insert the node's MBB
1208 // before the next MBB.
1209 if (CurBlock == CurMBB)
1210 visitSwitchCase(CB);
1211 else
1212 SwitchCases.push_back(CB);
1213
1214 CurBlock = FallThrough;
1215 }
1216 return;
1217 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001218
Nate Begemand7a19102006-05-08 16:51:36 +00001219 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1220 // target supports indirect branches, then emit a jump table rather than
1221 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001222 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1223 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001224 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001225 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1226 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001227 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1228
Nate Begemand7a19102006-05-08 16:51:36 +00001229 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001230 // Create a new basic block to hold the code for loading the address
1231 // of the jump table, and jumping to it. Update successor information;
1232 // we will either branch to the default case for the switch, or the jump
1233 // table.
1234 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1235 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1236 CurMBB->addSuccessor(Default);
1237 CurMBB->addSuccessor(JumpTableBB);
1238
1239 // Subtract the lowest switch case value from the value being switched on
1240 // and conditional branch to default mbb if the result is greater than the
1241 // difference between smallest and largest cases.
1242 SDOperand SwitchOp = getValue(SV);
1243 MVT::ValueType VT = SwitchOp.getValueType();
1244 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1245 DAG.getConstant(First, VT));
1246
1247 // The SDNode we just created, which holds the value being switched on
1248 // minus the the smallest case value, needs to be copied to a virtual
1249 // register so it can be used as an index into the jump table in a
1250 // subsequent basic block. This value may be smaller or larger than the
1251 // target's pointer type, and therefore require extension or truncating.
1252 if (VT > TLI.getPointerTy())
1253 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1254 else
1255 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001256
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001257 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1258 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1259
1260 // Emit the range check for the jump table, and branch to the default
1261 // block for the switch statement if the value being switched on exceeds
1262 // the largest case in the switch.
1263 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1264 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1265 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1266 DAG.getBasicBlock(Default)));
1267
Nate Begemandf488392006-05-03 03:48:02 +00001268 // Build a vector of destination BBs, corresponding to each target
1269 // of the jump table. If the value of the jump table slot corresponds to
1270 // a case statement, push the case's BB onto the vector, otherwise, push
1271 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001272 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001273 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001274 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001275 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001276 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001277 ++ii;
1278 } else {
1279 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001280 }
Nate Begemandf488392006-05-03 03:48:02 +00001281
Chris Lattner84a03502006-10-27 23:50:33 +00001282 // Update successor info. Add one edge to each unique successor.
1283 // Vector bool would be better, but vector<bool> is really slow.
1284 std::vector<unsigned char> SuccsHandled;
1285 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1286
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001287 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001288 E = DestBBs.end(); I != E; ++I) {
1289 if (!SuccsHandled[(*I)->getNumber()]) {
1290 SuccsHandled[(*I)->getNumber()] = true;
1291 JumpTableBB->addSuccessor(*I);
1292 }
1293 }
Nate Begemandf488392006-05-03 03:48:02 +00001294
1295 // Create a jump table index for this jump table, or return an existing
1296 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001297 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1298
1299 // Set the jump table information so that we can codegen it as a second
1300 // MachineBasicBlock
1301 JT.Reg = JumpTableReg;
1302 JT.JTI = JTI;
1303 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001304 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001305 return;
1306 }
1307 }
Nate Begemaned728c12006-03-27 01:32:24 +00001308
1309 // Push the initial CaseRec onto the worklist
1310 std::vector<CaseRec> CaseVec;
1311 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1312
1313 while (!CaseVec.empty()) {
1314 // Grab a record representing a case range to process off the worklist
1315 CaseRec CR = CaseVec.back();
1316 CaseVec.pop_back();
1317
1318 // Size is the number of Cases represented by this range. If Size is 1,
1319 // then we are processing a leaf of the binary search tree. Otherwise,
1320 // we need to pick a pivot, and push left and right ranges onto the
1321 // worklist.
1322 unsigned Size = CR.Range.second - CR.Range.first;
1323
1324 if (Size == 1) {
1325 // Create a CaseBlock record representing a conditional branch to
1326 // the Case's target mbb if the value being switched on SV is equal
1327 // to C. Otherwise, branch to default.
1328 Constant *C = CR.Range.first->first;
1329 MachineBasicBlock *Target = CR.Range.first->second;
1330 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1331 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001332
Nate Begemaned728c12006-03-27 01:32:24 +00001333 // If the MBB representing the leaf node is the current MBB, then just
1334 // call visitSwitchCase to emit the code into the current block.
1335 // Otherwise, push the CaseBlock onto the vector to be later processed
1336 // by SDISel, and insert the node's MBB before the next MBB.
1337 if (CR.CaseBB == CurMBB)
1338 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001339 else
Nate Begemaned728c12006-03-27 01:32:24 +00001340 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001341 } else {
1342 // split case range at pivot
1343 CaseItr Pivot = CR.Range.first + (Size / 2);
1344 CaseRange LHSR(CR.Range.first, Pivot);
1345 CaseRange RHSR(Pivot, CR.Range.second);
1346 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001347 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001348
Nate Begemaned728c12006-03-27 01:32:24 +00001349 // We know that we branch to the LHS if the Value being switched on is
1350 // less than the Pivot value, C. We use this to optimize our binary
1351 // tree a bit, by recognizing that if SV is greater than or equal to the
1352 // LHS's Case Value, and that Case Value is exactly one less than the
1353 // Pivot's Value, then we can branch directly to the LHS's Target,
1354 // rather than creating a leaf node for it.
1355 if ((LHSR.second - LHSR.first) == 1 &&
1356 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001357 cast<ConstantIntegral>(C)->getZExtValue() ==
1358 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001359 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001360 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001361 TrueBB = new MachineBasicBlock(LLVMBB);
1362 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1363 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001364 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001365
Nate Begemaned728c12006-03-27 01:32:24 +00001366 // Similar to the optimization above, if the Value being switched on is
1367 // known to be less than the Constant CR.LT, and the current Case Value
1368 // is CR.LT - 1, then we can branch directly to the target block for
1369 // the current Case Value, rather than emitting a RHS leaf node for it.
1370 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001371 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1372 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001373 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001374 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001375 FalseBB = new MachineBasicBlock(LLVMBB);
1376 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1377 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001378 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001379
Nate Begemaned728c12006-03-27 01:32:24 +00001380 // Create a CaseBlock record representing a conditional branch to
1381 // the LHS node if the value being switched on SV is less than C.
1382 // Otherwise, branch to LHS.
1383 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001384 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001385
Nate Begemaned728c12006-03-27 01:32:24 +00001386 if (CR.CaseBB == CurMBB)
1387 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001388 else
Nate Begemaned728c12006-03-27 01:32:24 +00001389 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001390 }
1391 }
1392}
1393
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001394void SelectionDAGLowering::visitSub(User &I) {
1395 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001396 if (I.getType()->isFloatingPoint()) {
1397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1398 if (CFP->isExactlyValue(-0.0)) {
1399 SDOperand Op2 = getValue(I.getOperand(1));
1400 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1401 return;
1402 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001403 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1404 } else
1405 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001406}
1407
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001408void
1409SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001410 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001411 SDOperand Op1 = getValue(I.getOperand(0));
1412 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001413
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001414 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001415 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1416 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1417 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001418 } else {
1419 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1420 }
1421}
1422
1423void
1424SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1425 const Type *Ty = I.getType();
1426 SDOperand Op1 = getValue(I.getOperand(0));
1427 SDOperand Op2 = getValue(I.getOperand(1));
1428
1429 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1430 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1431 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1432 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1433 } else {
1434 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001435 }
Nate Begeman127321b2005-11-18 07:42:56 +00001436}
Chris Lattner96c26752005-01-19 22:31:21 +00001437
Nate Begeman127321b2005-11-18 07:42:56 +00001438void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1439 SDOperand Op1 = getValue(I.getOperand(0));
1440 SDOperand Op2 = getValue(I.getOperand(1));
1441
1442 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1443
Chris Lattner7a60d912005-01-07 07:47:53 +00001444 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1445}
1446
Reid Spencerd9436b62006-11-20 01:22:35 +00001447void SelectionDAGLowering::visitICmp(User &I) {
1448 ICmpInst *IC = cast<ICmpInst>(&I);
1449 SDOperand Op1 = getValue(IC->getOperand(0));
1450 SDOperand Op2 = getValue(IC->getOperand(1));
1451 ISD::CondCode Opcode;
1452 switch (IC->getPredicate()) {
1453 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1454 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1455 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1456 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1457 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1458 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1459 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1460 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1461 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1462 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1463 default:
1464 assert(!"Invalid ICmp predicate value");
1465 Opcode = ISD::SETEQ;
1466 break;
1467 }
1468 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1469}
1470
1471void SelectionDAGLowering::visitFCmp(User &I) {
1472 FCmpInst *FC = cast<FCmpInst>(&I);
1473 SDOperand Op1 = getValue(FC->getOperand(0));
1474 SDOperand Op2 = getValue(FC->getOperand(1));
1475 ISD::CondCode Opcode;
1476 switch (FC->getPredicate()) {
1477 case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
1478 case FCmpInst::FCMP_OEQ : Opcode = ISD::SETOEQ;
1479 case FCmpInst::FCMP_OGT : Opcode = ISD::SETOGT;
1480 case FCmpInst::FCMP_OGE : Opcode = ISD::SETOGE;
1481 case FCmpInst::FCMP_OLT : Opcode = ISD::SETOLT;
1482 case FCmpInst::FCMP_OLE : Opcode = ISD::SETOLE;
1483 case FCmpInst::FCMP_ONE : Opcode = ISD::SETONE;
1484 case FCmpInst::FCMP_ORD : Opcode = ISD::SETO;
1485 case FCmpInst::FCMP_UNO : Opcode = ISD::SETUO;
1486 case FCmpInst::FCMP_UEQ : Opcode = ISD::SETUEQ;
1487 case FCmpInst::FCMP_UGT : Opcode = ISD::SETUGT;
1488 case FCmpInst::FCMP_UGE : Opcode = ISD::SETUGE;
1489 case FCmpInst::FCMP_ULT : Opcode = ISD::SETULT;
1490 case FCmpInst::FCMP_ULE : Opcode = ISD::SETULE;
1491 case FCmpInst::FCMP_UNE : Opcode = ISD::SETUNE;
1492 case FCmpInst::FCMP_TRUE : Opcode = ISD::SETTRUE;
1493 default:
1494 assert(!"Invalid FCmp predicate value");
1495 Opcode = ISD::SETFALSE;
1496 break;
1497 }
1498 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1499}
1500
Chris Lattner7a60d912005-01-07 07:47:53 +00001501void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001502 ISD::CondCode UnsignedOpcode,
1503 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001504 SDOperand Op1 = getValue(I.getOperand(0));
1505 SDOperand Op2 = getValue(I.getOperand(1));
1506 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001507 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001508 Opcode = FPOpcode;
1509 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001510 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001511 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001512}
1513
1514void SelectionDAGLowering::visitSelect(User &I) {
1515 SDOperand Cond = getValue(I.getOperand(0));
1516 SDOperand TrueVal = getValue(I.getOperand(1));
1517 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001518 if (!isa<PackedType>(I.getType())) {
1519 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1520 TrueVal, FalseVal));
1521 } else {
1522 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1523 *(TrueVal.Val->op_end()-2),
1524 *(TrueVal.Val->op_end()-1)));
1525 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001526}
1527
1528void SelectionDAGLowering::visitCast(User &I) {
1529 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001530 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001531 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001532
Chris Lattner2f4119a2006-03-22 20:09:35 +00001533 if (DestVT == MVT::Vector) {
1534 // This is a cast to a vector from something else. This is always a bit
1535 // convert. Get information about the input vector.
1536 const PackedType *DestTy = cast<PackedType>(I.getType());
1537 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1538 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1539 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1540 DAG.getValueType(EltVT)));
1541 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001542 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001543 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001544 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001545 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001546 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001547 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001548 } else if (isInteger(SrcVT)) {
1549 if (isInteger(DestVT)) { // Int -> Int cast
1550 if (DestVT < SrcVT) // Truncating cast?
1551 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001552 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001553 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001554 else
Chris Lattner4024c002006-03-15 22:19:46 +00001555 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001556 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001557 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001558 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001559 else
Chris Lattner4024c002006-03-15 22:19:46 +00001560 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001561 } else {
1562 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001563 }
Chris Lattner4024c002006-03-15 22:19:46 +00001564 } else if (isFloatingPoint(SrcVT)) {
1565 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1566 if (DestVT < SrcVT) // Rounding cast?
1567 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001568 else
Chris Lattner4024c002006-03-15 22:19:46 +00001569 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001570 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001571 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001572 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001573 else
Chris Lattner4024c002006-03-15 22:19:46 +00001574 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001575 } else {
1576 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001577 }
1578 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001579 assert(SrcVT == MVT::Vector && "Unknown cast!");
1580 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1581 // This is a cast from a vector to something else. This is always a bit
1582 // convert. Get information about the input vector.
1583 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001584 }
1585}
1586
Chris Lattner67271862006-03-29 00:11:43 +00001587void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001588 SDOperand InVec = getValue(I.getOperand(0));
1589 SDOperand InVal = getValue(I.getOperand(1));
1590 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1591 getValue(I.getOperand(2)));
1592
Chris Lattner29b23012006-03-19 01:17:20 +00001593 SDOperand Num = *(InVec.Val->op_end()-2);
1594 SDOperand Typ = *(InVec.Val->op_end()-1);
1595 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1596 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001597}
1598
Chris Lattner67271862006-03-29 00:11:43 +00001599void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001600 SDOperand InVec = getValue(I.getOperand(0));
1601 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1602 getValue(I.getOperand(1)));
1603 SDOperand Typ = *(InVec.Val->op_end()-1);
1604 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1605 TLI.getValueType(I.getType()), InVec, InIdx));
1606}
Chris Lattner32206f52006-03-18 01:44:44 +00001607
Chris Lattner098c01e2006-04-08 04:15:24 +00001608void SelectionDAGLowering::visitShuffleVector(User &I) {
1609 SDOperand V1 = getValue(I.getOperand(0));
1610 SDOperand V2 = getValue(I.getOperand(1));
1611 SDOperand Mask = getValue(I.getOperand(2));
1612
1613 SDOperand Num = *(V1.Val->op_end()-2);
1614 SDOperand Typ = *(V2.Val->op_end()-1);
1615 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1616 V1, V2, Mask, Num, Typ));
1617}
1618
1619
Chris Lattner7a60d912005-01-07 07:47:53 +00001620void SelectionDAGLowering::visitGetElementPtr(User &I) {
1621 SDOperand N = getValue(I.getOperand(0));
1622 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001623
1624 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1625 OI != E; ++OI) {
1626 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001627 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001628 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001629 if (Field) {
1630 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001631 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001632 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001633 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001634 }
1635 Ty = StTy->getElementType(Field);
1636 } else {
1637 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001638
Chris Lattner43535a12005-11-09 04:45:33 +00001639 // If this is a constant subscript, handle it quickly.
1640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001641 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001642 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001643 if (CI->getType()->isSigned())
1644 Offs = (int64_t)
1645 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001646 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001647 Offs =
1648 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001649 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1650 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001651 }
Chris Lattner43535a12005-11-09 04:45:33 +00001652
1653 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001654 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001655 SDOperand IdxN = getValue(Idx);
1656
1657 // If the index is smaller or larger than intptr_t, truncate or extend
1658 // it.
1659 if (IdxN.getValueType() < N.getValueType()) {
1660 if (Idx->getType()->isSigned())
1661 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1662 else
1663 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1664 } else if (IdxN.getValueType() > N.getValueType())
1665 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1666
1667 // If this is a multiply by a power of two, turn it into a shl
1668 // immediately. This is a very common case.
1669 if (isPowerOf2_64(ElementSize)) {
1670 unsigned Amt = Log2_64(ElementSize);
1671 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001672 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001673 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1674 continue;
1675 }
1676
1677 SDOperand Scale = getIntPtrConstant(ElementSize);
1678 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1679 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001680 }
1681 }
1682 setValue(&I, N);
1683}
1684
1685void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1686 // If this is a fixed sized alloca in the entry block of the function,
1687 // allocate it statically on the stack.
1688 if (FuncInfo.StaticAllocaMap.count(&I))
1689 return; // getValue will auto-populate this.
1690
1691 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001692 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1693 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001694 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001695
1696 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001697 MVT::ValueType IntPtr = TLI.getPointerTy();
1698 if (IntPtr < AllocSize.getValueType())
1699 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1700 else if (IntPtr > AllocSize.getValueType())
1701 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001702
Chris Lattnereccb73d2005-01-22 23:04:37 +00001703 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001704 getIntPtrConstant(TySize));
1705
1706 // Handle alignment. If the requested alignment is less than or equal to the
1707 // stack alignment, ignore it and round the size of the allocation up to the
1708 // stack alignment size. If the size is greater than the stack alignment, we
1709 // note this in the DYNAMIC_STACKALLOC node.
1710 unsigned StackAlign =
1711 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1712 if (Align <= StackAlign) {
1713 Align = 0;
1714 // Add SA-1 to the size.
1715 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1716 getIntPtrConstant(StackAlign-1));
1717 // Mask out the low bits for alignment purposes.
1718 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1719 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1720 }
1721
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001722 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001723 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1724 MVT::Other);
1725 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001726 DAG.setRoot(setValue(&I, DSA).getValue(1));
1727
1728 // Inform the Frame Information that we have just allocated a variable-sized
1729 // object.
1730 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1731}
1732
Chris Lattner7a60d912005-01-07 07:47:53 +00001733void SelectionDAGLowering::visitLoad(LoadInst &I) {
1734 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001735
Chris Lattner4d9651c2005-01-17 22:19:26 +00001736 SDOperand Root;
1737 if (I.isVolatile())
1738 Root = getRoot();
1739 else {
1740 // Do not serialize non-volatile loads against each other.
1741 Root = DAG.getRoot();
1742 }
Chris Lattner4024c002006-03-15 22:19:46 +00001743
Evan Chenge71fe34d2006-10-09 20:57:25 +00001744 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001745 Root, I.isVolatile()));
1746}
1747
1748SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001749 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001750 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001751 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001752 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001753 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001754 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1755 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001756 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001757 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001758 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001759
Chris Lattner4024c002006-03-15 22:19:46 +00001760 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001761 DAG.setRoot(L.getValue(1));
1762 else
1763 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001764
1765 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001766}
1767
1768
1769void SelectionDAGLowering::visitStore(StoreInst &I) {
1770 Value *SrcV = I.getOperand(0);
1771 SDOperand Src = getValue(SrcV);
1772 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001773 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1774 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001775}
1776
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001777/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1778/// access memory and has no other side effects at all.
1779static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1780#define GET_NO_MEMORY_INTRINSICS
1781#include "llvm/Intrinsics.gen"
1782#undef GET_NO_MEMORY_INTRINSICS
1783 return false;
1784}
1785
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001786// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1787// have any side-effects or if it only reads memory.
1788static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1789#define GET_SIDE_EFFECT_INFO
1790#include "llvm/Intrinsics.gen"
1791#undef GET_SIDE_EFFECT_INFO
1792 return false;
1793}
1794
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001795/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1796/// node.
1797void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1798 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001799 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001800 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001801
1802 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001803 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001804 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1805 if (OnlyLoad) {
1806 // We don't need to serialize loads against other loads.
1807 Ops.push_back(DAG.getRoot());
1808 } else {
1809 Ops.push_back(getRoot());
1810 }
1811 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001812
1813 // Add the intrinsic ID as an integer operand.
1814 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1815
1816 // Add all operands of the call to the operand list.
1817 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1818 SDOperand Op = getValue(I.getOperand(i));
1819
1820 // If this is a vector type, force it to the right packed type.
1821 if (Op.getValueType() == MVT::Vector) {
1822 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1823 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1824
1825 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1826 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1827 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1828 }
1829
1830 assert(TLI.isTypeLegal(Op.getValueType()) &&
1831 "Intrinsic uses a non-legal type?");
1832 Ops.push_back(Op);
1833 }
1834
1835 std::vector<MVT::ValueType> VTs;
1836 if (I.getType() != Type::VoidTy) {
1837 MVT::ValueType VT = TLI.getValueType(I.getType());
1838 if (VT == MVT::Vector) {
1839 const PackedType *DestTy = cast<PackedType>(I.getType());
1840 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1841
1842 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1843 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1844 }
1845
1846 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1847 VTs.push_back(VT);
1848 }
1849 if (HasChain)
1850 VTs.push_back(MVT::Other);
1851
Chris Lattnerbd887772006-08-14 23:53:35 +00001852 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1853
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001854 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001855 SDOperand Result;
1856 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001857 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1858 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001859 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001860 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1861 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001862 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001863 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1864 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001865
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001866 if (HasChain) {
1867 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1868 if (OnlyLoad)
1869 PendingLoads.push_back(Chain);
1870 else
1871 DAG.setRoot(Chain);
1872 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001873 if (I.getType() != Type::VoidTy) {
1874 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1875 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1876 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1877 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1878 DAG.getValueType(EVT));
1879 }
1880 setValue(&I, Result);
1881 }
1882}
1883
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001884/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1885/// we want to emit this as a call to a named external function, return the name
1886/// otherwise lower it and return null.
1887const char *
1888SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1889 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001890 default:
1891 // By default, turn this into a target intrinsic node.
1892 visitTargetIntrinsic(I, Intrinsic);
1893 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001894 case Intrinsic::vastart: visitVAStart(I); return 0;
1895 case Intrinsic::vaend: visitVAEnd(I); return 0;
1896 case Intrinsic::vacopy: visitVACopy(I); return 0;
1897 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1898 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1899 case Intrinsic::setjmp:
1900 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1901 break;
1902 case Intrinsic::longjmp:
1903 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1904 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001905 case Intrinsic::memcpy_i32:
1906 case Intrinsic::memcpy_i64:
1907 visitMemIntrinsic(I, ISD::MEMCPY);
1908 return 0;
1909 case Intrinsic::memset_i32:
1910 case Intrinsic::memset_i64:
1911 visitMemIntrinsic(I, ISD::MEMSET);
1912 return 0;
1913 case Intrinsic::memmove_i32:
1914 case Intrinsic::memmove_i64:
1915 visitMemIntrinsic(I, ISD::MEMMOVE);
1916 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001917
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001918 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001919 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001920 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001921 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001922 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001923
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001924 Ops[0] = getRoot();
1925 Ops[1] = getValue(SPI.getLineValue());
1926 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001927
Jim Laskeya8bdac82006-03-23 18:06:46 +00001928 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001929 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001930 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1931
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001932 Ops[3] = DAG.getString(CompileUnit->getFileName());
1933 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001934
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001935 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001936 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001937
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001938 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001939 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001940 case Intrinsic::dbg_region_start: {
1941 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1942 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001943 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001944 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001945 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1946 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001947 }
1948
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001949 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001950 }
1951 case Intrinsic::dbg_region_end: {
1952 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1953 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001954 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001955 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001956 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1957 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001958 }
1959
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001960 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001961 }
1962 case Intrinsic::dbg_func_start: {
1963 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1964 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001965 if (DebugInfo && FSI.getSubprogram() &&
1966 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001967 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001968 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1969 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001970 }
1971
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001972 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001973 }
1974 case Intrinsic::dbg_declare: {
1975 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1976 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001977 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001978 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001979 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001980 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001981 }
1982
1983 return 0;
1984 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001985
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001986 case Intrinsic::isunordered_f32:
1987 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001988 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1989 getValue(I.getOperand(2)), ISD::SETUO));
1990 return 0;
1991
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001992 case Intrinsic::sqrt_f32:
1993 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001994 setValue(&I, DAG.getNode(ISD::FSQRT,
1995 getValue(I.getOperand(1)).getValueType(),
1996 getValue(I.getOperand(1))));
1997 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001998 case Intrinsic::powi_f32:
1999 case Intrinsic::powi_f64:
2000 setValue(&I, DAG.getNode(ISD::FPOWI,
2001 getValue(I.getOperand(1)).getValueType(),
2002 getValue(I.getOperand(1)),
2003 getValue(I.getOperand(2))));
2004 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002005 case Intrinsic::pcmarker: {
2006 SDOperand Tmp = getValue(I.getOperand(1));
2007 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2008 return 0;
2009 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002010 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002011 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002012 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2013 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2014 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002015 setValue(&I, Tmp);
2016 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002017 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002018 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002019 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002020 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002021 case Intrinsic::bswap_i64:
2022 setValue(&I, DAG.getNode(ISD::BSWAP,
2023 getValue(I.getOperand(1)).getValueType(),
2024 getValue(I.getOperand(1))));
2025 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002026 case Intrinsic::cttz_i8:
2027 case Intrinsic::cttz_i16:
2028 case Intrinsic::cttz_i32:
2029 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002030 setValue(&I, DAG.getNode(ISD::CTTZ,
2031 getValue(I.getOperand(1)).getValueType(),
2032 getValue(I.getOperand(1))));
2033 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002034 case Intrinsic::ctlz_i8:
2035 case Intrinsic::ctlz_i16:
2036 case Intrinsic::ctlz_i32:
2037 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002038 setValue(&I, DAG.getNode(ISD::CTLZ,
2039 getValue(I.getOperand(1)).getValueType(),
2040 getValue(I.getOperand(1))));
2041 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002042 case Intrinsic::ctpop_i8:
2043 case Intrinsic::ctpop_i16:
2044 case Intrinsic::ctpop_i32:
2045 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002046 setValue(&I, DAG.getNode(ISD::CTPOP,
2047 getValue(I.getOperand(1)).getValueType(),
2048 getValue(I.getOperand(1))));
2049 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002050 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002051 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002052 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2053 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002054 setValue(&I, Tmp);
2055 DAG.setRoot(Tmp.getValue(1));
2056 return 0;
2057 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002058 case Intrinsic::stackrestore: {
2059 SDOperand Tmp = getValue(I.getOperand(1));
2060 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002061 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002062 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002063 case Intrinsic::prefetch:
2064 // FIXME: Currently discarding prefetches.
2065 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002066 }
2067}
2068
2069
Chris Lattner7a60d912005-01-07 07:47:53 +00002070void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002071 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002072 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00002073 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002074 if (unsigned IID = F->getIntrinsicID()) {
2075 RenameFn = visitIntrinsicCall(I, IID);
2076 if (!RenameFn)
2077 return;
2078 } else { // Not an LLVM intrinsic.
2079 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002080 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2081 if (I.getNumOperands() == 3 && // Basic sanity checks.
2082 I.getOperand(1)->getType()->isFloatingPoint() &&
2083 I.getType() == I.getOperand(1)->getType() &&
2084 I.getType() == I.getOperand(2)->getType()) {
2085 SDOperand LHS = getValue(I.getOperand(1));
2086 SDOperand RHS = getValue(I.getOperand(2));
2087 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2088 LHS, RHS));
2089 return;
2090 }
2091 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002092 if (I.getNumOperands() == 2 && // Basic sanity checks.
2093 I.getOperand(1)->getType()->isFloatingPoint() &&
2094 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002095 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002096 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2097 return;
2098 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002099 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002100 if (I.getNumOperands() == 2 && // Basic sanity checks.
2101 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002102 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002103 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002104 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2105 return;
2106 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002107 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002108 if (I.getNumOperands() == 2 && // Basic sanity checks.
2109 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002110 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002111 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002112 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2113 return;
2114 }
2115 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002116 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002117 } else if (isa<InlineAsm>(I.getOperand(0))) {
2118 visitInlineAsm(I);
2119 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002120 }
Misha Brukman835702a2005-04-21 22:36:52 +00002121
Chris Lattner18d2b342005-01-08 22:48:57 +00002122 SDOperand Callee;
2123 if (!RenameFn)
2124 Callee = getValue(I.getOperand(0));
2125 else
2126 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002127 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002128 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002129 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2130 Value *Arg = I.getOperand(i);
2131 SDOperand ArgNode = getValue(Arg);
2132 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2133 }
Misha Brukman835702a2005-04-21 22:36:52 +00002134
Nate Begemanf6565252005-03-26 01:29:23 +00002135 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2136 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002137
Chris Lattner1f45cd72005-01-08 19:26:18 +00002138 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002139 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002140 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002141 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002142 setValue(&I, Result.first);
2143 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002144}
2145
Chris Lattner6f87d182006-02-22 22:37:12 +00002146SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002147 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002148 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2149 Chain = Val.getValue(1);
2150 Flag = Val.getValue(2);
2151
2152 // If the result was expanded, copy from the top part.
2153 if (Regs.size() > 1) {
2154 assert(Regs.size() == 2 &&
2155 "Cannot expand to more than 2 elts yet!");
2156 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002157 Chain = Hi.getValue(1);
2158 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002159 if (DAG.getTargetLoweringInfo().isLittleEndian())
2160 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2161 else
2162 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002163 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002164
Chris Lattner705948d2006-06-08 18:22:48 +00002165 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002166 // appropriate type.
2167 if (RegVT == ValueVT)
2168 return Val;
2169
Chris Lattner705948d2006-06-08 18:22:48 +00002170 if (MVT::isInteger(RegVT)) {
2171 if (ValueVT < RegVT)
2172 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2173 else
2174 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2175 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002176 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002177 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002178}
2179
Chris Lattner571d9642006-02-23 19:21:04 +00002180/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2181/// specified value into the registers specified by this object. This uses
2182/// Chain/Flag as the input and updates them for the output Chain/Flag.
2183void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002184 SDOperand &Chain, SDOperand &Flag,
2185 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002186 if (Regs.size() == 1) {
2187 // If there is a single register and the types differ, this must be
2188 // a promotion.
2189 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002190 if (MVT::isInteger(RegVT)) {
2191 if (RegVT < ValueVT)
2192 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2193 else
2194 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2195 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002196 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2197 }
2198 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2199 Flag = Chain.getValue(1);
2200 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002201 std::vector<unsigned> R(Regs);
2202 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2203 std::reverse(R.begin(), R.end());
2204
2205 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002206 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002207 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002208 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002209 Flag = Chain.getValue(1);
2210 }
2211 }
2212}
Chris Lattner6f87d182006-02-22 22:37:12 +00002213
Chris Lattner571d9642006-02-23 19:21:04 +00002214/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2215/// operand list. This adds the code marker and includes the number of
2216/// values added into it.
2217void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002218 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002219 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2220 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2221 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2222}
Chris Lattner6f87d182006-02-22 22:37:12 +00002223
2224/// isAllocatableRegister - If the specified register is safe to allocate,
2225/// i.e. it isn't a stack pointer or some other special register, return the
2226/// register class for the register. Otherwise, return null.
2227static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002228isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2229 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002230 MVT::ValueType FoundVT = MVT::Other;
2231 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002232 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2233 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002234 MVT::ValueType ThisVT = MVT::Other;
2235
Chris Lattnerb1124f32006-02-22 23:09:03 +00002236 const TargetRegisterClass *RC = *RCI;
2237 // If none of the the value types for this register class are valid, we
2238 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002239 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2240 I != E; ++I) {
2241 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002242 // If we have already found this register in a different register class,
2243 // choose the one with the largest VT specified. For example, on
2244 // PowerPC, we favor f64 register classes over f32.
2245 if (FoundVT == MVT::Other ||
2246 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2247 ThisVT = *I;
2248 break;
2249 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002250 }
2251 }
2252
Chris Lattnerbec582f2006-04-02 00:24:45 +00002253 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002254
Chris Lattner6f87d182006-02-22 22:37:12 +00002255 // NOTE: This isn't ideal. In particular, this might allocate the
2256 // frame pointer in functions that need it (due to them not being taken
2257 // out of allocation, because a variable sized allocation hasn't been seen
2258 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002259 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2260 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002261 if (*I == Reg) {
2262 // We found a matching register class. Keep looking at others in case
2263 // we find one with larger registers that this physreg is also in.
2264 FoundRC = RC;
2265 FoundVT = ThisVT;
2266 break;
2267 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002268 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002269 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002270}
2271
2272RegsForValue SelectionDAGLowering::
2273GetRegistersForValue(const std::string &ConstrCode,
2274 MVT::ValueType VT, bool isOutReg, bool isInReg,
2275 std::set<unsigned> &OutputRegs,
2276 std::set<unsigned> &InputRegs) {
2277 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2278 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2279 std::vector<unsigned> Regs;
2280
2281 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2282 MVT::ValueType RegVT;
2283 MVT::ValueType ValueVT = VT;
2284
Chris Lattner55402d42006-11-02 01:41:49 +00002285 // If this is a constraint for a specific physical register, like {r17},
2286 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002287 if (PhysReg.first) {
2288 if (VT == MVT::Other)
2289 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002290
2291 // Get the actual register value type. This is important, because the user
2292 // may have asked for (e.g.) the AX register in i32 type. We need to
2293 // remember that AX is actually i16 to get the right extension.
2294 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002295
2296 // This is a explicit reference to a physical register.
2297 Regs.push_back(PhysReg.first);
2298
2299 // If this is an expanded reference, add the rest of the regs to Regs.
2300 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002301 TargetRegisterClass::iterator I = PhysReg.second->begin();
2302 TargetRegisterClass::iterator E = PhysReg.second->end();
2303 for (; *I != PhysReg.first; ++I)
2304 assert(I != E && "Didn't find reg!");
2305
2306 // Already added the first reg.
2307 --NumRegs; ++I;
2308 for (; NumRegs; --NumRegs, ++I) {
2309 assert(I != E && "Ran out of registers to allocate!");
2310 Regs.push_back(*I);
2311 }
2312 }
2313 return RegsForValue(Regs, RegVT, ValueVT);
2314 }
2315
Chris Lattner55402d42006-11-02 01:41:49 +00002316 // Otherwise, if this was a reference to an LLVM register class, create vregs
2317 // for this reference.
2318 std::vector<unsigned> RegClassRegs;
2319 if (PhysReg.second) {
2320 // If this is an early clobber or tied register, our regalloc doesn't know
2321 // how to maintain the constraint. If it isn't, go ahead and create vreg
2322 // and let the regalloc do the right thing.
2323 if (!isOutReg || !isInReg) {
2324 if (VT == MVT::Other)
2325 ValueVT = *PhysReg.second->vt_begin();
2326 RegVT = *PhysReg.second->vt_begin();
2327
2328 // Create the appropriate number of virtual registers.
2329 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2330 for (; NumRegs; --NumRegs)
2331 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2332
2333 return RegsForValue(Regs, RegVT, ValueVT);
2334 }
2335
2336 // Otherwise, we can't allocate it. Let the code below figure out how to
2337 // maintain these constraints.
2338 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2339
2340 } else {
2341 // This is a reference to a register class that doesn't directly correspond
2342 // to an LLVM register class. Allocate NumRegs consecutive, available,
2343 // registers from the class.
2344 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2345 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002346
2347 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2348 MachineFunction &MF = *CurMBB->getParent();
2349 unsigned NumAllocated = 0;
2350 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2351 unsigned Reg = RegClassRegs[i];
2352 // See if this register is available.
2353 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2354 (isInReg && InputRegs.count(Reg))) { // Already used.
2355 // Make sure we find consecutive registers.
2356 NumAllocated = 0;
2357 continue;
2358 }
2359
2360 // Check to see if this register is allocatable (i.e. don't give out the
2361 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002362 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002363 if (!RC) {
2364 // Make sure we find consecutive registers.
2365 NumAllocated = 0;
2366 continue;
2367 }
2368
2369 // Okay, this register is good, we can use it.
2370 ++NumAllocated;
2371
2372 // If we allocated enough consecutive
2373 if (NumAllocated == NumRegs) {
2374 unsigned RegStart = (i-NumAllocated)+1;
2375 unsigned RegEnd = i+1;
2376 // Mark all of the allocated registers used.
2377 for (unsigned i = RegStart; i != RegEnd; ++i) {
2378 unsigned Reg = RegClassRegs[i];
2379 Regs.push_back(Reg);
2380 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2381 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2382 }
2383
2384 return RegsForValue(Regs, *RC->vt_begin(), VT);
2385 }
2386 }
2387
2388 // Otherwise, we couldn't allocate enough registers for this.
2389 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002390}
2391
Chris Lattner6f87d182006-02-22 22:37:12 +00002392
Chris Lattner476e67b2006-01-26 22:24:51 +00002393/// visitInlineAsm - Handle a call to an InlineAsm object.
2394///
2395void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2396 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2397
2398 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2399 MVT::Other);
2400
Chris Lattner3a5ed552006-02-01 01:28:23 +00002401 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002402 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002403
2404 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2405 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2406 /// if it is a def of that register.
2407 std::vector<SDOperand> AsmNodeOperands;
2408 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2409 AsmNodeOperands.push_back(AsmStr);
2410
2411 SDOperand Chain = getRoot();
2412 SDOperand Flag;
2413
Chris Lattner1558fc62006-02-01 18:59:47 +00002414 // We fully assign registers here at isel time. This is not optimal, but
2415 // should work. For register classes that correspond to LLVM classes, we
2416 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2417 // over the constraints, collecting fixed registers that we know we can't use.
2418 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002419 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002420 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2421 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2422 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002423
Chris Lattner7ad77df2006-02-22 00:56:39 +00002424 MVT::ValueType OpVT;
2425
2426 // Compute the value type for each operand and add it to ConstraintVTs.
2427 switch (Constraints[i].Type) {
2428 case InlineAsm::isOutput:
2429 if (!Constraints[i].isIndirectOutput) {
2430 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2431 OpVT = TLI.getValueType(I.getType());
2432 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002433 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002434 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2435 OpNum++; // Consumes a call operand.
2436 }
2437 break;
2438 case InlineAsm::isInput:
2439 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2440 OpNum++; // Consumes a call operand.
2441 break;
2442 case InlineAsm::isClobber:
2443 OpVT = MVT::Other;
2444 break;
2445 }
2446
2447 ConstraintVTs.push_back(OpVT);
2448
Chris Lattner6f87d182006-02-22 22:37:12 +00002449 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2450 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002451
Chris Lattner6f87d182006-02-22 22:37:12 +00002452 // Build a list of regs that this operand uses. This always has a single
2453 // element for promoted/expanded operands.
2454 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2455 false, false,
2456 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002457
2458 switch (Constraints[i].Type) {
2459 case InlineAsm::isOutput:
2460 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002461 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002462 // If this is an early-clobber output, it cannot be assigned to the same
2463 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002464 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002465 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002466 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002467 case InlineAsm::isInput:
2468 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002469 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002470 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002471 case InlineAsm::isClobber:
2472 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002473 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2474 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002475 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002476 }
2477 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002478
Chris Lattner5c79f982006-02-21 23:12:12 +00002479 // Loop over all of the inputs, copying the operand values into the
2480 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002481 RegsForValue RetValRegs;
2482 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002483 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002484
Chris Lattner2e56e892006-01-31 02:03:41 +00002485 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002486 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2487 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002488
Chris Lattner3a5ed552006-02-01 01:28:23 +00002489 switch (Constraints[i].Type) {
2490 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002491 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2492 if (ConstraintCode.size() == 1) // not a physreg name.
2493 CTy = TLI.getConstraintType(ConstraintCode[0]);
2494
2495 if (CTy == TargetLowering::C_Memory) {
2496 // Memory output.
2497 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2498
2499 // Check that the operand (the address to store to) isn't a float.
2500 if (!MVT::isInteger(InOperandVal.getValueType()))
2501 assert(0 && "MATCH FAIL!");
2502
2503 if (!Constraints[i].isIndirectOutput)
2504 assert(0 && "MATCH FAIL!");
2505
2506 OpNum++; // Consumes a call operand.
2507
2508 // Extend/truncate to the right pointer type if needed.
2509 MVT::ValueType PtrType = TLI.getPointerTy();
2510 if (InOperandVal.getValueType() < PtrType)
2511 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2512 else if (InOperandVal.getValueType() > PtrType)
2513 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2514
2515 // Add information to the INLINEASM node to know about this output.
2516 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2517 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2518 AsmNodeOperands.push_back(InOperandVal);
2519 break;
2520 }
2521
2522 // Otherwise, this is a register output.
2523 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2524
Chris Lattner6f87d182006-02-22 22:37:12 +00002525 // If this is an early-clobber output, or if there is an input
2526 // constraint that matches this, we need to reserve the input register
2527 // so no other inputs allocate to it.
2528 bool UsesInputRegister = false;
2529 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2530 UsesInputRegister = true;
2531
2532 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002533 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002534 RegsForValue Regs =
2535 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2536 true, UsesInputRegister,
2537 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002538 if (Regs.Regs.empty()) {
2539 std::cerr << "Couldn't allocate output reg for contraint '"
2540 << ConstraintCode << "'!\n";
2541 exit(1);
2542 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002543
Chris Lattner3a5ed552006-02-01 01:28:23 +00002544 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002545 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002546 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002547 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002548 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002549 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002550 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2551 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002552 OpNum++; // Consumes a call operand.
2553 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002554
2555 // Add information to the INLINEASM node to know that this register is
2556 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002557 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002558 break;
2559 }
2560 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002561 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002562 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002563
Chris Lattner7f5880b2006-02-02 00:25:23 +00002564 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2565 // If this is required to match an output register we have already set,
2566 // just use its register.
2567 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002568
Chris Lattner571d9642006-02-23 19:21:04 +00002569 // Scan until we find the definition we already emitted of this operand.
2570 // When we find it, create a RegsForValue operand.
2571 unsigned CurOp = 2; // The first operand.
2572 for (; OperandNo; --OperandNo) {
2573 // Advance to the next operand.
2574 unsigned NumOps =
2575 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002576 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2577 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002578 "Skipped past definitions?");
2579 CurOp += (NumOps>>3)+1;
2580 }
2581
2582 unsigned NumOps =
2583 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2584 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2585 "Skipped past definitions?");
2586
2587 // Add NumOps>>3 registers to MatchedRegs.
2588 RegsForValue MatchedRegs;
2589 MatchedRegs.ValueVT = InOperandVal.getValueType();
2590 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2591 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2592 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2593 MatchedRegs.Regs.push_back(Reg);
2594 }
2595
2596 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002597 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2598 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002599 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002600 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002601 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002602
2603 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2604 if (ConstraintCode.size() == 1) // not a physreg name.
2605 CTy = TLI.getConstraintType(ConstraintCode[0]);
2606
2607 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002608 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2609 ConstraintCode[0], DAG);
2610 if (!InOperandVal.Val) {
2611 std::cerr << "Invalid operand for inline asm constraint '"
2612 << ConstraintCode << "'!\n";
2613 exit(1);
2614 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002615
2616 // Add information to the INLINEASM node to know about this input.
2617 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2618 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2619 AsmNodeOperands.push_back(InOperandVal);
2620 break;
2621 } else if (CTy == TargetLowering::C_Memory) {
2622 // Memory input.
2623
2624 // Check that the operand isn't a float.
2625 if (!MVT::isInteger(InOperandVal.getValueType()))
2626 assert(0 && "MATCH FAIL!");
2627
2628 // Extend/truncate to the right pointer type if needed.
2629 MVT::ValueType PtrType = TLI.getPointerTy();
2630 if (InOperandVal.getValueType() < PtrType)
2631 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2632 else if (InOperandVal.getValueType() > PtrType)
2633 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2634
2635 // Add information to the INLINEASM node to know about this input.
2636 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2637 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2638 AsmNodeOperands.push_back(InOperandVal);
2639 break;
2640 }
2641
2642 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2643
2644 // Copy the input into the appropriate registers.
2645 RegsForValue InRegs =
2646 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2647 false, true, OutputRegs, InputRegs);
2648 // FIXME: should be match fail.
2649 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2650
Evan Chengef9e07d2006-06-15 08:11:54 +00002651 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002652
2653 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002654 break;
2655 }
Chris Lattner571d9642006-02-23 19:21:04 +00002656 case InlineAsm::isClobber: {
2657 RegsForValue ClobberedRegs =
2658 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2659 OutputRegs, InputRegs);
2660 // Add the clobbered value to the operand list, so that the register
2661 // allocator is aware that the physreg got clobbered.
2662 if (!ClobberedRegs.Regs.empty())
2663 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002664 break;
2665 }
Chris Lattner571d9642006-02-23 19:21:04 +00002666 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002667 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002668
2669 // Finish up input operands.
2670 AsmNodeOperands[0] = Chain;
2671 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2672
Chris Lattnerbd887772006-08-14 23:53:35 +00002673 Chain = DAG.getNode(ISD::INLINEASM,
2674 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002675 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002676 Flag = Chain.getValue(1);
2677
Chris Lattner2e56e892006-01-31 02:03:41 +00002678 // If this asm returns a register value, copy the result from that register
2679 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002680 if (!RetValRegs.Regs.empty())
2681 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002682
Chris Lattner2e56e892006-01-31 02:03:41 +00002683 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2684
2685 // Process indirect outputs, first output all of the flagged copies out of
2686 // physregs.
2687 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002688 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002689 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002690 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2691 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002692 }
2693
2694 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002695 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002696 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002697 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002698 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002699 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002700 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002701 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2702 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002703 DAG.setRoot(Chain);
2704}
2705
2706
Chris Lattner7a60d912005-01-07 07:47:53 +00002707void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2708 SDOperand Src = getValue(I.getOperand(0));
2709
2710 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002711
2712 if (IntPtr < Src.getValueType())
2713 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2714 else if (IntPtr > Src.getValueType())
2715 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002716
2717 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002718 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002719 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2720 Src, getIntPtrConstant(ElementSize));
2721
2722 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002723 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002724
2725 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002726 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002727 DAG.getExternalSymbol("malloc", IntPtr),
2728 Args, DAG);
2729 setValue(&I, Result.first); // Pointers always fit in registers
2730 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002731}
2732
2733void SelectionDAGLowering::visitFree(FreeInst &I) {
2734 std::vector<std::pair<SDOperand, const Type*> > Args;
2735 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002736 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002737 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002738 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002739 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002740 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2741 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002742}
2743
Chris Lattner13d7c252005-08-26 20:54:47 +00002744// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2745// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2746// instructions are special in various ways, which require special support to
2747// insert. The specified MachineInstr is created but not inserted into any
2748// basic blocks, and the scheduler passes ownership of it to this method.
2749MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2750 MachineBasicBlock *MBB) {
2751 std::cerr << "If a target marks an instruction with "
2752 "'usesCustomDAGSchedInserter', it must implement "
2753 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2754 abort();
2755 return 0;
2756}
2757
Chris Lattner58cfd792005-01-09 00:00:49 +00002758void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002759 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2760 getValue(I.getOperand(1)),
2761 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002762}
2763
2764void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002765 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2766 getValue(I.getOperand(0)),
2767 DAG.getSrcValue(I.getOperand(0)));
2768 setValue(&I, V);
2769 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002770}
2771
2772void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002773 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2774 getValue(I.getOperand(1)),
2775 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002776}
2777
2778void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002779 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2780 getValue(I.getOperand(1)),
2781 getValue(I.getOperand(2)),
2782 DAG.getSrcValue(I.getOperand(1)),
2783 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002784}
2785
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002786/// TargetLowering::LowerArguments - This is the default LowerArguments
2787/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002788/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2789/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002790std::vector<SDOperand>
2791TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2792 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2793 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002794 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002795 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2796 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2797
2798 // Add one result value for each formal argument.
2799 std::vector<MVT::ValueType> RetVals;
2800 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2801 MVT::ValueType VT = getValueType(I->getType());
2802
2803 switch (getTypeAction(VT)) {
2804 default: assert(0 && "Unknown type action!");
2805 case Legal:
2806 RetVals.push_back(VT);
2807 break;
2808 case Promote:
2809 RetVals.push_back(getTypeToTransformTo(VT));
2810 break;
2811 case Expand:
2812 if (VT != MVT::Vector) {
2813 // If this is a large integer, it needs to be broken up into small
2814 // integers. Figure out what the destination type is and how many small
2815 // integers it turns into.
2816 MVT::ValueType NVT = getTypeToTransformTo(VT);
2817 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2818 for (unsigned i = 0; i != NumVals; ++i)
2819 RetVals.push_back(NVT);
2820 } else {
2821 // Otherwise, this is a vector type. We only support legal vectors
2822 // right now.
2823 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2824 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002825
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002826 // Figure out if there is a Packed type corresponding to this Vector
2827 // type. If so, convert to the packed type.
2828 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2829 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2830 RetVals.push_back(TVT);
2831 } else {
2832 assert(0 && "Don't support illegal by-val vector arguments yet!");
2833 }
2834 }
2835 break;
2836 }
2837 }
Evan Cheng9618df12006-04-25 23:03:35 +00002838
Chris Lattner3d826992006-05-16 06:45:34 +00002839 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002840
2841 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002842 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2843 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002844 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002845
2846 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002847
2848 // Set up the return result vector.
2849 Ops.clear();
2850 unsigned i = 0;
2851 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2852 MVT::ValueType VT = getValueType(I->getType());
2853
2854 switch (getTypeAction(VT)) {
2855 default: assert(0 && "Unknown type action!");
2856 case Legal:
2857 Ops.push_back(SDOperand(Result, i++));
2858 break;
2859 case Promote: {
2860 SDOperand Op(Result, i++);
2861 if (MVT::isInteger(VT)) {
2862 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2863 : ISD::AssertZext;
2864 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2865 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2866 } else {
2867 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2868 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2869 }
2870 Ops.push_back(Op);
2871 break;
2872 }
2873 case Expand:
2874 if (VT != MVT::Vector) {
2875 // If this is a large integer, it needs to be reassembled from small
2876 // integers. Figure out what the source elt type is and how many small
2877 // integers it is.
2878 MVT::ValueType NVT = getTypeToTransformTo(VT);
2879 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2880 if (NumVals == 2) {
2881 SDOperand Lo = SDOperand(Result, i++);
2882 SDOperand Hi = SDOperand(Result, i++);
2883
2884 if (!isLittleEndian())
2885 std::swap(Lo, Hi);
2886
2887 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2888 } else {
2889 // Value scalarized into many values. Unimp for now.
2890 assert(0 && "Cannot expand i64 -> i16 yet!");
2891 }
2892 } else {
2893 // Otherwise, this is a vector type. We only support legal vectors
2894 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002895 const PackedType *PTy = cast<PackedType>(I->getType());
2896 unsigned NumElems = PTy->getNumElements();
2897 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002898
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002899 // Figure out if there is a Packed type corresponding to this Vector
2900 // type. If so, convert to the packed type.
2901 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002902 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002903 SDOperand N = SDOperand(Result, i++);
2904 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002905 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2906 DAG.getConstant(NumElems, MVT::i32),
2907 DAG.getValueType(getValueType(EltTy)));
2908 Ops.push_back(N);
2909 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002910 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002911 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002912 }
2913 }
2914 break;
2915 }
2916 }
2917 return Ops;
2918}
2919
Chris Lattneraaa23d92006-05-16 22:53:20 +00002920
2921/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2922/// implementation, which just inserts an ISD::CALL node, which is later custom
2923/// lowered by the target to something concrete. FIXME: When all targets are
2924/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2925std::pair<SDOperand, SDOperand>
2926TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2927 unsigned CallingConv, bool isTailCall,
2928 SDOperand Callee,
2929 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002930 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002931 Ops.push_back(Chain); // Op#0 - Chain
2932 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2933 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2934 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2935 Ops.push_back(Callee);
2936
2937 // Handle all of the outgoing arguments.
2938 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2939 MVT::ValueType VT = getValueType(Args[i].second);
2940 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002941 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002942 switch (getTypeAction(VT)) {
2943 default: assert(0 && "Unknown type action!");
2944 case Legal:
2945 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002946 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002947 break;
2948 case Promote:
2949 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002950 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002951 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2952 } else {
2953 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2954 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2955 }
2956 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002957 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002958 break;
2959 case Expand:
2960 if (VT != MVT::Vector) {
2961 // If this is a large integer, it needs to be broken down into small
2962 // integers. Figure out what the source elt type is and how many small
2963 // integers it is.
2964 MVT::ValueType NVT = getTypeToTransformTo(VT);
2965 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2966 if (NumVals == 2) {
2967 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2968 DAG.getConstant(0, getPointerTy()));
2969 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2970 DAG.getConstant(1, getPointerTy()));
2971 if (!isLittleEndian())
2972 std::swap(Lo, Hi);
2973
2974 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002975 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002976 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002977 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002978 } else {
2979 // Value scalarized into many values. Unimp for now.
2980 assert(0 && "Cannot expand i64 -> i16 yet!");
2981 }
2982 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002983 // Otherwise, this is a vector type. We only support legal vectors
2984 // right now.
2985 const PackedType *PTy = cast<PackedType>(Args[i].second);
2986 unsigned NumElems = PTy->getNumElements();
2987 const Type *EltTy = PTy->getElementType();
2988
2989 // Figure out if there is a Packed type corresponding to this Vector
2990 // type. If so, convert to the packed type.
2991 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002992 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2993 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2994 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2995 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002996 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002997 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002998 assert(0 && "Don't support illegal by-val vector call args yet!");
2999 abort();
3000 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003001 }
3002 break;
3003 }
3004 }
3005
3006 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003007 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003008
3009 if (RetTy != Type::VoidTy) {
3010 MVT::ValueType VT = getValueType(RetTy);
3011 switch (getTypeAction(VT)) {
3012 default: assert(0 && "Unknown type action!");
3013 case Legal:
3014 RetTys.push_back(VT);
3015 break;
3016 case Promote:
3017 RetTys.push_back(getTypeToTransformTo(VT));
3018 break;
3019 case Expand:
3020 if (VT != MVT::Vector) {
3021 // If this is a large integer, it needs to be reassembled from small
3022 // integers. Figure out what the source elt type is and how many small
3023 // integers it is.
3024 MVT::ValueType NVT = getTypeToTransformTo(VT);
3025 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3026 for (unsigned i = 0; i != NumVals; ++i)
3027 RetTys.push_back(NVT);
3028 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003029 // Otherwise, this is a vector type. We only support legal vectors
3030 // right now.
3031 const PackedType *PTy = cast<PackedType>(RetTy);
3032 unsigned NumElems = PTy->getNumElements();
3033 const Type *EltTy = PTy->getElementType();
3034
3035 // Figure out if there is a Packed type corresponding to this Vector
3036 // type. If so, convert to the packed type.
3037 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3038 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3039 RetTys.push_back(TVT);
3040 } else {
3041 assert(0 && "Don't support illegal by-val vector call results yet!");
3042 abort();
3043 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003044 }
3045 }
3046 }
3047
3048 RetTys.push_back(MVT::Other); // Always has a chain.
3049
3050 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003051 SDOperand Res = DAG.getNode(ISD::CALL,
3052 DAG.getVTList(&RetTys[0], RetTys.size()),
3053 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003054
3055 // This returns a pair of operands. The first element is the
3056 // return value for the function (if RetTy is not VoidTy). The second
3057 // element is the outgoing token chain.
3058 SDOperand ResVal;
3059 if (RetTys.size() != 1) {
3060 MVT::ValueType VT = getValueType(RetTy);
3061 if (RetTys.size() == 2) {
3062 ResVal = Res;
3063
3064 // If this value was promoted, truncate it down.
3065 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003066 if (VT == MVT::Vector) {
3067 // Insert a VBITCONVERT to convert from the packed result type to the
3068 // MVT::Vector type.
3069 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3070 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3071
3072 // Figure out if there is a Packed type corresponding to this Vector
3073 // type. If so, convert to the packed type.
3074 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3075 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003076 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3077 // "N x PTyElementVT" MVT::Vector type.
3078 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003079 DAG.getConstant(NumElems, MVT::i32),
3080 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003081 } else {
3082 abort();
3083 }
3084 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003085 unsigned AssertOp = RetTy->isSigned() ?
3086 ISD::AssertSext : ISD::AssertZext;
3087 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3088 DAG.getValueType(VT));
3089 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3090 } else {
3091 assert(MVT::isFloatingPoint(VT));
3092 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3093 }
3094 }
3095 } else if (RetTys.size() == 3) {
3096 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3097 Res.getValue(0), Res.getValue(1));
3098
3099 } else {
3100 assert(0 && "Case not handled yet!");
3101 }
3102 }
3103
3104 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3105}
3106
3107
3108
Chris Lattner58cfd792005-01-09 00:00:49 +00003109// It is always conservatively correct for llvm.returnaddress and
3110// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00003111//
3112// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3113// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00003114std::pair<SDOperand, SDOperand>
3115TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3116 unsigned Depth, SelectionDAG &DAG) {
3117 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00003118}
3119
Chris Lattner29dcc712005-05-14 05:50:48 +00003120SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003121 assert(0 && "LowerOperation not implemented for this target!");
3122 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003123 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003124}
3125
Nate Begeman595ec732006-01-28 03:14:31 +00003126SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3127 SelectionDAG &DAG) {
3128 assert(0 && "CustomPromoteOperation not implemented for this target!");
3129 abort();
3130 return SDOperand();
3131}
3132
Chris Lattner58cfd792005-01-09 00:00:49 +00003133void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003134 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00003135 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00003136 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00003137 setValue(&I, Result.first);
3138 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003139}
3140
Evan Cheng6781b6e2006-02-15 21:59:04 +00003141/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003142/// operand.
3143static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003144 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003145 MVT::ValueType CurVT = VT;
3146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3147 uint64_t Val = C->getValue() & 255;
3148 unsigned Shift = 8;
3149 while (CurVT != MVT::i8) {
3150 Val = (Val << Shift) | Val;
3151 Shift <<= 1;
3152 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003153 }
3154 return DAG.getConstant(Val, VT);
3155 } else {
3156 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3157 unsigned Shift = 8;
3158 while (CurVT != MVT::i8) {
3159 Value =
3160 DAG.getNode(ISD::OR, VT,
3161 DAG.getNode(ISD::SHL, VT, Value,
3162 DAG.getConstant(Shift, MVT::i8)), Value);
3163 Shift <<= 1;
3164 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003165 }
3166
3167 return Value;
3168 }
3169}
3170
Evan Cheng6781b6e2006-02-15 21:59:04 +00003171/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3172/// used when a memcpy is turned into a memset when the source is a constant
3173/// string ptr.
3174static SDOperand getMemsetStringVal(MVT::ValueType VT,
3175 SelectionDAG &DAG, TargetLowering &TLI,
3176 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003177 uint64_t Val = 0;
3178 unsigned MSB = getSizeInBits(VT) / 8;
3179 if (TLI.isLittleEndian())
3180 Offset = Offset + MSB - 1;
3181 for (unsigned i = 0; i != MSB; ++i) {
3182 Val = (Val << 8) | Str[Offset];
3183 Offset += TLI.isLittleEndian() ? -1 : 1;
3184 }
3185 return DAG.getConstant(Val, VT);
3186}
3187
Evan Cheng81fcea82006-02-14 08:22:34 +00003188/// getMemBasePlusOffset - Returns base and offset node for the
3189static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3190 SelectionDAG &DAG, TargetLowering &TLI) {
3191 MVT::ValueType VT = Base.getValueType();
3192 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3193}
3194
Evan Chengdb2a7a72006-02-14 20:12:38 +00003195/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003196/// to replace the memset / memcpy is below the threshold. It also returns the
3197/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003198static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3199 unsigned Limit, uint64_t Size,
3200 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003201 MVT::ValueType VT;
3202
3203 if (TLI.allowsUnalignedMemoryAccesses()) {
3204 VT = MVT::i64;
3205 } else {
3206 switch (Align & 7) {
3207 case 0:
3208 VT = MVT::i64;
3209 break;
3210 case 4:
3211 VT = MVT::i32;
3212 break;
3213 case 2:
3214 VT = MVT::i16;
3215 break;
3216 default:
3217 VT = MVT::i8;
3218 break;
3219 }
3220 }
3221
Evan Chengd5026102006-02-14 09:11:59 +00003222 MVT::ValueType LVT = MVT::i64;
3223 while (!TLI.isTypeLegal(LVT))
3224 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3225 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003226
Evan Chengd5026102006-02-14 09:11:59 +00003227 if (VT > LVT)
3228 VT = LVT;
3229
Evan Cheng04514992006-02-14 23:05:54 +00003230 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003231 while (Size != 0) {
3232 unsigned VTSize = getSizeInBits(VT) / 8;
3233 while (VTSize > Size) {
3234 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003235 VTSize >>= 1;
3236 }
Evan Chengd5026102006-02-14 09:11:59 +00003237 assert(MVT::isInteger(VT));
3238
3239 if (++NumMemOps > Limit)
3240 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003241 MemOps.push_back(VT);
3242 Size -= VTSize;
3243 }
Evan Chengd5026102006-02-14 09:11:59 +00003244
3245 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003246}
3247
Chris Lattner875def92005-01-11 05:56:49 +00003248void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003249 SDOperand Op1 = getValue(I.getOperand(1));
3250 SDOperand Op2 = getValue(I.getOperand(2));
3251 SDOperand Op3 = getValue(I.getOperand(3));
3252 SDOperand Op4 = getValue(I.getOperand(4));
3253 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3254 if (Align == 0) Align = 1;
3255
3256 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3257 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003258
3259 // Expand memset / memcpy to a series of load / store ops
3260 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003261 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003262 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003263 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003264 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003265 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3266 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003267 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003268 unsigned Offset = 0;
3269 for (unsigned i = 0; i < NumMemOps; i++) {
3270 MVT::ValueType VT = MemOps[i];
3271 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003272 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003273 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003274 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003275 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003276 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003277 Offset += VTSize;
3278 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003279 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003280 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003281 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003282 case ISD::MEMCPY: {
3283 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3284 Size->getValue(), Align, TLI)) {
3285 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003286 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003287 GlobalAddressSDNode *G = NULL;
3288 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003289 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003290
3291 if (Op2.getOpcode() == ISD::GlobalAddress)
3292 G = cast<GlobalAddressSDNode>(Op2);
3293 else if (Op2.getOpcode() == ISD::ADD &&
3294 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3295 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3296 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003297 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003298 }
3299 if (G) {
3300 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003301 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00003302 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003303 if (!Str.empty()) {
3304 CopyFromStr = true;
3305 SrcOff += SrcDelta;
3306 }
3307 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003308 }
3309
Evan Chenge2038bd2006-02-15 01:54:51 +00003310 for (unsigned i = 0; i < NumMemOps; i++) {
3311 MVT::ValueType VT = MemOps[i];
3312 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003313 SDOperand Value, Chain, Store;
3314
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003315 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003316 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3317 Chain = getRoot();
3318 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003319 DAG.getStore(Chain, Value,
3320 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003321 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003322 } else {
3323 Value = DAG.getLoad(VT, getRoot(),
3324 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003325 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003326 Chain = Value.getValue(1);
3327 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003328 DAG.getStore(Chain, Value,
3329 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003330 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003331 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003332 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003333 SrcOff += VTSize;
3334 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003335 }
3336 }
3337 break;
3338 }
3339 }
3340
3341 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003342 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3343 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003344 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003345 }
3346 }
3347
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003348 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003349}
3350
Chris Lattner875def92005-01-11 05:56:49 +00003351//===----------------------------------------------------------------------===//
3352// SelectionDAGISel code
3353//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003354
3355unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3356 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3357}
3358
Chris Lattnerc9950c12005-08-17 06:37:43 +00003359void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003360 // FIXME: we only modify the CFG to split critical edges. This
3361 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003362 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003363}
Chris Lattner7a60d912005-01-07 07:47:53 +00003364
Chris Lattner35397782005-12-05 07:10:48 +00003365
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003366/// OptimizeNoopCopyExpression - We have determined that the specified cast
3367/// instruction is a noop copy (e.g. it's casting from one pointer type to
3368/// another, int->uint, or int->sbyte on PPC.
3369///
3370/// Return true if any changes are made.
3371static bool OptimizeNoopCopyExpression(CastInst *CI) {
3372 BasicBlock *DefBB = CI->getParent();
3373
3374 /// InsertedCasts - Only insert a cast in each block once.
3375 std::map<BasicBlock*, CastInst*> InsertedCasts;
3376
3377 bool MadeChange = false;
3378 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3379 UI != E; ) {
3380 Use &TheUse = UI.getUse();
3381 Instruction *User = cast<Instruction>(*UI);
3382
3383 // Figure out which BB this cast is used in. For PHI's this is the
3384 // appropriate predecessor block.
3385 BasicBlock *UserBB = User->getParent();
3386 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3387 unsigned OpVal = UI.getOperandNo()/2;
3388 UserBB = PN->getIncomingBlock(OpVal);
3389 }
3390
3391 // Preincrement use iterator so we don't invalidate it.
3392 ++UI;
3393
3394 // If this user is in the same block as the cast, don't change the cast.
3395 if (UserBB == DefBB) continue;
3396
3397 // If we have already inserted a cast into this block, use it.
3398 CastInst *&InsertedCast = InsertedCasts[UserBB];
3399
3400 if (!InsertedCast) {
3401 BasicBlock::iterator InsertPt = UserBB->begin();
3402 while (isa<PHINode>(InsertPt)) ++InsertPt;
3403
3404 InsertedCast =
3405 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3406 MadeChange = true;
3407 }
3408
3409 // Replace a use of the cast with a use of the new casat.
3410 TheUse = InsertedCast;
3411 }
3412
3413 // If we removed all uses, nuke the cast.
3414 if (CI->use_empty())
3415 CI->eraseFromParent();
3416
3417 return MadeChange;
3418}
3419
Chris Lattner35397782005-12-05 07:10:48 +00003420/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3421/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003422static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3423 Instruction *GEPI, Value *Ptr,
3424 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003425 if (V) return V; // Already computed.
3426
3427 BasicBlock::iterator InsertPt;
3428 if (BB == GEPI->getParent()) {
3429 // If insert into the GEP's block, insert right after the GEP.
3430 InsertPt = GEPI;
3431 ++InsertPt;
3432 } else {
3433 // Otherwise, insert at the top of BB, after any PHI nodes
3434 InsertPt = BB->begin();
3435 while (isa<PHINode>(InsertPt)) ++InsertPt;
3436 }
3437
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003438 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3439 // BB so that there is only one value live across basic blocks (the cast
3440 // operand).
3441 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3442 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3443 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3444
Chris Lattner35397782005-12-05 07:10:48 +00003445 // Add the offset, cast it to the right type.
3446 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003447 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003448}
3449
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003450/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3451/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3452/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3453/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3454/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3455/// the constant add into a load or store instruction. Additionally, if a user
3456/// is a pointer-pointer cast, we look through it to find its users.
3457static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3458 Constant *PtrOffset, BasicBlock *DefBB,
3459 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003460 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003461 while (!RepPtr->use_empty()) {
3462 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003463
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003464 // If the user is a Pointer-Pointer cast, recurse.
3465 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3466 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003467
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003468 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3469 // could invalidate an iterator.
3470 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3471 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003472 }
3473
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003474 // If this is a load of the pointer, or a store through the pointer, emit
3475 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003476 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003477 if (isa<LoadInst>(User) ||
3478 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3479 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3480 User->getParent(), GEPI,
3481 Ptr, PtrOffset);
3482 } else {
3483 // If this use is not foldable into the addressing mode, use a version
3484 // emitted in the GEP block.
3485 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3486 Ptr, PtrOffset);
3487 }
3488
Chris Lattner21cd9902006-05-06 09:10:37 +00003489 if (GEPI->getType() != RepPtr->getType()) {
3490 BasicBlock::iterator IP = NewVal;
3491 ++IP;
3492 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3493 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003494 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003495 }
3496}
Chris Lattner35397782005-12-05 07:10:48 +00003497
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003498
Chris Lattner35397782005-12-05 07:10:48 +00003499/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3500/// selection, we want to be a bit careful about some things. In particular, if
3501/// we have a GEP instruction that is used in a different block than it is
3502/// defined, the addressing expression of the GEP cannot be folded into loads or
3503/// stores that use it. In this case, decompose the GEP and move constant
3504/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003505static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003506 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003507 // If this GEP is only used inside the block it is defined in, there is no
3508 // need to rewrite it.
3509 bool isUsedOutsideDefBB = false;
3510 BasicBlock *DefBB = GEPI->getParent();
3511 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3512 UI != E; ++UI) {
3513 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3514 isUsedOutsideDefBB = true;
3515 break;
3516 }
3517 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003518 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003519
3520 // If this GEP has no non-zero constant indices, there is nothing we can do,
3521 // ignore it.
3522 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003523 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003524 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3525 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003526 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003527 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003528 hasConstantIndex = true;
3529 break;
3530 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003531 } else {
3532 hasVariableIndex = true;
3533 }
Chris Lattner35397782005-12-05 07:10:48 +00003534 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003535
3536 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3537 if (!hasConstantIndex && !hasVariableIndex) {
3538 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3539 GEPI->getName(), GEPI);
3540 GEPI->replaceAllUsesWith(NC);
3541 GEPI->eraseFromParent();
3542 return true;
3543 }
3544
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003545 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003546 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3547 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003548
3549 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3550 // constant offset (which we now know is non-zero) and deal with it later.
3551 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003552 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003553 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3554 const Type *Ty = GEPI->getOperand(0)->getType();
3555
3556 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3557 E = GEPI->op_end(); OI != E; ++OI) {
3558 Value *Idx = *OI;
3559 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003560 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003561 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003562 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003563 Ty = StTy->getElementType(Field);
3564 } else {
3565 Ty = cast<SequentialType>(Ty)->getElementType();
3566
3567 // Handle constant subscripts.
3568 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003569 if (CI->getZExtValue() == 0) continue;
3570 if (CI->getType()->isSigned())
3571 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003572 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003573 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003574 continue;
3575 }
3576
3577 // Ptr = Ptr + Idx * ElementSize;
3578
3579 // Cast Idx to UIntPtrTy if needed.
3580 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3581
Owen Anderson20a631f2006-05-03 01:29:57 +00003582 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003583 // Mask off bits that should not be set.
3584 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003585 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003586
3587 // Multiply by the element size and add to the base.
3588 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3589 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3590 }
3591 }
3592
3593 // Make sure that the offset fits in uintptr_t.
3594 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003595 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003596
3597 // Okay, we have now emitted all of the variable index parts to the BB that
3598 // the GEP is defined in. Loop over all of the using instructions, inserting
3599 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003600 // instruction to use the newly computed value, making GEPI dead. When the
3601 // user is a load or store instruction address, we emit the add into the user
3602 // block, otherwise we use a canonical version right next to the gep (these
3603 // won't be foldable as addresses, so we might as well share the computation).
3604
Chris Lattner21cd9902006-05-06 09:10:37 +00003605 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003606 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003607
3608 // Finally, the GEP is dead, remove it.
3609 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003610
3611 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003612}
3613
Chris Lattnerbba52192006-10-28 19:22:10 +00003614
3615/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3616/// successor if it will improve codegen. We only do this if the successor has
3617/// phi nodes (otherwise critical edges are ok). If there is already another
3618/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3619/// instead of introducing a new block.
3620static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3621 BasicBlock *TIBB = TI->getParent();
3622 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3623 assert(isa<PHINode>(Dest->begin()) &&
3624 "This should only be called if Dest has a PHI!");
3625
3626 /// TIPHIValues - This array is lazily computed to determine the values of
3627 /// PHIs in Dest that TI would provide.
3628 std::vector<Value*> TIPHIValues;
3629
3630 // Check to see if Dest has any blocks that can be used as a split edge for
3631 // this terminator.
3632 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3633 BasicBlock *Pred = *PI;
3634 // To be usable, the pred has to end with an uncond branch to the dest.
3635 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3636 if (!PredBr || !PredBr->isUnconditional() ||
3637 // Must be empty other than the branch.
3638 &Pred->front() != PredBr)
3639 continue;
3640
3641 // Finally, since we know that Dest has phi nodes in it, we have to make
3642 // sure that jumping to Pred will have the same affect as going to Dest in
3643 // terms of PHI values.
3644 PHINode *PN;
3645 unsigned PHINo = 0;
3646 bool FoundMatch = true;
3647 for (BasicBlock::iterator I = Dest->begin();
3648 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3649 if (PHINo == TIPHIValues.size())
3650 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3651
3652 // If the PHI entry doesn't work, we can't use this pred.
3653 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3654 FoundMatch = false;
3655 break;
3656 }
3657 }
3658
3659 // If we found a workable predecessor, change TI to branch to Succ.
3660 if (FoundMatch) {
3661 Dest->removePredecessor(TIBB);
3662 TI->setSuccessor(SuccNum, Pred);
3663 return;
3664 }
3665 }
3666
3667 SplitCriticalEdge(TI, SuccNum, P, true);
3668}
3669
3670
Chris Lattner7a60d912005-01-07 07:47:53 +00003671bool SelectionDAGISel::runOnFunction(Function &Fn) {
3672 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3673 RegMap = MF.getSSARegMap();
3674 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3675
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003676 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003677 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003678 // In this pass we also look for GEP and cast instructions that are used
3679 // across basic blocks and rewrite them to improve basic-block-at-a-time
3680 // selection.
3681 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003682 bool MadeChange = true;
3683 while (MadeChange) {
3684 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003685 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbba52192006-10-28 19:22:10 +00003686 // Split all critical edges where the dest block has a PHI.
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003687 TerminatorInst *BBTI = BB->getTerminator();
3688 if (BBTI->getNumSuccessors() > 1) {
3689 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00003690 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3691 isCriticalEdge(BBTI, i, true))
3692 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003693 }
3694
Chris Lattner35397782005-12-05 07:10:48 +00003695
Chris Lattnera9caf952006-09-28 06:17:10 +00003696 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003697 Instruction *I = BBI++;
3698 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003699 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003701 // If the source of the cast is a constant, then this should have
3702 // already been constant folded. The only reason NOT to constant fold
3703 // it is if something (e.g. LSR) was careful to place the constant
3704 // evaluation in a block other than then one that uses it (e.g. to hoist
3705 // the address of globals out of a loop). If this is the case, we don't
3706 // want to forward-subst the cast.
3707 if (isa<Constant>(CI->getOperand(0)))
3708 continue;
3709
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003710 // If this is a noop copy, sink it into user blocks to reduce the number
3711 // of virtual registers that must be created and coallesced.
3712 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3713 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3714
3715 // This is an fp<->int conversion?
3716 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3717 continue;
3718
3719 // If this is an extension, it will be a zero or sign extension, which
3720 // isn't a noop.
3721 if (SrcVT < DstVT) continue;
3722
3723 // If these values will be promoted, find out what they will be promoted
3724 // to. This helps us consider truncates on PPC as noop copies when they
3725 // are.
3726 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3727 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3728 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3729 DstVT = TLI.getTypeToTransformTo(DstVT);
3730
3731 // If, after promotion, these are the same types, this is a noop copy.
3732 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003733 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003734 }
3735 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003736 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003737 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003738
Chris Lattner7a60d912005-01-07 07:47:53 +00003739 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3740
3741 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3742 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003743
Chris Lattner7a60d912005-01-07 07:47:53 +00003744 return true;
3745}
3746
Chris Lattnered0110b2006-10-27 21:36:01 +00003747SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3748 unsigned Reg) {
3749 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003750 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003751 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003752 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003753
3754 // If this type is not legal, we must make sure to not create an invalid
3755 // register use.
3756 MVT::ValueType SrcVT = Op.getValueType();
3757 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003758 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003759 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003760 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003761 // Handle copies from generic vectors to registers.
3762 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3763 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3764 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003765
Chris Lattner5fe1f542006-03-31 02:06:56 +00003766 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3767 // MVT::Vector type.
3768 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3769 DAG.getConstant(NE, MVT::i32),
3770 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003771
Chris Lattner5fe1f542006-03-31 02:06:56 +00003772 // Loop over all of the elements of the resultant vector,
3773 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3774 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003775 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003776 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003777 for (unsigned i = 0; i != NE; ++i) {
3778 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003779 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003780 if (PTyElementVT == PTyLegalElementVT) {
3781 // Elements are legal.
3782 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3783 } else if (PTyLegalElementVT > PTyElementVT) {
3784 // Elements are promoted.
3785 if (MVT::isFloatingPoint(PTyLegalElementVT))
3786 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3787 else
3788 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3789 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3790 } else {
3791 // Elements are expanded.
3792 // The src value is expanded into multiple registers.
3793 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003794 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003795 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003796 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003797 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3798 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3799 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003800 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003801 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3802 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003803 } else if (SrcVT < DestVT) {
3804 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003805 if (MVT::isFloatingPoint(SrcVT))
3806 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3807 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003808 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003809 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003810 } else {
3811 // The src value is expanded into multiple registers.
3812 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003813 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003814 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003815 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003816 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003817 return DAG.getCopyToReg(Op, Reg+1, Hi);
3818 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003819}
3820
Chris Lattner16f64df2005-01-17 17:15:02 +00003821void SelectionDAGISel::
3822LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3823 std::vector<SDOperand> &UnorderedChains) {
3824 // If this is the entry block, emit arguments.
3825 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003826 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003827 SDOperand OldRoot = SDL.DAG.getRoot();
3828 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003829
Chris Lattner6871b232005-10-30 19:42:35 +00003830 unsigned a = 0;
3831 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3832 AI != E; ++AI, ++a)
3833 if (!AI->use_empty()) {
3834 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003835
Chris Lattner6871b232005-10-30 19:42:35 +00003836 // If this argument is live outside of the entry block, insert a copy from
3837 // whereever we got it to the vreg that other BB's will reference it as.
3838 if (FuncInfo.ValueMap.count(AI)) {
3839 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003840 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003841 UnorderedChains.push_back(Copy);
3842 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003843 }
Chris Lattner6871b232005-10-30 19:42:35 +00003844
Chris Lattner6871b232005-10-30 19:42:35 +00003845 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003846 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003847 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003848}
3849
Chris Lattner7a60d912005-01-07 07:47:53 +00003850void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3851 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003852 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003853 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003854
3855 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003856
Chris Lattner6871b232005-10-30 19:42:35 +00003857 // Lower any arguments needed in this block if this is the entry block.
3858 if (LLVMBB == &LLVMBB->getParent()->front())
3859 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003860
3861 BB = FuncInfo.MBBMap[LLVMBB];
3862 SDL.setCurrentBasicBlock(BB);
3863
3864 // Lower all of the non-terminator instructions.
3865 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3866 I != E; ++I)
3867 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003868
Chris Lattner7a60d912005-01-07 07:47:53 +00003869 // Ensure that all instructions which are used outside of their defining
3870 // blocks are available as virtual registers.
3871 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003872 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003873 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003874 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003875 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003876 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003877 }
3878
3879 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3880 // ensure constants are generated when needed. Remember the virtual registers
3881 // that need to be added to the Machine PHI nodes as input. We cannot just
3882 // directly add them, because expansion might result in multiple MBB's for one
3883 // BB. As such, the start of the BB might correspond to a different MBB than
3884 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003885 //
Chris Lattner84a03502006-10-27 23:50:33 +00003886 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00003887
3888 // Emit constants only once even if used by multiple PHI nodes.
3889 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003890
Chris Lattner84a03502006-10-27 23:50:33 +00003891 // Vector bool would be better, but vector<bool> is really slow.
3892 std::vector<unsigned char> SuccsHandled;
3893 if (TI->getNumSuccessors())
3894 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3895
Chris Lattner7a60d912005-01-07 07:47:53 +00003896 // Check successor nodes PHI nodes that expect a constant to be available from
3897 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00003898 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3899 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003900 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00003901 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00003902
Chris Lattner84a03502006-10-27 23:50:33 +00003903 // If this terminator has multiple identical successors (common for
3904 // switches), only handle each succ once.
3905 unsigned SuccMBBNo = SuccMBB->getNumber();
3906 if (SuccsHandled[SuccMBBNo]) continue;
3907 SuccsHandled[SuccMBBNo] = true;
3908
3909 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00003910 PHINode *PN;
3911
3912 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3913 // nodes and Machine PHI nodes, but the incoming operands have not been
3914 // emitted yet.
3915 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00003916 (PN = dyn_cast<PHINode>(I)); ++I) {
3917 // Ignore dead phi's.
3918 if (PN->use_empty()) continue;
3919
3920 unsigned Reg;
3921 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3922 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3923 unsigned &RegOut = ConstantsOut[C];
3924 if (RegOut == 0) {
3925 RegOut = FuncInfo.CreateRegForValue(C);
3926 UnorderedChains.push_back(
3927 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00003928 }
Chris Lattner84a03502006-10-27 23:50:33 +00003929 Reg = RegOut;
3930 } else {
3931 Reg = FuncInfo.ValueMap[PHIOp];
3932 if (Reg == 0) {
3933 assert(isa<AllocaInst>(PHIOp) &&
3934 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3935 "Didn't codegen value into a register!??");
3936 Reg = FuncInfo.CreateRegForValue(PHIOp);
3937 UnorderedChains.push_back(
3938 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00003939 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003940 }
Chris Lattner84a03502006-10-27 23:50:33 +00003941
3942 // Remember that this register needs to added to the machine PHI node as
3943 // the input for this MBB.
3944 MVT::ValueType VT = TLI.getValueType(PN->getType());
3945 unsigned NumElements;
3946 if (VT != MVT::Vector)
3947 NumElements = TLI.getNumElements(VT);
3948 else {
3949 MVT::ValueType VT1,VT2;
3950 NumElements =
3951 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3952 VT1, VT2);
3953 }
3954 for (unsigned i = 0, e = NumElements; i != e; ++i)
3955 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3956 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003957 }
3958 ConstantsOut.clear();
3959
Chris Lattner718b5c22005-01-13 17:59:43 +00003960 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003961 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003962 SDOperand Root = SDL.getRoot();
3963 if (Root.getOpcode() != ISD::EntryToken) {
3964 unsigned i = 0, e = UnorderedChains.size();
3965 for (; i != e; ++i) {
3966 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3967 if (UnorderedChains[i].Val->getOperand(0) == Root)
3968 break; // Don't add the root if we already indirectly depend on it.
3969 }
3970
3971 if (i == e)
3972 UnorderedChains.push_back(Root);
3973 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003974 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3975 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003976 }
3977
Chris Lattner7a60d912005-01-07 07:47:53 +00003978 // Lower the terminator after the copies are emitted.
3979 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003980
Nate Begemaned728c12006-03-27 01:32:24 +00003981 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003982 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003983 SwitchCases.clear();
3984 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003985 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003986
Chris Lattner4108bb02005-01-17 19:43:36 +00003987 // Make sure the root of the DAG is up-to-date.
3988 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003989}
3990
Nate Begemaned728c12006-03-27 01:32:24 +00003991void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003992 // Get alias analysis for load/store combining.
3993 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3994
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003995 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003996 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003997
Chris Lattner7a60d912005-01-07 07:47:53 +00003998 DEBUG(std::cerr << "Lowered selection DAG:\n");
3999 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004000
Chris Lattner7a60d912005-01-07 07:47:53 +00004001 // Second step, hack on the DAG until it only uses operations and types that
4002 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004003 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004004
Chris Lattner7a60d912005-01-07 07:47:53 +00004005 DEBUG(std::cerr << "Legalized selection DAG:\n");
4006 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004007
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004008 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004009 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004010
Evan Cheng739a6a42006-01-21 02:32:06 +00004011 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004012
Chris Lattner5ca31d92005-03-30 01:10:47 +00004013 // Third, instruction select all of the operations to machine code, adding the
4014 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004015 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004016
Chris Lattner7a60d912005-01-07 07:47:53 +00004017 DEBUG(std::cerr << "Selected machine code:\n");
4018 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004019}
Chris Lattner7a60d912005-01-07 07:47:53 +00004020
Nate Begemaned728c12006-03-27 01:32:24 +00004021void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4022 FunctionLoweringInfo &FuncInfo) {
4023 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4024 {
4025 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4026 CurDAG = &DAG;
4027
4028 // First step, lower LLVM code to some DAG. This DAG may use operations and
4029 // types that are not supported by the target.
4030 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4031
4032 // Second step, emit the lowered DAG as machine code.
4033 CodeGenAndEmitDAG(DAG);
4034 }
4035
Chris Lattner5ca31d92005-03-30 01:10:47 +00004036 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004037 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004038 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00004039 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4040 MachineInstr *PHI = PHINodesToUpdate[i].first;
4041 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4042 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004043 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004044 PHI->addMachineBasicBlockOperand(BB);
4045 }
4046 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004047 }
Nate Begemaned728c12006-03-27 01:32:24 +00004048
Nate Begeman866b4b42006-04-23 06:26:20 +00004049 // If the JumpTable record is filled in, then we need to emit a jump table.
4050 // Updating the PHI nodes is tricky in this case, since we need to determine
4051 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004052 if (JT.Reg) {
4053 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4054 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4055 CurDAG = &SDAG;
4056 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00004057 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004058 // Set the current basic block to the mbb we wish to insert the code into
4059 BB = JT.MBB;
4060 SDL.setCurrentBasicBlock(BB);
4061 // Emit the code
4062 SDL.visitJumpTable(JT);
4063 SDAG.setRoot(SDL.getRoot());
4064 CodeGenAndEmitDAG(SDAG);
4065 // Update PHI Nodes
4066 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4067 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4068 MachineBasicBlock *PHIBB = PHI->getParent();
4069 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4070 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00004071 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004072 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004073 PHI->addMachineBasicBlockOperand(RangeBB);
4074 }
4075 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004076 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004077 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004078 }
4079 }
4080 return;
4081 }
4082
Chris Lattner76a7bc82006-10-22 23:00:53 +00004083 // If the switch block involved a branch to one of the actual successors, we
4084 // need to update PHI nodes in that block.
4085 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4086 MachineInstr *PHI = PHINodesToUpdate[i].first;
4087 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4088 "This is not a machine PHI node that we are updating!");
4089 if (BB->isSuccessor(PHI->getParent())) {
4090 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4091 PHI->addMachineBasicBlockOperand(BB);
4092 }
4093 }
4094
Nate Begemaned728c12006-03-27 01:32:24 +00004095 // If we generated any switch lowering information, build and codegen any
4096 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004097 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00004098 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4099 CurDAG = &SDAG;
4100 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004101
Nate Begemaned728c12006-03-27 01:32:24 +00004102 // Set the current basic block to the mbb we wish to insert the code into
4103 BB = SwitchCases[i].ThisBB;
4104 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004105
Nate Begemaned728c12006-03-27 01:32:24 +00004106 // Emit the code
4107 SDL.visitSwitchCase(SwitchCases[i]);
4108 SDAG.setRoot(SDL.getRoot());
4109 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004110
4111 // Handle any PHI nodes in successors of this chunk, as if we were coming
4112 // from the original BB before switch expansion. Note that PHI nodes can
4113 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4114 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004115 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004116 for (MachineBasicBlock::iterator Phi = BB->begin();
4117 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4118 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4119 for (unsigned pn = 0; ; ++pn) {
4120 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4121 if (PHINodesToUpdate[pn].first == Phi) {
4122 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4123 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4124 break;
4125 }
4126 }
Nate Begemaned728c12006-03-27 01:32:24 +00004127 }
Chris Lattner707339a52006-09-07 01:59:34 +00004128
4129 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004130 if (BB == SwitchCases[i].FalseBB)
4131 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004132
4133 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004134 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004135 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004136 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004137 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004138 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004139}
Evan Cheng739a6a42006-01-21 02:32:06 +00004140
Jim Laskey95eda5b2006-08-01 14:21:23 +00004141
Evan Cheng739a6a42006-01-21 02:32:06 +00004142//===----------------------------------------------------------------------===//
4143/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4144/// target node in the graph.
4145void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4146 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004147
Jim Laskey29e635d2006-08-02 12:30:23 +00004148 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004149
4150 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004151 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004152 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004153 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004154
Jim Laskey03593f72006-08-01 18:29:48 +00004155 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004156 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004157 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004158}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004159
Chris Lattner47639db2006-03-06 00:22:00 +00004160
Jim Laskey03593f72006-08-01 18:29:48 +00004161HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4162 return new HazardRecognizer();
4163}
4164
Chris Lattner6df34962006-10-11 03:58:02 +00004165//===----------------------------------------------------------------------===//
4166// Helper functions used by the generated instruction selector.
4167//===----------------------------------------------------------------------===//
4168// Calls to these methods are generated by tblgen.
4169
4170/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4171/// the dag combiner simplified the 255, we still want to match. RHS is the
4172/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4173/// specified in the .td file (e.g. 255).
4174bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4175 int64_t DesiredMaskS) {
4176 uint64_t ActualMask = RHS->getValue();
4177 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4178
4179 // If the actual mask exactly matches, success!
4180 if (ActualMask == DesiredMask)
4181 return true;
4182
4183 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4184 if (ActualMask & ~DesiredMask)
4185 return false;
4186
4187 // Otherwise, the DAG Combiner may have proven that the value coming in is
4188 // either already zero or is not demanded. Check for known zero input bits.
4189 uint64_t NeededMask = DesiredMask & ~ActualMask;
4190 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4191 return true;
4192
4193 // TODO: check to see if missing bits are just not demanded.
4194
4195 // Otherwise, this pattern doesn't match.
4196 return false;
4197}
4198
4199/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4200/// the dag combiner simplified the 255, we still want to match. RHS is the
4201/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4202/// specified in the .td file (e.g. 255).
4203bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4204 int64_t DesiredMaskS) {
4205 uint64_t ActualMask = RHS->getValue();
4206 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4207
4208 // If the actual mask exactly matches, success!
4209 if (ActualMask == DesiredMask)
4210 return true;
4211
4212 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4213 if (ActualMask & ~DesiredMask)
4214 return false;
4215
4216 // Otherwise, the DAG Combiner may have proven that the value coming in is
4217 // either already zero or is not demanded. Check for known zero input bits.
4218 uint64_t NeededMask = DesiredMask & ~ActualMask;
4219
4220 uint64_t KnownZero, KnownOne;
4221 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4222
4223 // If all the missing bits in the or are already known to be set, match!
4224 if ((NeededMask & KnownOne) == NeededMask)
4225 return true;
4226
4227 // TODO: check to see if missing bits are just not demanded.
4228
4229 // Otherwise, this pattern doesn't match.
4230 return false;
4231}
4232
Jim Laskey03593f72006-08-01 18:29:48 +00004233
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004234/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4235/// by tblgen. Others should not call it.
4236void SelectionDAGISel::
4237SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4238 std::vector<SDOperand> InOps;
4239 std::swap(InOps, Ops);
4240
4241 Ops.push_back(InOps[0]); // input chain.
4242 Ops.push_back(InOps[1]); // input asm string.
4243
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004244 unsigned i = 2, e = InOps.size();
4245 if (InOps[e-1].getValueType() == MVT::Flag)
4246 --e; // Don't process a flag operand if it is here.
4247
4248 while (i != e) {
4249 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4250 if ((Flags & 7) != 4 /*MEM*/) {
4251 // Just skip over this operand, copying the operands verbatim.
4252 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4253 i += (Flags >> 3) + 1;
4254 } else {
4255 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4256 // Otherwise, this is a memory operand. Ask the target to select it.
4257 std::vector<SDOperand> SelOps;
4258 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4259 std::cerr << "Could not match memory address. Inline asm failure!\n";
4260 exit(1);
4261 }
4262
4263 // Add this to the output node.
4264 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4265 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4266 i += 2;
4267 }
4268 }
4269
4270 // Add the flag input back if present.
4271 if (e != InOps.size())
4272 Ops.push_back(InOps.back());
4273}