1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuilder.h"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Module.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/GCStrategy.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetFrameInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetIntrinsicInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
72 /// RegsForValue - This struct represents the registers (physical or virtual)
73 /// that a particular set of values is assigned, and the type information about
74 /// the value. The most common situation is to represent one value at a time,
75 /// but struct or array values are handled element-wise as multiple values.
76 /// The splitting of aggregates is performed recursively, so that we never
77 /// have aggregate-typed registers. The values at this point do not necessarily
78 /// have legal types, so each value may require one or more registers of some
82 /// TLI - The TargetLowering object.
84 const TargetLowering *TLI;
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
89 SmallVector<EVT, 4> ValueVTs;
91 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
100 SmallVector<EVT, 4> RegVTs;
102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
106 SmallVector<unsigned, 4> Regs;
108 RegsForValue() : TLI(0) {}
110 RegsForValue(const TargetLowering &tli,
111 const SmallVector<unsigned, 4> ®s,
112 EVT regvt, EVT valuevt)
113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
115 const SmallVector<unsigned, 4> ®s,
116 const SmallVector<EVT, 4> ®vts,
117 const SmallVector<EVT, 4> &valuevts)
118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
124 EVT ValueVT = ValueVTs[Value];
125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
134 /// append - Add the specified values to this one.
135 void append(const RegsForValue &RHS) {
137 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
138 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
139 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
143 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
144 /// this value and returns the result as a ValueVTs value. This uses
145 /// Chain/Flag as the input and updates them for the output Chain/Flag.
146 /// If the Flag pointer is NULL, no flag is used.
147 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
148 SDValue &Chain, SDValue *Flag) const;
150 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
151 /// specified value into the registers specified by this object. This uses
152 /// Chain/Flag as the input and updates them for the output Chain/Flag.
153 /// If the Flag pointer is NULL, no flag is used.
154 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
155 unsigned Order, SDValue &Chain, SDValue *Flag) const;
157 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
158 /// operand list. This adds the code marker, matching input operand index
159 /// (if applicable), and includes the number of values added into it.
160 void AddInlineAsmOperands(unsigned Code,
161 bool HasMatching, unsigned MatchingIdx,
162 SelectionDAG &DAG, unsigned Order,
163 std::vector<SDValue> &Ops) const;
167 /// getCopyFromParts - Create a value that contains the specified legal parts
168 /// combined into the value they represent. If the parts combine to a type
169 /// larger then ValueVT then AssertOp can be used to specify whether the extra
170 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
171 /// (ISD::AssertSext).
172 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
173 const SDValue *Parts,
174 unsigned NumParts, EVT PartVT, EVT ValueVT,
175 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
176 assert(NumParts > 0 && "No parts to assemble!");
177 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
178 SDValue Val = Parts[0];
181 // Assemble the value from multiple parts.
182 if (!ValueVT.isVector() && ValueVT.isInteger()) {
183 unsigned PartBits = PartVT.getSizeInBits();
184 unsigned ValueBits = ValueVT.getSizeInBits();
186 // Assemble the power of 2 part.
187 unsigned RoundParts = NumParts & (NumParts - 1) ?
188 1 << Log2_32(NumParts) : NumParts;
189 unsigned RoundBits = PartBits * RoundParts;
190 EVT RoundVT = RoundBits == ValueBits ?
191 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
196 if (RoundParts > 2) {
197 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
198 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
201 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
202 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
204 if (TLI.isBigEndian())
206 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
208 if (RoundParts < NumParts) {
209 // Assemble the trailing non-power-of-2 part.
210 unsigned OddParts = NumParts - RoundParts;
211 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
212 Hi = getCopyFromParts(DAG, dl,
213 Parts+RoundParts, OddParts, PartVT, OddVT);
215 // Combine the round and odd parts.
217 if (TLI.isBigEndian())
219 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
220 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
221 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
222 DAG.getConstant(Lo.getValueType().getSizeInBits(),
223 TLI.getPointerTy()));
224 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
225 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
227 } else if (ValueVT.isVector()) {
228 // Handle a multi-element vector.
229 EVT IntermediateVT, RegisterVT;
230 unsigned NumIntermediates;
232 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
233 NumIntermediates, RegisterVT);
234 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
235 NumParts = NumRegs; // Silence a compiler warning.
236 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
237 assert(RegisterVT == Parts[0].getValueType() &&
238 "Part type doesn't match part!");
240 // Assemble the parts into intermediate operands.
241 SmallVector<SDValue, 8> Ops(NumIntermediates);
242 if (NumIntermediates == NumParts) {
243 // If the register was not expanded, truncate or copy the value,
245 for (unsigned i = 0; i != NumParts; ++i)
246 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
247 PartVT, IntermediateVT);
248 } else if (NumParts > 0) {
249 // If the intermediate type was expanded, build the intermediate operands
251 assert(NumParts % NumIntermediates == 0 &&
252 "Must expand into a divisible number of parts!");
253 unsigned Factor = NumParts / NumIntermediates;
254 for (unsigned i = 0; i != NumIntermediates; ++i)
255 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
256 PartVT, IntermediateVT);
259 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
261 Val = DAG.getNode(IntermediateVT.isVector() ?
262 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
263 ValueVT, &Ops[0], NumIntermediates);
264 } else if (PartVT.isFloatingPoint()) {
265 // FP split into multiple FP parts (for ppcf128)
266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
269 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
270 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
271 if (TLI.isBigEndian())
273 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
275 // FP split into integer parts (soft fp)
276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
277 !PartVT.isVector() && "Unexpected split");
278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
279 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
283 // There is now one part, held in Val. Correct it to match ValueVT.
284 PartVT = Val.getValueType();
286 if (PartVT == ValueVT)
289 if (PartVT.isVector()) {
290 assert(ValueVT.isVector() && "Unknown vector conversion!");
291 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
294 if (ValueVT.isVector()) {
295 assert(ValueVT.getVectorElementType() == PartVT &&
296 ValueVT.getVectorNumElements() == 1 &&
297 "Only trivial scalar-to-vector conversions should get here!");
298 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
301 if (PartVT.isInteger() &&
302 ValueVT.isInteger()) {
303 if (ValueVT.bitsLT(PartVT)) {
304 // For a truncate, see if we have any information to
305 // indicate whether the truncated bits will always be
306 // zero or sign-extension.
307 if (AssertOp != ISD::DELETED_NODE)
308 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
309 DAG.getValueType(ValueVT));
310 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
312 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
316 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
317 if (ValueVT.bitsLT(Val.getValueType()))
318 // FP_ROUND's are always exact here.
319 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
320 DAG.getIntPtrConstant(1));
321 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
324 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
325 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
327 llvm_unreachable("Unknown mismatch!");
331 /// getCopyToParts - Create a series of nodes that contain the specified value
332 /// split into legal parts. If the parts contain more bits than Val, then, for
333 /// integers, ExtendKind can be used to specify how to generate the extra bits.
334 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
335 SDValue *Parts, unsigned NumParts, EVT PartVT,
336 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
338 EVT PtrVT = TLI.getPointerTy();
339 EVT ValueVT = Val.getValueType();
340 unsigned PartBits = PartVT.getSizeInBits();
341 unsigned OrigNumParts = NumParts;
342 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
347 if (!ValueVT.isVector()) {
348 if (PartVT == ValueVT) {
349 assert(NumParts == 1 && "No-op copy with multiple parts!");
354 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
355 // If the parts cover more bits than the value has, promote the value.
356 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
357 assert(NumParts == 1 && "Do not know what to promote to!");
358 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
359 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
360 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
361 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
363 llvm_unreachable("Unknown mismatch!");
365 } else if (PartBits == ValueVT.getSizeInBits()) {
366 // Different types of the same size.
367 assert(NumParts == 1 && PartVT != ValueVT);
368 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
369 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
370 // If the parts cover less bits than value has, truncate the value.
371 if (PartVT.isInteger() && ValueVT.isInteger()) {
372 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
373 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
375 llvm_unreachable("Unknown mismatch!");
379 // The value may have changed - recompute ValueVT.
380 ValueVT = Val.getValueType();
381 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
382 "Failed to tile the value with PartVT!");
385 assert(PartVT == ValueVT && "Type conversion failed!");
390 // Expand the value into multiple parts.
391 if (NumParts & (NumParts - 1)) {
392 // The number of parts is not a power of 2. Split off and copy the tail.
393 assert(PartVT.isInteger() && ValueVT.isInteger() &&
394 "Do not know what to expand to!");
395 unsigned RoundParts = 1 << Log2_32(NumParts);
396 unsigned RoundBits = RoundParts * PartBits;
397 unsigned OddParts = NumParts - RoundParts;
398 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
399 DAG.getConstant(RoundBits,
400 TLI.getPointerTy()));
401 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
402 if (TLI.isBigEndian())
403 // The odd parts were reversed by getCopyToParts - unreverse them.
404 std::reverse(Parts + RoundParts, Parts + NumParts);
405 NumParts = RoundParts;
406 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
407 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
410 // The number of parts is a power of 2. Repeatedly bisect the value using
412 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
413 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
415 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
416 for (unsigned i = 0; i < NumParts; i += StepSize) {
417 unsigned ThisBits = StepSize * PartBits / 2;
418 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
419 SDValue &Part0 = Parts[i];
420 SDValue &Part1 = Parts[i+StepSize/2];
422 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
424 DAG.getConstant(1, PtrVT));
425 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
427 DAG.getConstant(0, PtrVT));
429 if (ThisBits == PartBits && ThisVT != PartVT) {
430 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
432 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
438 if (TLI.isBigEndian())
439 std::reverse(Parts, Parts + OrigNumParts);
446 if (PartVT != ValueVT) {
447 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
448 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
450 assert(ValueVT.getVectorElementType() == PartVT &&
451 ValueVT.getVectorNumElements() == 1 &&
452 "Only trivial vector-to-scalar conversions should get here!");
453 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
455 DAG.getConstant(0, PtrVT));
463 // Handle a multi-element vector.
464 EVT IntermediateVT, RegisterVT;
465 unsigned NumIntermediates;
466 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
467 IntermediateVT, NumIntermediates, RegisterVT);
468 unsigned NumElements = ValueVT.getVectorNumElements();
470 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
471 NumParts = NumRegs; // Silence a compiler warning.
472 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
474 // Split the vector into intermediate operands.
475 SmallVector<SDValue, 8> Ops(NumIntermediates);
476 for (unsigned i = 0; i != NumIntermediates; ++i)
477 if (IntermediateVT.isVector())
478 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
480 DAG.getConstant(i * (NumElements / NumIntermediates),
483 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
485 DAG.getConstant(i, PtrVT));
487 // Split the intermediate operands into legal parts.
488 if (NumParts == NumIntermediates) {
489 // If the register was not expanded, promote or copy the value,
491 for (unsigned i = 0; i != NumParts; ++i)
492 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
493 } else if (NumParts > 0) {
494 // If the intermediate type was expanded, split each the value into
496 assert(NumParts % NumIntermediates == 0 &&
497 "Must expand into a divisible number of parts!");
498 unsigned Factor = NumParts / NumIntermediates;
499 for (unsigned i = 0; i != NumIntermediates; ++i)
500 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
505 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
508 TD = DAG.getTarget().getTargetData();
511 /// clear - Clear out the curret SelectionDAG and the associated
512 /// state and prepare this SelectionDAGBuilder object to be used
513 /// for a new block. This doesn't clear out information about
514 /// additional blocks that are needed to complete switch lowering
515 /// or PHI node updating; that information is cleared out as it is
517 void SelectionDAGBuilder::clear() {
519 PendingLoads.clear();
520 PendingExports.clear();
523 CurDebugLoc = DebugLoc::getUnknownLoc();
527 /// getRoot - Return the current virtual root of the Selection DAG,
528 /// flushing any PendingLoad items. This must be done before emitting
529 /// a store or any other node that may need to be ordered after any
530 /// prior load instructions.
532 SDValue SelectionDAGBuilder::getRoot() {
533 if (PendingLoads.empty())
534 return DAG.getRoot();
536 if (PendingLoads.size() == 1) {
537 SDValue Root = PendingLoads[0];
539 PendingLoads.clear();
543 // Otherwise, we have to make a token factor node.
544 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
545 &PendingLoads[0], PendingLoads.size());
546 PendingLoads.clear();
551 /// getControlRoot - Similar to getRoot, but instead of flushing all the
552 /// PendingLoad items, flush all the PendingExports items. It is necessary
553 /// to do this before emitting a terminator instruction.
555 SDValue SelectionDAGBuilder::getControlRoot() {
556 SDValue Root = DAG.getRoot();
558 if (PendingExports.empty())
561 // Turn all of the CopyToReg chains into one factored node.
562 if (Root.getOpcode() != ISD::EntryToken) {
563 unsigned i = 0, e = PendingExports.size();
564 for (; i != e; ++i) {
565 assert(PendingExports[i].getNode()->getNumOperands() > 1);
566 if (PendingExports[i].getNode()->getOperand(0) == Root)
567 break; // Don't add the root if we already indirectly depend on it.
571 PendingExports.push_back(Root);
574 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
576 PendingExports.size());
577 PendingExports.clear();
582 void SelectionDAGBuilder::visit(Instruction &I) {
583 visit(I.getOpcode(), I);
586 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
587 // We're processing a new instruction.
590 // Note: this doesn't use InstVisitor, because it has to work with
591 // ConstantExpr's in addition to instructions.
593 default: llvm_unreachable("Unknown instruction type encountered!");
594 // Build the switch statement using the Instruction.def file.
595 #define HANDLE_INST(NUM, OPCODE, CLASS) \
596 case Instruction::OPCODE: return visit##OPCODE((CLASS&)I);
597 #include "llvm/Instruction.def"
601 SDValue SelectionDAGBuilder::getValue(const Value *V) {
602 SDValue &N = NodeMap[V];
603 if (N.getNode()) return N;
605 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
606 EVT VT = TLI.getValueType(V->getType(), true);
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
609 return N = DAG.getConstant(*CI, VT);
611 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
612 return N = DAG.getGlobalAddress(GV, VT);
614 if (isa<ConstantPointerNull>(C))
615 return N = DAG.getConstant(0, TLI.getPointerTy());
617 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
618 return N = DAG.getConstantFP(*CFP, VT);
620 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
621 return N = DAG.getUNDEF(VT);
623 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
624 visit(CE->getOpcode(), *CE);
625 SDValue N1 = NodeMap[V];
626 assert(N1.getNode() && "visit didn't populate the ValueMap!");
630 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
631 SmallVector<SDValue, 4> Constants;
632 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
634 SDNode *Val = getValue(*OI).getNode();
635 // If the operand is an empty aggregate, there are no values.
637 // Add each leaf value from the operand to the Constants list
638 // to form a flattened list of all the values.
639 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
640 Constants.push_back(SDValue(Val, i));
643 SDValue Res = DAG.getMergeValues(&Constants[0], Constants.size(),
645 if (DisableScheduling)
646 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
650 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
651 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
652 "Unknown struct or array constant!");
654 SmallVector<EVT, 4> ValueVTs;
655 ComputeValueVTs(TLI, C->getType(), ValueVTs);
656 unsigned NumElts = ValueVTs.size();
658 return SDValue(); // empty struct
659 SmallVector<SDValue, 4> Constants(NumElts);
660 for (unsigned i = 0; i != NumElts; ++i) {
661 EVT EltVT = ValueVTs[i];
662 if (isa<UndefValue>(C))
663 Constants[i] = DAG.getUNDEF(EltVT);
664 else if (EltVT.isFloatingPoint())
665 Constants[i] = DAG.getConstantFP(0, EltVT);
667 Constants[i] = DAG.getConstant(0, EltVT);
670 SDValue Res = DAG.getMergeValues(&Constants[0], NumElts,
672 if (DisableScheduling)
673 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
677 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
678 return DAG.getBlockAddress(BA, VT);
680 const VectorType *VecTy = cast<VectorType>(V->getType());
681 unsigned NumElements = VecTy->getNumElements();
683 // Now that we know the number and type of the elements, get that number of
684 // elements into the Ops array based on what kind of constant it is.
685 SmallVector<SDValue, 16> Ops;
686 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
687 for (unsigned i = 0; i != NumElements; ++i)
688 Ops.push_back(getValue(CP->getOperand(i)));
690 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
691 EVT EltVT = TLI.getValueType(VecTy->getElementType());
694 if (EltVT.isFloatingPoint())
695 Op = DAG.getConstantFP(0, EltVT);
697 Op = DAG.getConstant(0, EltVT);
698 Ops.assign(NumElements, Op);
701 // Create a BUILD_VECTOR node.
702 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
703 VT, &Ops[0], Ops.size());
704 if (DisableScheduling)
705 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
707 return NodeMap[V] = Res;
710 // If this is a static alloca, generate it as the frameindex instead of
712 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
713 DenseMap<const AllocaInst*, int>::iterator SI =
714 FuncInfo.StaticAllocaMap.find(AI);
715 if (SI != FuncInfo.StaticAllocaMap.end())
716 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
719 unsigned InReg = FuncInfo.ValueMap[V];
720 assert(InReg && "Value not in map!");
722 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
723 SDValue Chain = DAG.getEntryNode();
724 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
725 SDNodeOrder, Chain, NULL);
728 /// Get the EVTs and ArgFlags collections that represent the return type
729 /// of the given function. This does not require a DAG or a return value, and
730 /// is suitable for use before any DAGs for the function are constructed.
731 static void getReturnInfo(const Type* ReturnType,
732 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
733 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
735 SmallVectorImpl<uint64_t> *Offsets = 0) {
736 SmallVector<EVT, 4> ValueVTs;
737 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
738 unsigned NumValues = ValueVTs.size();
739 if ( NumValues == 0 ) return;
741 for (unsigned j = 0, f = NumValues; j != f; ++j) {
742 EVT VT = ValueVTs[j];
743 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
745 if (attr & Attribute::SExt)
746 ExtendKind = ISD::SIGN_EXTEND;
747 else if (attr & Attribute::ZExt)
748 ExtendKind = ISD::ZERO_EXTEND;
750 // FIXME: C calling convention requires the return type to be promoted to
751 // at least 32-bit. But this is not necessary for non-C calling
752 // conventions. The frontend should mark functions whose return values
753 // require promoting with signext or zeroext attributes.
754 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
755 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
756 if (VT.bitsLT(MinVT))
760 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
761 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
762 // 'inreg' on function refers to return value
763 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
764 if (attr & Attribute::InReg)
767 // Propagate extension type if any
768 if (attr & Attribute::SExt)
770 else if (attr & Attribute::ZExt)
773 for (unsigned i = 0; i < NumParts; ++i) {
774 OutVTs.push_back(PartVT);
775 OutFlags.push_back(Flags);
780 void SelectionDAGBuilder::visitRet(ReturnInst &I) {
781 SDValue Chain = getControlRoot();
782 SmallVector<ISD::OutputArg, 8> Outs;
783 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
785 if (!FLI.CanLowerReturn) {
786 unsigned DemoteReg = FLI.DemoteRegister;
787 const Function *F = I.getParent()->getParent();
789 // Emit a store of the return value through the virtual register.
790 // Leave Outs empty so that LowerReturn won't try to load return
791 // registers the usual way.
792 SmallVector<EVT, 1> PtrValueVTs;
793 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
796 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
797 SDValue RetOp = getValue(I.getOperand(0));
799 SmallVector<EVT, 4> ValueVTs;
800 SmallVector<uint64_t, 4> Offsets;
801 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
802 unsigned NumValues = ValueVTs.size();
804 SmallVector<SDValue, 4> Chains(NumValues);
805 EVT PtrVT = PtrValueVTs[0];
806 for (unsigned i = 0; i != NumValues; ++i) {
807 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
808 DAG.getConstant(Offsets[i], PtrVT));
810 DAG.getStore(Chain, getCurDebugLoc(),
811 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
812 Add, NULL, Offsets[i], false, 0);
814 if (DisableScheduling) {
815 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
816 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
820 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
821 MVT::Other, &Chains[0], NumValues);
823 if (DisableScheduling)
824 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
826 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
827 SmallVector<EVT, 4> ValueVTs;
828 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
829 unsigned NumValues = ValueVTs.size();
830 if (NumValues == 0) continue;
832 SDValue RetOp = getValue(I.getOperand(i));
833 for (unsigned j = 0, f = NumValues; j != f; ++j) {
834 EVT VT = ValueVTs[j];
836 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
838 const Function *F = I.getParent()->getParent();
839 if (F->paramHasAttr(0, Attribute::SExt))
840 ExtendKind = ISD::SIGN_EXTEND;
841 else if (F->paramHasAttr(0, Attribute::ZExt))
842 ExtendKind = ISD::ZERO_EXTEND;
844 // FIXME: C calling convention requires the return type to be promoted to
845 // at least 32-bit. But this is not necessary for non-C calling
846 // conventions. The frontend should mark functions whose return values
847 // require promoting with signext or zeroext attributes.
848 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
849 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
850 if (VT.bitsLT(MinVT))
854 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
855 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
856 SmallVector<SDValue, 4> Parts(NumParts);
857 getCopyToParts(DAG, getCurDebugLoc(),
858 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
859 &Parts[0], NumParts, PartVT, ExtendKind);
861 // 'inreg' on function refers to return value
862 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
863 if (F->paramHasAttr(0, Attribute::InReg))
866 // Propagate extension type if any
867 if (F->paramHasAttr(0, Attribute::SExt))
869 else if (F->paramHasAttr(0, Attribute::ZExt))
872 for (unsigned i = 0; i < NumParts; ++i)
873 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
878 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
879 CallingConv::ID CallConv =
880 DAG.getMachineFunction().getFunction()->getCallingConv();
881 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
882 Outs, getCurDebugLoc(), DAG);
884 // Verify that the target's LowerReturn behaved as expected.
885 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
886 "LowerReturn didn't return a valid chain!");
888 // Update the DAG with the new chain value resulting from return lowering.
891 if (DisableScheduling)
892 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
895 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
896 /// created for it, emit nodes to copy the value into the virtual
898 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
899 if (!V->use_empty()) {
900 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
901 if (VMI != FuncInfo.ValueMap.end())
902 CopyValueToVirtualRegister(V, VMI->second);
906 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
907 /// the current basic block, add it to ValueMap now so that we'll get a
909 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
910 // No need to export constants.
911 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
914 if (FuncInfo.isExportedInst(V)) return;
916 unsigned Reg = FuncInfo.InitializeRegForValue(V);
917 CopyValueToVirtualRegister(V, Reg);
920 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
921 const BasicBlock *FromBB) {
922 // The operands of the setcc have to be in this block. We don't know
923 // how to export them from some other block.
924 if (Instruction *VI = dyn_cast<Instruction>(V)) {
925 // Can export from current BB.
926 if (VI->getParent() == FromBB)
929 // Is already exported, noop.
930 return FuncInfo.isExportedInst(V);
933 // If this is an argument, we can export it if the BB is the entry block or
934 // if it is already exported.
935 if (isa<Argument>(V)) {
936 if (FromBB == &FromBB->getParent()->getEntryBlock())
939 // Otherwise, can only export this if it is already exported.
940 return FuncInfo.isExportedInst(V);
943 // Otherwise, constants can always be exported.
947 static bool InBlock(const Value *V, const BasicBlock *BB) {
948 if (const Instruction *I = dyn_cast<Instruction>(V))
949 return I->getParent() == BB;
953 /// getFCmpCondCode - Return the ISD condition code corresponding to
954 /// the given LLVM IR floating-point condition code. This includes
955 /// consideration of global floating-point math flags.
957 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
958 ISD::CondCode FPC, FOC;
960 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
961 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
962 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
963 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
964 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
965 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
966 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
967 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
968 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
969 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
970 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
971 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
972 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
973 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
974 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
975 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
977 llvm_unreachable("Invalid FCmp predicate opcode!");
978 FOC = FPC = ISD::SETFALSE;
981 if (FiniteOnlyFPMath())
987 /// getICmpCondCode - Return the ISD condition code corresponding to
988 /// the given LLVM IR integer condition code.
990 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
992 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
993 case ICmpInst::ICMP_NE: return ISD::SETNE;
994 case ICmpInst::ICMP_SLE: return ISD::SETLE;
995 case ICmpInst::ICMP_ULE: return ISD::SETULE;
996 case ICmpInst::ICMP_SGE: return ISD::SETGE;
997 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
998 case ICmpInst::ICMP_SLT: return ISD::SETLT;
999 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1000 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1001 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1003 llvm_unreachable("Invalid ICmp predicate opcode!");
1008 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1009 /// This function emits a branch and is used at the leaves of an OR or an
1010 /// AND operator tree.
1013 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1014 MachineBasicBlock *TBB,
1015 MachineBasicBlock *FBB,
1016 MachineBasicBlock *CurBB) {
1017 const BasicBlock *BB = CurBB->getBasicBlock();
1019 // If the leaf of the tree is a comparison, merge the condition into
1021 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1022 // The operands of the cmp have to be in this block. We don't know
1023 // how to export them from some other block. If this is the first block
1024 // of the sequence, no exporting is needed.
1025 if (CurBB == CurMBB ||
1026 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1027 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1028 ISD::CondCode Condition;
1029 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1030 Condition = getICmpCondCode(IC->getPredicate());
1031 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1032 Condition = getFCmpCondCode(FC->getPredicate());
1034 Condition = ISD::SETEQ; // silence warning.
1035 llvm_unreachable("Unknown compare instruction");
1038 CaseBlock CB(Condition, BOp->getOperand(0),
1039 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1040 SwitchCases.push_back(CB);
1045 // Create a CaseBlock record representing this branch.
1046 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1047 NULL, TBB, FBB, CurBB);
1048 SwitchCases.push_back(CB);
1051 /// FindMergedConditions - If Cond is an expression like
1052 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1053 MachineBasicBlock *TBB,
1054 MachineBasicBlock *FBB,
1055 MachineBasicBlock *CurBB,
1057 // If this node is not part of the or/and tree, emit it as a branch.
1058 Instruction *BOp = dyn_cast<Instruction>(Cond);
1059 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1060 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1061 BOp->getParent() != CurBB->getBasicBlock() ||
1062 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1063 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1064 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1068 // Create TmpBB after CurBB.
1069 MachineFunction::iterator BBI = CurBB;
1070 MachineFunction &MF = DAG.getMachineFunction();
1071 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1072 CurBB->getParent()->insert(++BBI, TmpBB);
1074 if (Opc == Instruction::Or) {
1075 // Codegen X | Y as:
1083 // Emit the LHS condition.
1084 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1086 // Emit the RHS condition into TmpBB.
1087 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1089 assert(Opc == Instruction::And && "Unknown merge op!");
1090 // Codegen X & Y as:
1097 // This requires creation of TmpBB after CurBB.
1099 // Emit the LHS condition.
1100 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1102 // Emit the RHS condition into TmpBB.
1103 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1107 /// If the set of cases should be emitted as a series of branches, return true.
1108 /// If we should emit this as a bunch of and/or'd together conditions, return
1111 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1112 if (Cases.size() != 2) return true;
1114 // If this is two comparisons of the same values or'd or and'd together, they
1115 // will get folded into a single comparison, so don't emit two blocks.
1116 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1117 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1118 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1119 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1126 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1127 // Update machine-CFG edges.
1128 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1130 // Figure out which block is immediately after the current one.
1131 MachineBasicBlock *NextBlock = 0;
1132 MachineFunction::iterator BBI = CurMBB;
1133 if (++BBI != FuncInfo.MF->end())
1136 if (I.isUnconditional()) {
1137 // Update machine-CFG edges.
1138 CurMBB->addSuccessor(Succ0MBB);
1140 // If this is not a fall-through branch, emit the branch.
1141 if (Succ0MBB != NextBlock) {
1142 SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(),
1143 MVT::Other, getControlRoot(),
1144 DAG.getBasicBlock(Succ0MBB));
1147 if (DisableScheduling)
1148 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
1154 // If this condition is one of the special cases we handle, do special stuff
1156 Value *CondVal = I.getCondition();
1157 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1159 // If this is a series of conditions that are or'd or and'd together, emit
1160 // this as a sequence of branches instead of setcc's with and/or operations.
1161 // For example, instead of something like:
1174 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1175 if (BOp->hasOneUse() &&
1176 (BOp->getOpcode() == Instruction::And ||
1177 BOp->getOpcode() == Instruction::Or)) {
1178 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1179 // If the compares in later blocks need to use values not currently
1180 // exported from this block, export them now. This block should always
1181 // be the first entry.
1182 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1184 // Allow some cases to be rejected.
1185 if (ShouldEmitAsBranches(SwitchCases)) {
1186 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1187 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1188 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1191 // Emit the branch for this block.
1192 visitSwitchCase(SwitchCases[0]);
1193 SwitchCases.erase(SwitchCases.begin());
1197 // Okay, we decided not to do this, remove any inserted MBB's and clear
1199 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1200 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1202 SwitchCases.clear();
1206 // Create a CaseBlock record representing this branch.
1207 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1208 NULL, Succ0MBB, Succ1MBB, CurMBB);
1210 // Use visitSwitchCase to actually insert the fast branch sequence for this
1212 visitSwitchCase(CB);
1215 /// visitSwitchCase - Emits the necessary code to represent a single node in
1216 /// the binary search tree resulting from lowering a switch instruction.
1217 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1219 SDValue CondLHS = getValue(CB.CmpLHS);
1220 DebugLoc dl = getCurDebugLoc();
1222 // Build the setcc now.
1223 if (CB.CmpMHS == NULL) {
1224 // Fold "(X == true)" to X and "(X == false)" to !X to
1225 // handle common cases produced by branch lowering.
1226 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1227 CB.CC == ISD::SETEQ)
1229 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1230 CB.CC == ISD::SETEQ) {
1231 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1232 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1234 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1236 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1238 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1239 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1241 SDValue CmpOp = getValue(CB.CmpMHS);
1242 EVT VT = CmpOp.getValueType();
1244 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1245 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1248 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1249 VT, CmpOp, DAG.getConstant(Low, VT));
1250 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1251 DAG.getConstant(High-Low, VT), ISD::SETULE);
1255 if (DisableScheduling)
1256 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1258 // Update successor info
1259 CurMBB->addSuccessor(CB.TrueBB);
1260 CurMBB->addSuccessor(CB.FalseBB);
1262 // Set NextBlock to be the MBB immediately after the current one, if any.
1263 // This is used to avoid emitting unnecessary branches to the next block.
1264 MachineBasicBlock *NextBlock = 0;
1265 MachineFunction::iterator BBI = CurMBB;
1266 if (++BBI != FuncInfo.MF->end())
1269 // If the lhs block is the next block, invert the condition so that we can
1270 // fall through to the lhs instead of the rhs block.
1271 if (CB.TrueBB == NextBlock) {
1272 std::swap(CB.TrueBB, CB.FalseBB);
1273 SDValue True = DAG.getConstant(1, Cond.getValueType());
1274 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1276 if (DisableScheduling)
1277 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1280 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1281 MVT::Other, getControlRoot(), Cond,
1282 DAG.getBasicBlock(CB.TrueBB));
1284 if (DisableScheduling)
1285 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1287 // If the branch was constant folded, fix up the CFG.
1288 if (BrCond.getOpcode() == ISD::BR) {
1289 CurMBB->removeSuccessor(CB.FalseBB);
1291 // Otherwise, go ahead and insert the false branch.
1292 if (BrCond == getControlRoot())
1293 CurMBB->removeSuccessor(CB.TrueBB);
1295 if (CB.FalseBB != NextBlock) {
1296 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1297 DAG.getBasicBlock(CB.FalseBB));
1299 if (DisableScheduling)
1300 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1304 DAG.setRoot(BrCond);
1307 /// visitJumpTable - Emit JumpTable node in the current MBB
1308 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1309 // Emit the code for the jump table
1310 assert(JT.Reg != -1U && "Should lower JT Header first!");
1311 EVT PTy = TLI.getPointerTy();
1312 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1314 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1315 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1316 MVT::Other, Index.getValue(1),
1318 DAG.setRoot(BrJumpTable);
1320 if (DisableScheduling) {
1321 DAG.AssignOrdering(Index.getNode(), SDNodeOrder);
1322 DAG.AssignOrdering(Table.getNode(), SDNodeOrder);
1323 DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder);
1327 /// visitJumpTableHeader - This function emits necessary code to produce index
1328 /// in the JumpTable from switch case.
1329 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1330 JumpTableHeader &JTH) {
1331 // Subtract the lowest switch case value from the value being switched on and
1332 // conditional branch to default mbb if the result is greater than the
1333 // difference between smallest and largest cases.
1334 SDValue SwitchOp = getValue(JTH.SValue);
1335 EVT VT = SwitchOp.getValueType();
1336 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1337 DAG.getConstant(JTH.First, VT));
1339 // The SDNode we just created, which holds the value being switched on minus
1340 // the the smallest case value, needs to be copied to a virtual register so it
1341 // can be used as an index into the jump table in a subsequent basic block.
1342 // This value may be smaller or larger than the target's pointer type, and
1343 // therefore require extension or truncating.
1344 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1346 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1347 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1348 JumpTableReg, SwitchOp);
1349 JT.Reg = JumpTableReg;
1351 // Emit the range check for the jump table, and branch to the default block
1352 // for the switch statement if the value being switched on exceeds the largest
1353 // case in the switch.
1354 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1355 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1356 DAG.getConstant(JTH.Last-JTH.First,VT),
1359 if (DisableScheduling) {
1360 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1361 DAG.AssignOrdering(SwitchOp.getNode(), SDNodeOrder);
1362 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1363 DAG.AssignOrdering(CMP.getNode(), SDNodeOrder);
1366 // Set NextBlock to be the MBB immediately after the current one, if any.
1367 // This is used to avoid emitting unnecessary branches to the next block.
1368 MachineBasicBlock *NextBlock = 0;
1369 MachineFunction::iterator BBI = CurMBB;
1371 if (++BBI != FuncInfo.MF->end())
1374 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1375 MVT::Other, CopyTo, CMP,
1376 DAG.getBasicBlock(JT.Default));
1378 if (DisableScheduling)
1379 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1381 if (JT.MBB != NextBlock) {
1382 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1383 DAG.getBasicBlock(JT.MBB));
1385 if (DisableScheduling)
1386 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1389 DAG.setRoot(BrCond);
1392 /// visitBitTestHeader - This function emits necessary code to produce value
1393 /// suitable for "bit tests"
1394 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1395 // Subtract the minimum value
1396 SDValue SwitchOp = getValue(B.SValue);
1397 EVT VT = SwitchOp.getValueType();
1398 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1399 DAG.getConstant(B.First, VT));
1402 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1403 TLI.getSetCCResultType(Sub.getValueType()),
1404 Sub, DAG.getConstant(B.Range, VT),
1407 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1408 TLI.getPointerTy());
1410 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1411 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1414 if (DisableScheduling) {
1415 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1416 DAG.AssignOrdering(RangeCmp.getNode(), SDNodeOrder);
1417 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1418 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1421 // Set NextBlock to be the MBB immediately after the current one, if any.
1422 // This is used to avoid emitting unnecessary branches to the next block.
1423 MachineBasicBlock *NextBlock = 0;
1424 MachineFunction::iterator BBI = CurMBB;
1425 if (++BBI != FuncInfo.MF->end())
1428 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1430 CurMBB->addSuccessor(B.Default);
1431 CurMBB->addSuccessor(MBB);
1433 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1434 MVT::Other, CopyTo, RangeCmp,
1435 DAG.getBasicBlock(B.Default));
1437 if (DisableScheduling)
1438 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1440 if (MBB != NextBlock) {
1441 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1442 DAG.getBasicBlock(MBB));
1444 if (DisableScheduling)
1445 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1448 DAG.setRoot(BrRange);
1451 /// visitBitTestCase - this function produces one "bit test"
1452 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1455 // Make desired shift
1456 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1457 TLI.getPointerTy());
1458 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1460 DAG.getConstant(1, TLI.getPointerTy()),
1463 // Emit bit tests and jumps
1464 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1465 TLI.getPointerTy(), SwitchVal,
1466 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1467 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1468 TLI.getSetCCResultType(AndOp.getValueType()),
1469 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1472 if (DisableScheduling) {
1473 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1474 DAG.AssignOrdering(SwitchVal.getNode(), SDNodeOrder);
1475 DAG.AssignOrdering(AndOp.getNode(), SDNodeOrder);
1476 DAG.AssignOrdering(AndCmp.getNode(), SDNodeOrder);
1479 CurMBB->addSuccessor(B.TargetBB);
1480 CurMBB->addSuccessor(NextMBB);
1482 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1483 MVT::Other, getControlRoot(),
1484 AndCmp, DAG.getBasicBlock(B.TargetBB));
1486 if (DisableScheduling)
1487 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1489 // Set NextBlock to be the MBB immediately after the current one, if any.
1490 // This is used to avoid emitting unnecessary branches to the next block.
1491 MachineBasicBlock *NextBlock = 0;
1492 MachineFunction::iterator BBI = CurMBB;
1493 if (++BBI != FuncInfo.MF->end())
1496 if (NextMBB != NextBlock) {
1497 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1498 DAG.getBasicBlock(NextMBB));
1500 if (DisableScheduling)
1501 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1507 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1508 // Retrieve successors.
1509 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1510 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1512 const Value *Callee(I.getCalledValue());
1513 if (isa<InlineAsm>(Callee))
1516 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1518 // If the value of the invoke is used outside of its defining block, make it
1519 // available as a virtual register.
1520 CopyToExportRegsIfNeeded(&I);
1522 // Update successor info
1523 CurMBB->addSuccessor(Return);
1524 CurMBB->addSuccessor(LandingPad);
1526 // Drop into normal successor.
1527 SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(),
1528 MVT::Other, getControlRoot(),
1529 DAG.getBasicBlock(Return));
1530 DAG.setRoot(Branch);
1532 if (DisableScheduling)
1533 DAG.AssignOrdering(Branch.getNode(), SDNodeOrder);
1536 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1539 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1540 /// small case ranges).
1541 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1542 CaseRecVector& WorkList,
1544 MachineBasicBlock* Default) {
1545 Case& BackCase = *(CR.Range.second-1);
1547 // Size is the number of Cases represented by this range.
1548 size_t Size = CR.Range.second - CR.Range.first;
1552 // Get the MachineFunction which holds the current MBB. This is used when
1553 // inserting any additional MBBs necessary to represent the switch.
1554 MachineFunction *CurMF = FuncInfo.MF;
1556 // Figure out which block is immediately after the current one.
1557 MachineBasicBlock *NextBlock = 0;
1558 MachineFunction::iterator BBI = CR.CaseBB;
1560 if (++BBI != FuncInfo.MF->end())
1563 // TODO: If any two of the cases has the same destination, and if one value
1564 // is the same as the other, but has one bit unset that the other has set,
1565 // use bit manipulation to do two compares at once. For example:
1566 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1568 // Rearrange the case blocks so that the last one falls through if possible.
1569 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1570 // The last case block won't fall through into 'NextBlock' if we emit the
1571 // branches in this order. See if rearranging a case value would help.
1572 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1573 if (I->BB == NextBlock) {
1574 std::swap(*I, BackCase);
1580 // Create a CaseBlock record representing a conditional branch to
1581 // the Case's target mbb if the value being switched on SV is equal
1583 MachineBasicBlock *CurBlock = CR.CaseBB;
1584 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1585 MachineBasicBlock *FallThrough;
1587 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1588 CurMF->insert(BBI, FallThrough);
1590 // Put SV in a virtual register to make it available from the new blocks.
1591 ExportFromCurrentBlock(SV);
1593 // If the last case doesn't match, go to the default block.
1594 FallThrough = Default;
1597 Value *RHS, *LHS, *MHS;
1599 if (I->High == I->Low) {
1600 // This is just small small case range :) containing exactly 1 case
1602 LHS = SV; RHS = I->High; MHS = NULL;
1605 LHS = I->Low; MHS = SV; RHS = I->High;
1607 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1609 // If emitting the first comparison, just call visitSwitchCase to emit the
1610 // code into the current block. Otherwise, push the CaseBlock onto the
1611 // vector to be later processed by SDISel, and insert the node's MBB
1612 // before the next MBB.
1613 if (CurBlock == CurMBB)
1614 visitSwitchCase(CB);
1616 SwitchCases.push_back(CB);
1618 CurBlock = FallThrough;
1624 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1625 return !DisableJumpTables &&
1626 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1627 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1630 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1631 APInt LastExt(Last), FirstExt(First);
1632 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1633 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1634 return (LastExt - FirstExt + 1ULL);
1637 /// handleJTSwitchCase - Emit jumptable for current switch case range
1638 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1639 CaseRecVector& WorkList,
1641 MachineBasicBlock* Default) {
1642 Case& FrontCase = *CR.Range.first;
1643 Case& BackCase = *(CR.Range.second-1);
1645 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1646 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1648 APInt TSize(First.getBitWidth(), 0);
1649 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1653 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1656 APInt Range = ComputeRange(First, Last);
1657 double Density = TSize.roundToDouble() / Range.roundToDouble();
1661 DEBUG(errs() << "Lowering jump table\n"
1662 << "First entry: " << First << ". Last entry: " << Last << '\n'
1663 << "Range: " << Range
1664 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1666 // Get the MachineFunction which holds the current MBB. This is used when
1667 // inserting any additional MBBs necessary to represent the switch.
1668 MachineFunction *CurMF = FuncInfo.MF;
1670 // Figure out which block is immediately after the current one.
1671 MachineFunction::iterator BBI = CR.CaseBB;
1674 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1676 // Create a new basic block to hold the code for loading the address
1677 // of the jump table, and jumping to it. Update successor information;
1678 // we will either branch to the default case for the switch, or the jump
1680 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1681 CurMF->insert(BBI, JumpTableBB);
1682 CR.CaseBB->addSuccessor(Default);
1683 CR.CaseBB->addSuccessor(JumpTableBB);
1685 // Build a vector of destination BBs, corresponding to each target
1686 // of the jump table. If the value of the jump table slot corresponds to
1687 // a case statement, push the case's BB onto the vector, otherwise, push
1689 std::vector<MachineBasicBlock*> DestBBs;
1691 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1692 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1693 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1695 if (Low.sle(TEI) && TEI.sle(High)) {
1696 DestBBs.push_back(I->BB);
1700 DestBBs.push_back(Default);
1704 // Update successor info. Add one edge to each unique successor.
1705 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1706 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1707 E = DestBBs.end(); I != E; ++I) {
1708 if (!SuccsHandled[(*I)->getNumber()]) {
1709 SuccsHandled[(*I)->getNumber()] = true;
1710 JumpTableBB->addSuccessor(*I);
1714 // Create a jump table index for this jump table, or return an existing
1716 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1718 // Set the jump table information so that we can codegen it as a second
1719 // MachineBasicBlock
1720 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1721 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1722 if (CR.CaseBB == CurMBB)
1723 visitJumpTableHeader(JT, JTH);
1725 JTCases.push_back(JumpTableBlock(JTH, JT));
1730 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1732 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1733 CaseRecVector& WorkList,
1735 MachineBasicBlock* Default) {
1736 // Get the MachineFunction which holds the current MBB. This is used when
1737 // inserting any additional MBBs necessary to represent the switch.
1738 MachineFunction *CurMF = FuncInfo.MF;
1740 // Figure out which block is immediately after the current one.
1741 MachineFunction::iterator BBI = CR.CaseBB;
1744 Case& FrontCase = *CR.Range.first;
1745 Case& BackCase = *(CR.Range.second-1);
1746 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1748 // Size is the number of Cases represented by this range.
1749 unsigned Size = CR.Range.second - CR.Range.first;
1751 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1752 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1754 CaseItr Pivot = CR.Range.first + Size/2;
1756 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1757 // (heuristically) allow us to emit JumpTable's later.
1758 APInt TSize(First.getBitWidth(), 0);
1759 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1763 APInt LSize = FrontCase.size();
1764 APInt RSize = TSize-LSize;
1765 DEBUG(errs() << "Selecting best pivot: \n"
1766 << "First: " << First << ", Last: " << Last <<'\n'
1767 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1768 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1770 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1771 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1772 APInt Range = ComputeRange(LEnd, RBegin);
1773 assert((Range - 2ULL).isNonNegative() &&
1774 "Invalid case distance");
1775 double LDensity = (double)LSize.roundToDouble() /
1776 (LEnd - First + 1ULL).roundToDouble();
1777 double RDensity = (double)RSize.roundToDouble() /
1778 (Last - RBegin + 1ULL).roundToDouble();
1779 double Metric = Range.logBase2()*(LDensity+RDensity);
1780 // Should always split in some non-trivial place
1781 DEBUG(errs() <<"=>Step\n"
1782 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1783 << "LDensity: " << LDensity
1784 << ", RDensity: " << RDensity << '\n'
1785 << "Metric: " << Metric << '\n');
1786 if (FMetric < Metric) {
1789 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1795 if (areJTsAllowed(TLI)) {
1796 // If our case is dense we *really* should handle it earlier!
1797 assert((FMetric > 0) && "Should handle dense range earlier!");
1799 Pivot = CR.Range.first + Size/2;
1802 CaseRange LHSR(CR.Range.first, Pivot);
1803 CaseRange RHSR(Pivot, CR.Range.second);
1804 Constant *C = Pivot->Low;
1805 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1807 // We know that we branch to the LHS if the Value being switched on is
1808 // less than the Pivot value, C. We use this to optimize our binary
1809 // tree a bit, by recognizing that if SV is greater than or equal to the
1810 // LHS's Case Value, and that Case Value is exactly one less than the
1811 // Pivot's Value, then we can branch directly to the LHS's Target,
1812 // rather than creating a leaf node for it.
1813 if ((LHSR.second - LHSR.first) == 1 &&
1814 LHSR.first->High == CR.GE &&
1815 cast<ConstantInt>(C)->getValue() ==
1816 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1817 TrueBB = LHSR.first->BB;
1819 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1820 CurMF->insert(BBI, TrueBB);
1821 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1823 // Put SV in a virtual register to make it available from the new blocks.
1824 ExportFromCurrentBlock(SV);
1827 // Similar to the optimization above, if the Value being switched on is
1828 // known to be less than the Constant CR.LT, and the current Case Value
1829 // is CR.LT - 1, then we can branch directly to the target block for
1830 // the current Case Value, rather than emitting a RHS leaf node for it.
1831 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1832 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1833 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1834 FalseBB = RHSR.first->BB;
1836 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1837 CurMF->insert(BBI, FalseBB);
1838 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1840 // Put SV in a virtual register to make it available from the new blocks.
1841 ExportFromCurrentBlock(SV);
1844 // Create a CaseBlock record representing a conditional branch to
1845 // the LHS node if the value being switched on SV is less than C.
1846 // Otherwise, branch to LHS.
1847 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1849 if (CR.CaseBB == CurMBB)
1850 visitSwitchCase(CB);
1852 SwitchCases.push_back(CB);
1857 /// handleBitTestsSwitchCase - if current case range has few destination and
1858 /// range span less, than machine word bitwidth, encode case range into series
1859 /// of masks and emit bit tests with these masks.
1860 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1861 CaseRecVector& WorkList,
1863 MachineBasicBlock* Default){
1864 EVT PTy = TLI.getPointerTy();
1865 unsigned IntPtrBits = PTy.getSizeInBits();
1867 Case& FrontCase = *CR.Range.first;
1868 Case& BackCase = *(CR.Range.second-1);
1870 // Get the MachineFunction which holds the current MBB. This is used when
1871 // inserting any additional MBBs necessary to represent the switch.
1872 MachineFunction *CurMF = FuncInfo.MF;
1874 // If target does not have legal shift left, do not emit bit tests at all.
1875 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1879 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1881 // Single case counts one, case range - two.
1882 numCmps += (I->Low == I->High ? 1 : 2);
1885 // Count unique destinations
1886 SmallSet<MachineBasicBlock*, 4> Dests;
1887 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1888 Dests.insert(I->BB);
1889 if (Dests.size() > 3)
1890 // Don't bother the code below, if there are too much unique destinations
1893 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1894 << "Total number of comparisons: " << numCmps << '\n');
1896 // Compute span of values.
1897 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1898 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1899 APInt cmpRange = maxValue - minValue;
1901 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1902 << "Low bound: " << minValue << '\n'
1903 << "High bound: " << maxValue << '\n');
1905 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1906 (!(Dests.size() == 1 && numCmps >= 3) &&
1907 !(Dests.size() == 2 && numCmps >= 5) &&
1908 !(Dests.size() >= 3 && numCmps >= 6)))
1911 DEBUG(errs() << "Emitting bit tests\n");
1912 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1914 // Optimize the case where all the case values fit in a
1915 // word without having to subtract minValue. In this case,
1916 // we can optimize away the subtraction.
1917 if (minValue.isNonNegative() &&
1918 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1919 cmpRange = maxValue;
1921 lowBound = minValue;
1924 CaseBitsVector CasesBits;
1925 unsigned i, count = 0;
1927 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1928 MachineBasicBlock* Dest = I->BB;
1929 for (i = 0; i < count; ++i)
1930 if (Dest == CasesBits[i].BB)
1934 assert((count < 3) && "Too much destinations to test!");
1935 CasesBits.push_back(CaseBits(0, Dest, 0));
1939 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1940 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1942 uint64_t lo = (lowValue - lowBound).getZExtValue();
1943 uint64_t hi = (highValue - lowBound).getZExtValue();
1945 for (uint64_t j = lo; j <= hi; j++) {
1946 CasesBits[i].Mask |= 1ULL << j;
1947 CasesBits[i].Bits++;
1951 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1955 // Figure out which block is immediately after the current one.
1956 MachineFunction::iterator BBI = CR.CaseBB;
1959 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1961 DEBUG(errs() << "Cases:\n");
1962 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1963 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1964 << ", Bits: " << CasesBits[i].Bits
1965 << ", BB: " << CasesBits[i].BB << '\n');
1967 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1968 CurMF->insert(BBI, CaseBB);
1969 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1973 // Put SV in a virtual register to make it available from the new blocks.
1974 ExportFromCurrentBlock(SV);
1977 BitTestBlock BTB(lowBound, cmpRange, SV,
1978 -1U, (CR.CaseBB == CurMBB),
1979 CR.CaseBB, Default, BTC);
1981 if (CR.CaseBB == CurMBB)
1982 visitBitTestHeader(BTB);
1984 BitTestCases.push_back(BTB);
1989 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1990 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1991 const SwitchInst& SI) {
1994 // Start with "simple" cases
1995 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1996 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1997 Cases.push_back(Case(SI.getSuccessorValue(i),
1998 SI.getSuccessorValue(i),
2001 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2003 // Merge case into clusters
2004 if (Cases.size() >= 2)
2005 // Must recompute end() each iteration because it may be
2006 // invalidated by erase if we hold on to it
2007 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2008 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2009 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2010 MachineBasicBlock* nextBB = J->BB;
2011 MachineBasicBlock* currentBB = I->BB;
2013 // If the two neighboring cases go to the same destination, merge them
2014 // into a single case.
2015 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2023 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2024 if (I->Low != I->High)
2025 // A range counts double, since it requires two compares.
2032 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
2033 // Figure out which block is immediately after the current one.
2034 MachineBasicBlock *NextBlock = 0;
2035 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2037 // If there is only the default destination, branch to it if it is not the
2038 // next basic block. Otherwise, just fall through.
2039 if (SI.getNumOperands() == 2) {
2040 // Update machine-CFG edges.
2042 // If this is not a fall-through branch, emit the branch.
2043 CurMBB->addSuccessor(Default);
2044 if (Default != NextBlock) {
2045 SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(),
2046 MVT::Other, getControlRoot(),
2047 DAG.getBasicBlock(Default));
2050 if (DisableScheduling)
2051 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2057 // If there are any non-default case statements, create a vector of Cases
2058 // representing each one, and sort the vector so that we can efficiently
2059 // create a binary search tree from them.
2061 size_t numCmps = Clusterify(Cases, SI);
2062 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2063 << ". Total compares: " << numCmps << '\n');
2066 // Get the Value to be switched on and default basic blocks, which will be
2067 // inserted into CaseBlock records, representing basic blocks in the binary
2069 Value *SV = SI.getOperand(0);
2071 // Push the initial CaseRec onto the worklist
2072 CaseRecVector WorkList;
2073 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2075 while (!WorkList.empty()) {
2076 // Grab a record representing a case range to process off the worklist
2077 CaseRec CR = WorkList.back();
2078 WorkList.pop_back();
2080 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2083 // If the range has few cases (two or less) emit a series of specific
2085 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2088 // If the switch has more than 5 blocks, and at least 40% dense, and the
2089 // target supports indirect branches, then emit a jump table rather than
2090 // lowering the switch to a binary tree of conditional branches.
2091 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2094 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2095 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2096 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2100 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2101 // Update machine-CFG edges.
2102 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2103 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2105 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2106 MVT::Other, getControlRoot(),
2107 getValue(I.getAddress()));
2110 if (DisableScheduling)
2111 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2114 void SelectionDAGBuilder::visitFSub(User &I) {
2115 // -0.0 - X --> fneg
2116 const Type *Ty = I.getType();
2117 if (isa<VectorType>(Ty)) {
2118 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2119 const VectorType *DestTy = cast<VectorType>(I.getType());
2120 const Type *ElTy = DestTy->getElementType();
2121 unsigned VL = DestTy->getNumElements();
2122 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2123 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2125 SDValue Op2 = getValue(I.getOperand(1));
2126 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2127 Op2.getValueType(), Op2);
2130 if (DisableScheduling)
2131 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2138 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2139 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2140 SDValue Op2 = getValue(I.getOperand(1));
2141 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2142 Op2.getValueType(), Op2);
2145 if (DisableScheduling)
2146 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2151 visitBinary(I, ISD::FSUB);
2154 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2155 SDValue Op1 = getValue(I.getOperand(0));
2156 SDValue Op2 = getValue(I.getOperand(1));
2157 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(),
2158 Op1.getValueType(), Op1, Op2);
2161 if (DisableScheduling)
2162 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2165 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2166 SDValue Op1 = getValue(I.getOperand(0));
2167 SDValue Op2 = getValue(I.getOperand(1));
2168 if (!isa<VectorType>(I.getType()) &&
2169 Op2.getValueType() != TLI.getShiftAmountTy()) {
2170 // If the operand is smaller than the shift count type, promote it.
2171 EVT PTy = TLI.getPointerTy();
2172 EVT STy = TLI.getShiftAmountTy();
2173 if (STy.bitsGT(Op2.getValueType()))
2174 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2175 TLI.getShiftAmountTy(), Op2);
2176 // If the operand is larger than the shift count type but the shift
2177 // count type has enough bits to represent any shift value, truncate
2178 // it now. This is a common case and it exposes the truncate to
2179 // optimization early.
2180 else if (STy.getSizeInBits() >=
2181 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2182 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2183 TLI.getShiftAmountTy(), Op2);
2184 // Otherwise we'll need to temporarily settle for some other
2185 // convenient type; type legalization will make adjustments as
2187 else if (PTy.bitsLT(Op2.getValueType()))
2188 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2189 TLI.getPointerTy(), Op2);
2190 else if (PTy.bitsGT(Op2.getValueType()))
2191 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2192 TLI.getPointerTy(), Op2);
2195 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(),
2196 Op1.getValueType(), Op1, Op2);
2199 if (DisableScheduling) {
2200 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
2201 DAG.AssignOrdering(Op2.getNode(), SDNodeOrder);
2202 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2206 void SelectionDAGBuilder::visitICmp(User &I) {
2207 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2208 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2209 predicate = IC->getPredicate();
2210 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2211 predicate = ICmpInst::Predicate(IC->getPredicate());
2212 SDValue Op1 = getValue(I.getOperand(0));
2213 SDValue Op2 = getValue(I.getOperand(1));
2214 ISD::CondCode Opcode = getICmpCondCode(predicate);
2216 EVT DestVT = TLI.getValueType(I.getType());
2217 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode);
2220 if (DisableScheduling)
2221 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2224 void SelectionDAGBuilder::visitFCmp(User &I) {
2225 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2226 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2227 predicate = FC->getPredicate();
2228 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2229 predicate = FCmpInst::Predicate(FC->getPredicate());
2230 SDValue Op1 = getValue(I.getOperand(0));
2231 SDValue Op2 = getValue(I.getOperand(1));
2232 ISD::CondCode Condition = getFCmpCondCode(predicate);
2233 EVT DestVT = TLI.getValueType(I.getType());
2234 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition);
2237 if (DisableScheduling)
2238 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2241 void SelectionDAGBuilder::visitSelect(User &I) {
2242 SmallVector<EVT, 4> ValueVTs;
2243 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2244 unsigned NumValues = ValueVTs.size();
2245 if (NumValues == 0) return;
2247 SmallVector<SDValue, 4> Values(NumValues);
2248 SDValue Cond = getValue(I.getOperand(0));
2249 SDValue TrueVal = getValue(I.getOperand(1));
2250 SDValue FalseVal = getValue(I.getOperand(2));
2252 for (unsigned i = 0; i != NumValues; ++i) {
2253 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2254 TrueVal.getNode()->getValueType(i), Cond,
2255 SDValue(TrueVal.getNode(),
2256 TrueVal.getResNo() + i),
2257 SDValue(FalseVal.getNode(),
2258 FalseVal.getResNo() + i));
2260 if (DisableScheduling)
2261 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder);
2264 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2265 DAG.getVTList(&ValueVTs[0], NumValues),
2266 &Values[0], NumValues);
2269 if (DisableScheduling)
2270 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2273 void SelectionDAGBuilder::visitTrunc(User &I) {
2274 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2275 SDValue N = getValue(I.getOperand(0));
2276 EVT DestVT = TLI.getValueType(I.getType());
2277 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2280 if (DisableScheduling)
2281 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2284 void SelectionDAGBuilder::visitZExt(User &I) {
2285 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2286 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2287 SDValue N = getValue(I.getOperand(0));
2288 EVT DestVT = TLI.getValueType(I.getType());
2289 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2292 if (DisableScheduling)
2293 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2296 void SelectionDAGBuilder::visitSExt(User &I) {
2297 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2298 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2299 SDValue N = getValue(I.getOperand(0));
2300 EVT DestVT = TLI.getValueType(I.getType());
2301 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N);
2304 if (DisableScheduling)
2305 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2308 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2309 // FPTrunc is never a no-op cast, no need to check
2310 SDValue N = getValue(I.getOperand(0));
2311 EVT DestVT = TLI.getValueType(I.getType());
2312 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2313 DestVT, N, DAG.getIntPtrConstant(0));
2316 if (DisableScheduling)
2317 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2320 void SelectionDAGBuilder::visitFPExt(User &I){
2321 // FPTrunc is never a no-op cast, no need to check
2322 SDValue N = getValue(I.getOperand(0));
2323 EVT DestVT = TLI.getValueType(I.getType());
2324 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N);
2327 if (DisableScheduling)
2328 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2331 void SelectionDAGBuilder::visitFPToUI(User &I) {
2332 // FPToUI is never a no-op cast, no need to check
2333 SDValue N = getValue(I.getOperand(0));
2334 EVT DestVT = TLI.getValueType(I.getType());
2335 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N);
2338 if (DisableScheduling)
2339 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2342 void SelectionDAGBuilder::visitFPToSI(User &I) {
2343 // FPToSI is never a no-op cast, no need to check
2344 SDValue N = getValue(I.getOperand(0));
2345 EVT DestVT = TLI.getValueType(I.getType());
2346 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N);
2349 if (DisableScheduling)
2350 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2353 void SelectionDAGBuilder::visitUIToFP(User &I) {
2354 // UIToFP is never a no-op cast, no need to check
2355 SDValue N = getValue(I.getOperand(0));
2356 EVT DestVT = TLI.getValueType(I.getType());
2357 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N);
2360 if (DisableScheduling)
2361 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2364 void SelectionDAGBuilder::visitSIToFP(User &I){
2365 // SIToFP is never a no-op cast, no need to check
2366 SDValue N = getValue(I.getOperand(0));
2367 EVT DestVT = TLI.getValueType(I.getType());
2368 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N);
2371 if (DisableScheduling)
2372 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2375 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2376 // What to do depends on the size of the integer and the size of the pointer.
2377 // We can either truncate, zero extend, or no-op, accordingly.
2378 SDValue N = getValue(I.getOperand(0));
2379 EVT SrcVT = N.getValueType();
2380 EVT DestVT = TLI.getValueType(I.getType());
2381 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2384 if (DisableScheduling)
2385 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2388 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2389 // What to do depends on the size of the integer and the size of the pointer.
2390 // We can either truncate, zero extend, or no-op, accordingly.
2391 SDValue N = getValue(I.getOperand(0));
2392 EVT SrcVT = N.getValueType();
2393 EVT DestVT = TLI.getValueType(I.getType());
2394 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2397 if (DisableScheduling)
2398 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2401 void SelectionDAGBuilder::visitBitCast(User &I) {
2402 SDValue N = getValue(I.getOperand(0));
2403 EVT DestVT = TLI.getValueType(I.getType());
2405 // BitCast assures us that source and destination are the same size so this is
2406 // either a BIT_CONVERT or a no-op.
2407 if (DestVT != N.getValueType()) {
2408 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2409 DestVT, N); // convert types.
2412 if (DisableScheduling)
2413 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2415 setValue(&I, N); // noop cast.
2419 void SelectionDAGBuilder::visitInsertElement(User &I) {
2420 SDValue InVec = getValue(I.getOperand(0));
2421 SDValue InVal = getValue(I.getOperand(1));
2422 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2424 getValue(I.getOperand(2)));
2425 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2426 TLI.getValueType(I.getType()),
2427 InVec, InVal, InIdx);
2430 if (DisableScheduling) {
2431 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2432 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2436 void SelectionDAGBuilder::visitExtractElement(User &I) {
2437 SDValue InVec = getValue(I.getOperand(0));
2438 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2440 getValue(I.getOperand(1)));
2441 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2442 TLI.getValueType(I.getType()), InVec, InIdx);
2445 if (DisableScheduling) {
2446 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2447 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2452 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2453 // from SIndx and increasing to the element length (undefs are allowed).
2454 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2455 unsigned MaskNumElts = Mask.size();
2456 for (unsigned i = 0; i != MaskNumElts; ++i)
2457 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2462 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2463 SmallVector<int, 8> Mask;
2464 SDValue Src1 = getValue(I.getOperand(0));
2465 SDValue Src2 = getValue(I.getOperand(1));
2467 // Convert the ConstantVector mask operand into an array of ints, with -1
2468 // representing undef values.
2469 SmallVector<Constant*, 8> MaskElts;
2470 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2472 unsigned MaskNumElts = MaskElts.size();
2473 for (unsigned i = 0; i != MaskNumElts; ++i) {
2474 if (isa<UndefValue>(MaskElts[i]))
2477 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2480 EVT VT = TLI.getValueType(I.getType());
2481 EVT SrcVT = Src1.getValueType();
2482 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2484 if (SrcNumElts == MaskNumElts) {
2485 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2489 if (DisableScheduling)
2490 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2495 // Normalize the shuffle vector since mask and vector length don't match.
2496 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2497 // Mask is longer than the source vectors and is a multiple of the source
2498 // vectors. We can use concatenate vector to make the mask and vectors
2500 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2501 // The shuffle is concatenating two vectors together.
2502 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2506 if (DisableScheduling)
2507 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2512 // Pad both vectors with undefs to make them the same length as the mask.
2513 unsigned NumConcat = MaskNumElts / SrcNumElts;
2514 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2515 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2516 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2518 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2519 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2523 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2524 getCurDebugLoc(), VT,
2525 &MOps1[0], NumConcat);
2526 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2527 getCurDebugLoc(), VT,
2528 &MOps2[0], NumConcat);
2530 // Readjust mask for new input vector length.
2531 SmallVector<int, 8> MappedOps;
2532 for (unsigned i = 0; i != MaskNumElts; ++i) {
2534 if (Idx < (int)SrcNumElts)
2535 MappedOps.push_back(Idx);
2537 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2540 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2544 if (DisableScheduling) {
2545 DAG.AssignOrdering(Src1.getNode(), SDNodeOrder);
2546 DAG.AssignOrdering(Src2.getNode(), SDNodeOrder);
2547 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2553 if (SrcNumElts > MaskNumElts) {
2554 // Analyze the access pattern of the vector to see if we can extract
2555 // two subvectors and do the shuffle. The analysis is done by calculating
2556 // the range of elements the mask access on both vectors.
2557 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2558 int MaxRange[2] = {-1, -1};
2560 for (unsigned i = 0; i != MaskNumElts; ++i) {
2566 if (Idx >= (int)SrcNumElts) {
2570 if (Idx > MaxRange[Input])
2571 MaxRange[Input] = Idx;
2572 if (Idx < MinRange[Input])
2573 MinRange[Input] = Idx;
2576 // Check if the access is smaller than the vector size and can we find
2577 // a reasonable extract index.
2578 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2579 int StartIdx[2]; // StartIdx to extract from
2580 for (int Input=0; Input < 2; ++Input) {
2581 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2582 RangeUse[Input] = 0; // Unused
2583 StartIdx[Input] = 0;
2584 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2585 // Fits within range but we should see if we can find a good
2586 // start index that is a multiple of the mask length.
2587 if (MaxRange[Input] < (int)MaskNumElts) {
2588 RangeUse[Input] = 1; // Extract from beginning of the vector
2589 StartIdx[Input] = 0;
2591 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2592 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2593 StartIdx[Input] + MaskNumElts < SrcNumElts)
2594 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2599 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2600 SDValue Res = DAG.getUNDEF(VT);
2601 setValue(&I, Res); // Vectors are not used.
2603 if (DisableScheduling)
2604 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2608 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2609 // Extract appropriate subvector and generate a vector shuffle
2610 for (int Input=0; Input < 2; ++Input) {
2611 SDValue &Src = Input == 0 ? Src1 : Src2;
2612 if (RangeUse[Input] == 0)
2613 Src = DAG.getUNDEF(VT);
2615 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2616 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2618 if (DisableScheduling)
2619 DAG.AssignOrdering(Src.getNode(), SDNodeOrder);
2622 // Calculate new mask.
2623 SmallVector<int, 8> MappedOps;
2624 for (unsigned i = 0; i != MaskNumElts; ++i) {
2627 MappedOps.push_back(Idx);
2628 else if (Idx < (int)SrcNumElts)
2629 MappedOps.push_back(Idx - StartIdx[0]);
2631 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2634 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2638 if (DisableScheduling)
2639 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2645 // We can't use either concat vectors or extract subvectors so fall back to
2646 // replacing the shuffle with extract and build vector.
2647 // to insert and build vector.
2648 EVT EltVT = VT.getVectorElementType();
2649 EVT PtrVT = TLI.getPointerTy();
2650 SmallVector<SDValue,8> Ops;
2651 for (unsigned i = 0; i != MaskNumElts; ++i) {
2653 Ops.push_back(DAG.getUNDEF(EltVT));
2658 if (Idx < (int)SrcNumElts)
2659 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2660 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2662 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2664 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2668 if (DisableScheduling)
2669 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2673 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2674 VT, &Ops[0], Ops.size());
2677 if (DisableScheduling)
2678 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2681 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2682 const Value *Op0 = I.getOperand(0);
2683 const Value *Op1 = I.getOperand(1);
2684 const Type *AggTy = I.getType();
2685 const Type *ValTy = Op1->getType();
2686 bool IntoUndef = isa<UndefValue>(Op0);
2687 bool FromUndef = isa<UndefValue>(Op1);
2689 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2690 I.idx_begin(), I.idx_end());
2692 SmallVector<EVT, 4> AggValueVTs;
2693 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2694 SmallVector<EVT, 4> ValValueVTs;
2695 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2697 unsigned NumAggValues = AggValueVTs.size();
2698 unsigned NumValValues = ValValueVTs.size();
2699 SmallVector<SDValue, 4> Values(NumAggValues);
2701 SDValue Agg = getValue(Op0);
2702 SDValue Val = getValue(Op1);
2704 // Copy the beginning value(s) from the original aggregate.
2705 for (; i != LinearIndex; ++i)
2706 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2707 SDValue(Agg.getNode(), Agg.getResNo() + i);
2708 // Copy values from the inserted value(s).
2709 for (; i != LinearIndex + NumValValues; ++i)
2710 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2711 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2712 // Copy remaining value(s) from the original aggregate.
2713 for (; i != NumAggValues; ++i)
2714 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2715 SDValue(Agg.getNode(), Agg.getResNo() + i);
2717 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2718 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2719 &Values[0], NumAggValues);
2722 if (DisableScheduling)
2723 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2726 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2727 const Value *Op0 = I.getOperand(0);
2728 const Type *AggTy = Op0->getType();
2729 const Type *ValTy = I.getType();
2730 bool OutOfUndef = isa<UndefValue>(Op0);
2732 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2733 I.idx_begin(), I.idx_end());
2735 SmallVector<EVT, 4> ValValueVTs;
2736 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2738 unsigned NumValValues = ValValueVTs.size();
2739 SmallVector<SDValue, 4> Values(NumValValues);
2741 SDValue Agg = getValue(Op0);
2742 // Copy out the selected value(s).
2743 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2744 Values[i - LinearIndex] =
2746 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2747 SDValue(Agg.getNode(), Agg.getResNo() + i);
2749 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2750 DAG.getVTList(&ValValueVTs[0], NumValValues),
2751 &Values[0], NumValValues);
2754 if (DisableScheduling)
2755 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2758 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2759 SDValue N = getValue(I.getOperand(0));
2760 const Type *Ty = I.getOperand(0)->getType();
2762 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2765 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2766 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2769 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2770 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2771 DAG.getIntPtrConstant(Offset));
2773 if (DisableScheduling)
2774 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2777 Ty = StTy->getElementType(Field);
2779 Ty = cast<SequentialType>(Ty)->getElementType();
2781 // If this is a constant subscript, handle it quickly.
2782 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2783 if (CI->getZExtValue() == 0) continue;
2785 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2787 EVT PTy = TLI.getPointerTy();
2788 unsigned PtrBits = PTy.getSizeInBits();
2790 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2792 DAG.getConstant(Offs, MVT::i64));
2794 OffsVal = DAG.getIntPtrConstant(Offs);
2796 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2799 if (DisableScheduling) {
2800 DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder);
2801 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2807 // N = N + Idx * ElementSize;
2808 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2809 TD->getTypeAllocSize(Ty));
2810 SDValue IdxN = getValue(Idx);
2812 // If the index is smaller or larger than intptr_t, truncate or extend
2814 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2816 // If this is a multiply by a power of two, turn it into a shl
2817 // immediately. This is a very common case.
2818 if (ElementSize != 1) {
2819 if (ElementSize.isPowerOf2()) {
2820 unsigned Amt = ElementSize.logBase2();
2821 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2822 N.getValueType(), IdxN,
2823 DAG.getConstant(Amt, TLI.getPointerTy()));
2825 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2826 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2827 N.getValueType(), IdxN, Scale);
2830 if (DisableScheduling)
2831 DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder);
2834 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2835 N.getValueType(), N, IdxN);
2837 if (DisableScheduling)
2838 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2845 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2846 // If this is a fixed sized alloca in the entry block of the function,
2847 // allocate it statically on the stack.
2848 if (FuncInfo.StaticAllocaMap.count(&I))
2849 return; // getValue will auto-populate this.
2851 const Type *Ty = I.getAllocatedType();
2852 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2854 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2857 SDValue AllocSize = getValue(I.getArraySize());
2859 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2861 DAG.getConstant(TySize, AllocSize.getValueType()));
2863 if (DisableScheduling)
2864 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2866 EVT IntPtr = TLI.getPointerTy();
2867 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2869 if (DisableScheduling)
2870 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2872 // Handle alignment. If the requested alignment is less than or equal to
2873 // the stack alignment, ignore it. If the size is greater than or equal to
2874 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2875 unsigned StackAlign =
2876 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2877 if (Align <= StackAlign)
2880 // Round the size of the allocation up to the stack alignment size
2881 // by add SA-1 to the size.
2882 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2883 AllocSize.getValueType(), AllocSize,
2884 DAG.getIntPtrConstant(StackAlign-1));
2885 if (DisableScheduling)
2886 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2888 // Mask out the low bits for alignment purposes.
2889 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2890 AllocSize.getValueType(), AllocSize,
2891 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2892 if (DisableScheduling)
2893 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2895 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2896 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2897 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2900 DAG.setRoot(DSA.getValue(1));
2902 if (DisableScheduling)
2903 DAG.AssignOrdering(DSA.getNode(), SDNodeOrder);
2905 // Inform the Frame Information that we have just allocated a variable-sized
2907 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2910 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2911 const Value *SV = I.getOperand(0);
2912 SDValue Ptr = getValue(SV);
2914 const Type *Ty = I.getType();
2915 bool isVolatile = I.isVolatile();
2916 unsigned Alignment = I.getAlignment();
2918 SmallVector<EVT, 4> ValueVTs;
2919 SmallVector<uint64_t, 4> Offsets;
2920 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2921 unsigned NumValues = ValueVTs.size();
2926 bool ConstantMemory = false;
2928 // Serialize volatile loads with other side effects.
2930 else if (AA->pointsToConstantMemory(SV)) {
2931 // Do not serialize (non-volatile) loads of constant memory with anything.
2932 Root = DAG.getEntryNode();
2933 ConstantMemory = true;
2935 // Do not serialize non-volatile loads against each other.
2936 Root = DAG.getRoot();
2939 SmallVector<SDValue, 4> Values(NumValues);
2940 SmallVector<SDValue, 4> Chains(NumValues);
2941 EVT PtrVT = Ptr.getValueType();
2942 for (unsigned i = 0; i != NumValues; ++i) {
2943 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2945 DAG.getConstant(Offsets[i], PtrVT));
2946 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2947 A, SV, Offsets[i], isVolatile, Alignment);
2950 Chains[i] = L.getValue(1);
2952 if (DisableScheduling) {
2953 DAG.AssignOrdering(A.getNode(), SDNodeOrder);
2954 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
2958 if (!ConstantMemory) {
2959 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2960 MVT::Other, &Chains[0], NumValues);
2964 PendingLoads.push_back(Chain);
2966 if (DisableScheduling)
2967 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
2970 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2971 DAG.getVTList(&ValueVTs[0], NumValues),
2972 &Values[0], NumValues);
2975 if (DisableScheduling)
2976 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2979 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2980 Value *SrcV = I.getOperand(0);
2981 Value *PtrV = I.getOperand(1);
2983 SmallVector<EVT, 4> ValueVTs;
2984 SmallVector<uint64_t, 4> Offsets;
2985 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2986 unsigned NumValues = ValueVTs.size();
2990 // Get the lowered operands. Note that we do this after
2991 // checking if NumResults is zero, because with zero results
2992 // the operands won't have values in the map.
2993 SDValue Src = getValue(SrcV);
2994 SDValue Ptr = getValue(PtrV);
2996 SDValue Root = getRoot();
2997 SmallVector<SDValue, 4> Chains(NumValues);
2998 EVT PtrVT = Ptr.getValueType();
2999 bool isVolatile = I.isVolatile();
3000 unsigned Alignment = I.getAlignment();
3002 for (unsigned i = 0; i != NumValues; ++i) {
3003 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3004 DAG.getConstant(Offsets[i], PtrVT));
3005 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
3006 SDValue(Src.getNode(), Src.getResNo() + i),
3007 Add, PtrV, Offsets[i], isVolatile, Alignment);
3009 if (DisableScheduling) {
3010 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
3011 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
3015 SDValue Res = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3016 MVT::Other, &Chains[0], NumValues);
3019 if (DisableScheduling)
3020 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3023 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3025 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
3026 unsigned Intrinsic) {
3027 bool HasChain = !I.doesNotAccessMemory();
3028 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3030 // Build the operand list.
3031 SmallVector<SDValue, 8> Ops;
3032 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3034 // We don't need to serialize loads against other loads.
3035 Ops.push_back(DAG.getRoot());
3037 Ops.push_back(getRoot());
3041 // Info is set by getTgtMemInstrinsic
3042 TargetLowering::IntrinsicInfo Info;
3043 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3045 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3046 if (!IsTgtIntrinsic)
3047 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3049 // Add all operands of the call to the operand list.
3050 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3051 SDValue Op = getValue(I.getOperand(i));
3052 assert(TLI.isTypeLegal(Op.getValueType()) &&
3053 "Intrinsic uses a non-legal type?");
3057 SmallVector<EVT, 4> ValueVTs;
3058 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3060 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3061 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3062 "Intrinsic uses a non-legal type?");
3067 ValueVTs.push_back(MVT::Other);
3069 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3073 if (IsTgtIntrinsic) {
3074 // This is target intrinsic that touches memory
3075 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3076 VTs, &Ops[0], Ops.size(),
3077 Info.memVT, Info.ptrVal, Info.offset,
3078 Info.align, Info.vol,
3079 Info.readMem, Info.writeMem);
3080 } else if (!HasChain) {
3081 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3082 VTs, &Ops[0], Ops.size());
3083 } else if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3084 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3085 VTs, &Ops[0], Ops.size());
3087 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3088 VTs, &Ops[0], Ops.size());
3091 if (DisableScheduling)
3092 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3095 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3097 PendingLoads.push_back(Chain);
3102 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3103 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3104 EVT VT = TLI.getValueType(PTy);
3105 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3107 if (DisableScheduling)
3108 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3111 setValue(&I, Result);
3115 /// GetSignificand - Get the significand and build it into a floating-point
3116 /// number with exponent of 1:
3118 /// Op = (Op & 0x007fffff) | 0x3f800000;
3120 /// where Op is the hexidecimal representation of floating point value.
3122 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
3123 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3124 DAG.getConstant(0x007fffff, MVT::i32));
3125 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3126 DAG.getConstant(0x3f800000, MVT::i32));
3127 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3129 if (DisableScheduling) {
3130 DAG.AssignOrdering(t1.getNode(), Order);
3131 DAG.AssignOrdering(t2.getNode(), Order);
3132 DAG.AssignOrdering(Res.getNode(), Order);
3138 /// GetExponent - Get the exponent:
3140 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3142 /// where Op is the hexidecimal representation of floating point value.
3144 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3145 DebugLoc dl, unsigned Order) {
3146 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3147 DAG.getConstant(0x7f800000, MVT::i32));
3148 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3149 DAG.getConstant(23, TLI.getPointerTy()));
3150 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3151 DAG.getConstant(127, MVT::i32));
3152 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3154 if (DisableScheduling) {
3155 DAG.AssignOrdering(t0.getNode(), Order);
3156 DAG.AssignOrdering(t1.getNode(), Order);
3157 DAG.AssignOrdering(t2.getNode(), Order);
3158 DAG.AssignOrdering(Res.getNode(), Order);
3164 /// getF32Constant - Get 32-bit floating point constant.
3166 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3167 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3170 /// Inlined utility function to implement binary input atomic intrinsics for
3171 /// visitIntrinsicCall: I is a call instruction
3172 /// Op is the associated NodeType for I
3174 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3175 SDValue Root = getRoot();
3177 DAG.getAtomic(Op, getCurDebugLoc(),
3178 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3180 getValue(I.getOperand(1)),
3181 getValue(I.getOperand(2)),
3184 DAG.setRoot(L.getValue(1));
3186 if (DisableScheduling)
3187 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3192 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3194 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3195 SDValue Op1 = getValue(I.getOperand(1));
3196 SDValue Op2 = getValue(I.getOperand(2));
3198 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3199 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3201 setValue(&I, Result);
3203 if (DisableScheduling)
3204 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3209 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3210 /// limited-precision mode.
3212 SelectionDAGBuilder::visitExp(CallInst &I) {
3214 DebugLoc dl = getCurDebugLoc();
3216 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3217 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3218 SDValue Op = getValue(I.getOperand(1));
3220 // Put the exponent in the right bit position for later addition to the
3223 // #define LOG2OFe 1.4426950f
3224 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3225 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3226 getF32Constant(DAG, 0x3fb8aa3b));
3227 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3229 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3230 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3231 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3233 if (DisableScheduling) {
3234 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3235 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3236 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3237 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3240 // IntegerPartOfX <<= 23;
3241 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3242 DAG.getConstant(23, TLI.getPointerTy()));
3244 if (DisableScheduling)
3245 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3247 if (LimitFloatPrecision <= 6) {
3248 // For floating-point precision of 6:
3250 // TwoToFractionalPartOfX =
3252 // (0.735607626f + 0.252464424f * x) * x;
3254 // error 0.0144103317, which is 6 bits
3255 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3256 getF32Constant(DAG, 0x3e814304));
3257 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3258 getF32Constant(DAG, 0x3f3c50c8));
3259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3260 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3261 getF32Constant(DAG, 0x3f7f5e7e));
3262 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3264 // Add the exponent into the result in integer domain.
3265 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3266 TwoToFracPartOfX, IntegerPartOfX);
3268 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3270 if (DisableScheduling) {
3271 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3272 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3273 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3274 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3275 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3276 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3277 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3279 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3280 // For floating-point precision of 12:
3282 // TwoToFractionalPartOfX =
3285 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3287 // 0.000107046256 error, which is 13 to 14 bits
3288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3289 getF32Constant(DAG, 0x3da235e3));
3290 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3291 getF32Constant(DAG, 0x3e65b8f3));
3292 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3293 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3294 getF32Constant(DAG, 0x3f324b07));
3295 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3296 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3297 getF32Constant(DAG, 0x3f7ff8fd));
3298 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3300 // Add the exponent into the result in integer domain.
3301 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3302 TwoToFracPartOfX, IntegerPartOfX);
3304 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3306 if (DisableScheduling) {
3307 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3308 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3309 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3310 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3311 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3312 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3313 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3314 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3315 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3317 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3318 // For floating-point precision of 18:
3320 // TwoToFractionalPartOfX =
3324 // (0.554906021e-1f +
3325 // (0.961591928e-2f +
3326 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3328 // error 2.47208000*10^(-7), which is better than 18 bits
3329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3330 getF32Constant(DAG, 0x3924b03e));
3331 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3332 getF32Constant(DAG, 0x3ab24b87));
3333 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3334 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3335 getF32Constant(DAG, 0x3c1d8c17));
3336 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3337 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3338 getF32Constant(DAG, 0x3d634a1d));
3339 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3340 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3341 getF32Constant(DAG, 0x3e75fe14));
3342 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3343 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3344 getF32Constant(DAG, 0x3f317234));
3345 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3346 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3347 getF32Constant(DAG, 0x3f800000));
3348 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3351 // Add the exponent into the result in integer domain.
3352 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3353 TwoToFracPartOfX, IntegerPartOfX);
3355 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3357 if (DisableScheduling) {
3358 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3359 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3360 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3361 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3362 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3363 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3364 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3365 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3366 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3367 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3368 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3369 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3370 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3371 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3372 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3376 // No special expansion.
3377 result = DAG.getNode(ISD::FEXP, dl,
3378 getValue(I.getOperand(1)).getValueType(),
3379 getValue(I.getOperand(1)));
3380 if (DisableScheduling)
3381 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3384 setValue(&I, result);
3387 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3388 /// limited-precision mode.
3390 SelectionDAGBuilder::visitLog(CallInst &I) {
3392 DebugLoc dl = getCurDebugLoc();
3394 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3395 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3396 SDValue Op = getValue(I.getOperand(1));
3397 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3399 if (DisableScheduling)
3400 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3402 // Scale the exponent by log(2) [0.69314718f].
3403 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3404 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3405 getF32Constant(DAG, 0x3f317218));
3407 if (DisableScheduling)
3408 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3410 // Get the significand and build it into a floating-point number with
3412 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3414 if (LimitFloatPrecision <= 6) {
3415 // For floating-point precision of 6:
3419 // (1.4034025f - 0.23903021f * x) * x;
3421 // error 0.0034276066, which is better than 8 bits
3422 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3423 getF32Constant(DAG, 0xbe74c456));
3424 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3425 getF32Constant(DAG, 0x3fb3a2b1));
3426 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3427 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3428 getF32Constant(DAG, 0x3f949a29));
3430 result = DAG.getNode(ISD::FADD, dl,
3431 MVT::f32, LogOfExponent, LogOfMantissa);
3433 if (DisableScheduling) {
3434 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3435 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3436 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3437 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3438 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3440 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3441 // For floating-point precision of 12:
3447 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3449 // error 0.000061011436, which is 14 bits
3450 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3451 getF32Constant(DAG, 0xbd67b6d6));
3452 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3453 getF32Constant(DAG, 0x3ee4f4b8));
3454 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3455 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3456 getF32Constant(DAG, 0x3fbc278b));
3457 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3458 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3459 getF32Constant(DAG, 0x40348e95));
3460 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3461 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3462 getF32Constant(DAG, 0x3fdef31a));
3464 result = DAG.getNode(ISD::FADD, dl,
3465 MVT::f32, LogOfExponent, LogOfMantissa);
3467 if (DisableScheduling) {
3468 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3469 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3470 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3471 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3472 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3473 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3474 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3475 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3476 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3478 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3479 // For floating-point precision of 18:
3487 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3489 // error 0.0000023660568, which is better than 18 bits
3490 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3491 getF32Constant(DAG, 0xbc91e5ac));
3492 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3493 getF32Constant(DAG, 0x3e4350aa));
3494 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3495 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3496 getF32Constant(DAG, 0x3f60d3e3));
3497 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3498 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3499 getF32Constant(DAG, 0x4011cdf0));
3500 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3501 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3502 getF32Constant(DAG, 0x406cfd1c));
3503 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3504 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3505 getF32Constant(DAG, 0x408797cb));
3506 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3507 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3508 getF32Constant(DAG, 0x4006dcab));
3510 result = DAG.getNode(ISD::FADD, dl,
3511 MVT::f32, LogOfExponent, LogOfMantissa);
3513 if (DisableScheduling) {
3514 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3515 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3516 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3517 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3518 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3519 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3520 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3521 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3522 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3523 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3524 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3525 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3526 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3530 // No special expansion.
3531 result = DAG.getNode(ISD::FLOG, dl,
3532 getValue(I.getOperand(1)).getValueType(),
3533 getValue(I.getOperand(1)));
3535 if (DisableScheduling)
3536 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3539 setValue(&I, result);
3542 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3543 /// limited-precision mode.
3545 SelectionDAGBuilder::visitLog2(CallInst &I) {
3547 DebugLoc dl = getCurDebugLoc();
3549 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3550 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3551 SDValue Op = getValue(I.getOperand(1));
3552 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3554 if (DisableScheduling)
3555 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3557 // Get the exponent.
3558 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3560 if (DisableScheduling)
3561 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3563 // Get the significand and build it into a floating-point number with
3565 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3567 // Different possible minimax approximations of significand in
3568 // floating-point for various degrees of accuracy over [1,2].
3569 if (LimitFloatPrecision <= 6) {
3570 // For floating-point precision of 6:
3572 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3574 // error 0.0049451742, which is more than 7 bits
3575 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3576 getF32Constant(DAG, 0xbeb08fe0));
3577 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3578 getF32Constant(DAG, 0x40019463));
3579 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3580 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3581 getF32Constant(DAG, 0x3fd6633d));
3583 result = DAG.getNode(ISD::FADD, dl,
3584 MVT::f32, LogOfExponent, Log2ofMantissa);
3586 if (DisableScheduling) {
3587 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3588 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3589 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3590 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3591 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3593 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3594 // For floating-point precision of 12:
3600 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3602 // error 0.0000876136000, which is better than 13 bits
3603 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3604 getF32Constant(DAG, 0xbda7262e));
3605 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3606 getF32Constant(DAG, 0x3f25280b));
3607 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3608 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3609 getF32Constant(DAG, 0x4007b923));
3610 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3611 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3612 getF32Constant(DAG, 0x40823e2f));
3613 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3614 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3615 getF32Constant(DAG, 0x4020d29c));
3617 result = DAG.getNode(ISD::FADD, dl,
3618 MVT::f32, LogOfExponent, Log2ofMantissa);
3620 if (DisableScheduling) {
3621 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3622 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3623 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3624 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3625 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3626 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3627 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3628 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3629 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3631 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3632 // For floating-point precision of 18:
3641 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3643 // error 0.0000018516, which is better than 18 bits
3644 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3645 getF32Constant(DAG, 0xbcd2769e));
3646 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3647 getF32Constant(DAG, 0x3e8ce0b9));
3648 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3649 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3650 getF32Constant(DAG, 0x3fa22ae7));
3651 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3652 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3653 getF32Constant(DAG, 0x40525723));
3654 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3655 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3656 getF32Constant(DAG, 0x40aaf200));
3657 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3658 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3659 getF32Constant(DAG, 0x40c39dad));
3660 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3661 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3662 getF32Constant(DAG, 0x4042902c));
3664 result = DAG.getNode(ISD::FADD, dl,
3665 MVT::f32, LogOfExponent, Log2ofMantissa);
3667 if (DisableScheduling) {
3668 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3669 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3670 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3671 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3672 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3673 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3674 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3675 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3676 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3677 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3678 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3679 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3680 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3684 // No special expansion.
3685 result = DAG.getNode(ISD::FLOG2, dl,
3686 getValue(I.getOperand(1)).getValueType(),
3687 getValue(I.getOperand(1)));
3689 if (DisableScheduling)
3690 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3693 setValue(&I, result);
3696 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3697 /// limited-precision mode.
3699 SelectionDAGBuilder::visitLog10(CallInst &I) {
3701 DebugLoc dl = getCurDebugLoc();
3703 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3704 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3705 SDValue Op = getValue(I.getOperand(1));
3706 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3708 if (DisableScheduling)
3709 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3711 // Scale the exponent by log10(2) [0.30102999f].
3712 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3713 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3714 getF32Constant(DAG, 0x3e9a209a));
3716 if (DisableScheduling)
3717 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3719 // Get the significand and build it into a floating-point number with
3721 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3723 if (LimitFloatPrecision <= 6) {
3724 // For floating-point precision of 6:
3726 // Log10ofMantissa =
3728 // (0.60948995f - 0.10380950f * x) * x;
3730 // error 0.0014886165, which is 6 bits
3731 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3732 getF32Constant(DAG, 0xbdd49a13));
3733 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3734 getF32Constant(DAG, 0x3f1c0789));
3735 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3736 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3737 getF32Constant(DAG, 0x3f011300));
3739 result = DAG.getNode(ISD::FADD, dl,
3740 MVT::f32, LogOfExponent, Log10ofMantissa);
3742 if (DisableScheduling) {
3743 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3744 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3745 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3746 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3747 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3749 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3750 // For floating-point precision of 12:
3752 // Log10ofMantissa =
3755 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3757 // error 0.00019228036, which is better than 12 bits
3758 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3759 getF32Constant(DAG, 0x3d431f31));
3760 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3761 getF32Constant(DAG, 0x3ea21fb2));
3762 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3763 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3764 getF32Constant(DAG, 0x3f6ae232));
3765 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3766 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3767 getF32Constant(DAG, 0x3f25f7c3));
3769 result = DAG.getNode(ISD::FADD, dl,
3770 MVT::f32, LogOfExponent, Log10ofMantissa);
3772 if (DisableScheduling) {
3773 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3774 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3775 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3776 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3777 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3778 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3779 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3781 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3782 // For floating-point precision of 18:
3784 // Log10ofMantissa =
3789 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3791 // error 0.0000037995730, which is better than 18 bits
3792 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3793 getF32Constant(DAG, 0x3c5d51ce));
3794 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3795 getF32Constant(DAG, 0x3e00685a));
3796 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3797 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3798 getF32Constant(DAG, 0x3efb6798));
3799 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3800 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3801 getF32Constant(DAG, 0x3f88d192));
3802 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3803 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3804 getF32Constant(DAG, 0x3fc4316c));
3805 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3806 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3807 getF32Constant(DAG, 0x3f57ce70));
3809 result = DAG.getNode(ISD::FADD, dl,
3810 MVT::f32, LogOfExponent, Log10ofMantissa);
3812 if (DisableScheduling) {
3813 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3814 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3815 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3816 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3817 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3818 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3819 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3820 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3821 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3822 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3823 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3827 // No special expansion.
3828 result = DAG.getNode(ISD::FLOG10, dl,
3829 getValue(I.getOperand(1)).getValueType(),
3830 getValue(I.getOperand(1)));
3832 if (DisableScheduling)
3833 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3836 setValue(&I, result);
3839 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3840 /// limited-precision mode.
3842 SelectionDAGBuilder::visitExp2(CallInst &I) {
3844 DebugLoc dl = getCurDebugLoc();
3846 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3847 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3848 SDValue Op = getValue(I.getOperand(1));
3850 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3852 if (DisableScheduling)
3853 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3855 // FractionalPartOfX = x - (float)IntegerPartOfX;
3856 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3857 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3859 // IntegerPartOfX <<= 23;
3860 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3861 DAG.getConstant(23, TLI.getPointerTy()));
3863 if (DisableScheduling) {
3864 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3865 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3866 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3869 if (LimitFloatPrecision <= 6) {
3870 // For floating-point precision of 6:
3872 // TwoToFractionalPartOfX =
3874 // (0.735607626f + 0.252464424f * x) * x;
3876 // error 0.0144103317, which is 6 bits
3877 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3878 getF32Constant(DAG, 0x3e814304));
3879 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3880 getF32Constant(DAG, 0x3f3c50c8));
3881 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3882 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3883 getF32Constant(DAG, 0x3f7f5e7e));
3884 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3885 SDValue TwoToFractionalPartOfX =
3886 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3888 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3889 MVT::f32, TwoToFractionalPartOfX);
3891 if (DisableScheduling) {
3892 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3893 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3894 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3895 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3896 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3897 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3898 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3900 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3901 // For floating-point precision of 12:
3903 // TwoToFractionalPartOfX =
3906 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3908 // error 0.000107046256, which is 13 to 14 bits
3909 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3910 getF32Constant(DAG, 0x3da235e3));
3911 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3912 getF32Constant(DAG, 0x3e65b8f3));
3913 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3914 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3915 getF32Constant(DAG, 0x3f324b07));
3916 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3917 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3918 getF32Constant(DAG, 0x3f7ff8fd));
3919 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3920 SDValue TwoToFractionalPartOfX =
3921 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3923 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3924 MVT::f32, TwoToFractionalPartOfX);
3926 if (DisableScheduling) {
3927 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3928 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3929 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3930 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3931 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3932 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3933 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3934 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3935 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3937 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3938 // For floating-point precision of 18:
3940 // TwoToFractionalPartOfX =
3944 // (0.554906021e-1f +
3945 // (0.961591928e-2f +
3946 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3947 // error 2.47208000*10^(-7), which is better than 18 bits
3948 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3949 getF32Constant(DAG, 0x3924b03e));
3950 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3951 getF32Constant(DAG, 0x3ab24b87));
3952 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3953 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3954 getF32Constant(DAG, 0x3c1d8c17));
3955 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3956 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3957 getF32Constant(DAG, 0x3d634a1d));
3958 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3959 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3960 getF32Constant(DAG, 0x3e75fe14));
3961 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3962 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3963 getF32Constant(DAG, 0x3f317234));
3964 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3965 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3966 getF32Constant(DAG, 0x3f800000));
3967 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3968 SDValue TwoToFractionalPartOfX =
3969 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3971 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3972 MVT::f32, TwoToFractionalPartOfX);
3974 if (DisableScheduling) {
3975 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3976 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3977 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3978 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3979 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3980 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3981 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3982 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3983 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3984 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3985 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3986 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3987 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3988 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3989 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3993 // No special expansion.
3994 result = DAG.getNode(ISD::FEXP2, dl,
3995 getValue(I.getOperand(1)).getValueType(),
3996 getValue(I.getOperand(1)));
3998 if (DisableScheduling)
3999 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4002 setValue(&I, result);
4005 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4006 /// limited-precision mode with x == 10.0f.
4008 SelectionDAGBuilder::visitPow(CallInst &I) {
4010 Value *Val = I.getOperand(1);
4011 DebugLoc dl = getCurDebugLoc();
4012 bool IsExp10 = false;
4014 if (getValue(Val).getValueType() == MVT::f32 &&
4015 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
4016 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4017 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4018 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4020 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4025 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4026 SDValue Op = getValue(I.getOperand(2));
4028 // Put the exponent in the right bit position for later addition to the
4031 // #define LOG2OF10 3.3219281f
4032 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4033 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4034 getF32Constant(DAG, 0x40549a78));
4035 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4037 // FractionalPartOfX = x - (float)IntegerPartOfX;
4038 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4039 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4041 if (DisableScheduling) {
4042 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
4043 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
4044 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4045 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
4048 // IntegerPartOfX <<= 23;
4049 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4050 DAG.getConstant(23, TLI.getPointerTy()));
4052 if (DisableScheduling)
4053 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4055 if (LimitFloatPrecision <= 6) {
4056 // For floating-point precision of 6:
4058 // twoToFractionalPartOfX =
4060 // (0.735607626f + 0.252464424f * x) * x;
4062 // error 0.0144103317, which is 6 bits
4063 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4064 getF32Constant(DAG, 0x3e814304));
4065 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4066 getF32Constant(DAG, 0x3f3c50c8));
4067 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4068 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4069 getF32Constant(DAG, 0x3f7f5e7e));
4070 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
4071 SDValue TwoToFractionalPartOfX =
4072 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4074 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4075 MVT::f32, TwoToFractionalPartOfX);
4077 if (DisableScheduling) {
4078 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4079 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4080 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4081 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4082 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4083 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4084 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4086 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4087 // For floating-point precision of 12:
4089 // TwoToFractionalPartOfX =
4092 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4094 // error 0.000107046256, which is 13 to 14 bits
4095 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4096 getF32Constant(DAG, 0x3da235e3));
4097 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4098 getF32Constant(DAG, 0x3e65b8f3));
4099 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4100 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4101 getF32Constant(DAG, 0x3f324b07));
4102 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4103 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4104 getF32Constant(DAG, 0x3f7ff8fd));
4105 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
4106 SDValue TwoToFractionalPartOfX =
4107 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4109 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4110 MVT::f32, TwoToFractionalPartOfX);
4112 if (DisableScheduling) {
4113 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4114 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4115 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4116 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4117 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4118 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4119 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4120 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4121 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4123 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4124 // For floating-point precision of 18:
4126 // TwoToFractionalPartOfX =
4130 // (0.554906021e-1f +
4131 // (0.961591928e-2f +
4132 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4133 // error 2.47208000*10^(-7), which is better than 18 bits
4134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4135 getF32Constant(DAG, 0x3924b03e));
4136 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4137 getF32Constant(DAG, 0x3ab24b87));
4138 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4139 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4140 getF32Constant(DAG, 0x3c1d8c17));
4141 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4142 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4143 getF32Constant(DAG, 0x3d634a1d));
4144 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4145 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4146 getF32Constant(DAG, 0x3e75fe14));
4147 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4148 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4149 getF32Constant(DAG, 0x3f317234));
4150 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4151 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4152 getF32Constant(DAG, 0x3f800000));
4153 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4154 SDValue TwoToFractionalPartOfX =
4155 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4157 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4158 MVT::f32, TwoToFractionalPartOfX);
4160 if (DisableScheduling) {
4161 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4162 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4163 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4164 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4165 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4166 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4167 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4168 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4169 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4170 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4171 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4172 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4173 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4174 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4175 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4179 // No special expansion.
4180 result = DAG.getNode(ISD::FPOW, dl,
4181 getValue(I.getOperand(1)).getValueType(),
4182 getValue(I.getOperand(1)),
4183 getValue(I.getOperand(2)));
4185 if (DisableScheduling)
4186 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4189 setValue(&I, result);
4192 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4193 /// we want to emit this as a call to a named external function, return the name
4194 /// otherwise lower it and return null.
4196 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
4197 DebugLoc dl = getCurDebugLoc();
4200 switch (Intrinsic) {
4202 // By default, turn this into a target intrinsic node.
4203 visitTargetIntrinsic(I, Intrinsic);
4205 case Intrinsic::vastart: visitVAStart(I); return 0;
4206 case Intrinsic::vaend: visitVAEnd(I); return 0;
4207 case Intrinsic::vacopy: visitVACopy(I); return 0;
4208 case Intrinsic::returnaddress:
4209 Res = DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4210 getValue(I.getOperand(1)));
4212 if (DisableScheduling)
4213 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4215 case Intrinsic::frameaddress:
4216 Res = DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4217 getValue(I.getOperand(1)));
4219 if (DisableScheduling)
4220 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4222 case Intrinsic::setjmp:
4223 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4224 case Intrinsic::longjmp:
4225 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4226 case Intrinsic::memcpy: {
4227 SDValue Op1 = getValue(I.getOperand(1));
4228 SDValue Op2 = getValue(I.getOperand(2));
4229 SDValue Op3 = getValue(I.getOperand(3));
4230 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4231 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4232 I.getOperand(1), 0, I.getOperand(2), 0);
4234 if (DisableScheduling)
4235 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4238 case Intrinsic::memset: {
4239 SDValue Op1 = getValue(I.getOperand(1));
4240 SDValue Op2 = getValue(I.getOperand(2));
4241 SDValue Op3 = getValue(I.getOperand(3));
4242 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4243 Res = DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
4244 I.getOperand(1), 0);
4246 if (DisableScheduling)
4247 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4250 case Intrinsic::memmove: {
4251 SDValue Op1 = getValue(I.getOperand(1));
4252 SDValue Op2 = getValue(I.getOperand(2));
4253 SDValue Op3 = getValue(I.getOperand(3));
4254 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4256 // If the source and destination are known to not be aliases, we can
4257 // lower memmove as memcpy.
4258 uint64_t Size = -1ULL;
4259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4260 Size = C->getZExtValue();
4261 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4262 AliasAnalysis::NoAlias) {
4263 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4264 I.getOperand(1), 0, I.getOperand(2), 0);
4266 if (DisableScheduling)
4267 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4271 Res = DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
4272 I.getOperand(1), 0, I.getOperand(2), 0);
4274 if (DisableScheduling)
4275 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4278 case Intrinsic::dbg_stoppoint:
4279 case Intrinsic::dbg_region_start:
4280 case Intrinsic::dbg_region_end:
4281 case Intrinsic::dbg_func_start:
4282 // FIXME - Remove this instructions once the dust settles.
4284 case Intrinsic::dbg_declare: {
4285 if (OptLevel != CodeGenOpt::None)
4286 // FIXME: Variable debug info is not supported here.
4288 DwarfWriter *DW = DAG.getDwarfWriter();
4291 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4292 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
4295 MDNode *Variable = DI.getVariable();
4296 Value *Address = DI.getAddress();
4297 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4298 Address = BCI->getOperand(0);
4299 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4300 // Don't handle byval struct arguments or VLAs, for example.
4303 DenseMap<const AllocaInst*, int>::iterator SI =
4304 FuncInfo.StaticAllocaMap.find(AI);
4305 if (SI == FuncInfo.StaticAllocaMap.end())
4307 int FI = SI->second;
4309 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4311 MetadataContext &TheMetadata =
4312 DI.getParent()->getContext().getMetadata();
4313 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
4314 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
4315 MMI->setVariableDbgInfo(Variable, FI, Dbg);
4319 case Intrinsic::eh_exception: {
4320 // Insert the EXCEPTIONADDR instruction.
4321 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
4322 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4324 Ops[0] = DAG.getRoot();
4325 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4327 DAG.setRoot(Op.getValue(1));
4328 if (DisableScheduling)
4329 DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4333 case Intrinsic::eh_selector: {
4334 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4336 if (CurMBB->isLandingPad())
4337 AddCatchInfo(I, MMI, CurMBB);
4340 FuncInfo.CatchInfoLost.insert(&I);
4342 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4343 unsigned Reg = TLI.getExceptionSelectorRegister();
4344 if (Reg) CurMBB->addLiveIn(Reg);
4347 // Insert the EHSELECTION instruction.
4348 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4350 Ops[0] = getValue(I.getOperand(1));
4352 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4354 DAG.setRoot(Op.getValue(1));
4356 Res = DAG.getSExtOrTrunc(Op, dl, MVT::i32);
4358 if (DisableScheduling) {
4359 DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4360 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4365 case Intrinsic::eh_typeid_for: {
4366 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4369 // Find the type id for the given typeinfo.
4370 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4371 unsigned TypeID = MMI->getTypeIDFor(GV);
4372 Res = DAG.getConstant(TypeID, MVT::i32);
4374 // Return something different to eh_selector.
4375 Res = DAG.getConstant(1, MVT::i32);
4379 if (DisableScheduling)
4380 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4384 case Intrinsic::eh_return_i32:
4385 case Intrinsic::eh_return_i64:
4386 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4387 MMI->setCallsEHReturn(true);
4388 Res = DAG.getNode(ISD::EH_RETURN, dl,
4391 getValue(I.getOperand(1)),
4392 getValue(I.getOperand(2)));
4394 if (DisableScheduling)
4395 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4397 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4401 case Intrinsic::eh_unwind_init:
4402 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4403 MMI->setCallsUnwindInit(true);
4406 case Intrinsic::eh_dwarf_cfa: {
4407 EVT VT = getValue(I.getOperand(1)).getValueType();
4408 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4409 TLI.getPointerTy());
4410 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4412 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4413 TLI.getPointerTy()),
4415 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4417 DAG.getConstant(0, TLI.getPointerTy()));
4418 Res = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4421 if (DisableScheduling) {
4422 DAG.AssignOrdering(CfaArg.getNode(), SDNodeOrder);
4423 DAG.AssignOrdering(Offset.getNode(), SDNodeOrder);
4424 DAG.AssignOrdering(FA.getNode(), SDNodeOrder);
4425 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4429 case Intrinsic::convertff:
4430 case Intrinsic::convertfsi:
4431 case Intrinsic::convertfui:
4432 case Intrinsic::convertsif:
4433 case Intrinsic::convertuif:
4434 case Intrinsic::convertss:
4435 case Intrinsic::convertsu:
4436 case Intrinsic::convertus:
4437 case Intrinsic::convertuu: {
4438 ISD::CvtCode Code = ISD::CVT_INVALID;
4439 switch (Intrinsic) {
4440 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4441 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4442 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4443 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4444 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4445 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4446 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4447 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4448 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4450 EVT DestVT = TLI.getValueType(I.getType());
4451 Value *Op1 = I.getOperand(1);
4452 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4453 DAG.getValueType(DestVT),
4454 DAG.getValueType(getValue(Op1).getValueType()),
4455 getValue(I.getOperand(2)),
4456 getValue(I.getOperand(3)),
4459 if (DisableScheduling)
4460 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4463 case Intrinsic::sqrt:
4464 Res = DAG.getNode(ISD::FSQRT, dl,
4465 getValue(I.getOperand(1)).getValueType(),
4466 getValue(I.getOperand(1)));
4468 if (DisableScheduling)
4469 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4471 case Intrinsic::powi:
4472 Res = DAG.getNode(ISD::FPOWI, dl,
4473 getValue(I.getOperand(1)).getValueType(),
4474 getValue(I.getOperand(1)),
4475 getValue(I.getOperand(2)));
4477 if (DisableScheduling)
4478 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4480 case Intrinsic::sin:
4481 Res = DAG.getNode(ISD::FSIN, dl,
4482 getValue(I.getOperand(1)).getValueType(),
4483 getValue(I.getOperand(1)));
4485 if (DisableScheduling)
4486 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4488 case Intrinsic::cos:
4489 Res = DAG.getNode(ISD::FCOS, dl,
4490 getValue(I.getOperand(1)).getValueType(),
4491 getValue(I.getOperand(1)));
4493 if (DisableScheduling)
4494 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4496 case Intrinsic::log:
4499 case Intrinsic::log2:
4502 case Intrinsic::log10:
4505 case Intrinsic::exp:
4508 case Intrinsic::exp2:
4511 case Intrinsic::pow:
4514 case Intrinsic::pcmarker: {
4515 SDValue Tmp = getValue(I.getOperand(1));
4516 Res = DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp);
4518 if (DisableScheduling)
4519 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4522 case Intrinsic::readcyclecounter: {
4523 SDValue Op = getRoot();
4524 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4525 DAG.getVTList(MVT::i64, MVT::Other),
4528 DAG.setRoot(Res.getValue(1));
4529 if (DisableScheduling)
4530 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4533 case Intrinsic::bswap:
4534 Res = DAG.getNode(ISD::BSWAP, dl,
4535 getValue(I.getOperand(1)).getValueType(),
4536 getValue(I.getOperand(1)));
4538 if (DisableScheduling)
4539 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4541 case Intrinsic::cttz: {
4542 SDValue Arg = getValue(I.getOperand(1));
4543 EVT Ty = Arg.getValueType();
4544 Res = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4546 if (DisableScheduling)
4547 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4550 case Intrinsic::ctlz: {
4551 SDValue Arg = getValue(I.getOperand(1));
4552 EVT Ty = Arg.getValueType();
4553 Res = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4555 if (DisableScheduling)
4556 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4559 case Intrinsic::ctpop: {
4560 SDValue Arg = getValue(I.getOperand(1));
4561 EVT Ty = Arg.getValueType();
4562 Res = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4564 if (DisableScheduling)
4565 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4568 case Intrinsic::stacksave: {
4569 SDValue Op = getRoot();
4570 Res = DAG.getNode(ISD::STACKSAVE, dl,
4571 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4573 DAG.setRoot(Res.getValue(1));
4574 if (DisableScheduling)
4575 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4578 case Intrinsic::stackrestore: {
4579 Res = getValue(I.getOperand(1));
4580 Res = DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res);
4582 if (DisableScheduling)
4583 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4586 case Intrinsic::stackprotector: {
4587 // Emit code into the DAG to store the stack guard onto the stack.
4588 MachineFunction &MF = DAG.getMachineFunction();
4589 MachineFrameInfo *MFI = MF.getFrameInfo();
4590 EVT PtrTy = TLI.getPointerTy();
4592 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4593 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4595 int FI = FuncInfo.StaticAllocaMap[Slot];
4596 MFI->setStackProtectorIndex(FI);
4598 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4600 // Store the stack protector onto the stack.
4601 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4602 PseudoSourceValue::getFixedStack(FI),
4606 if (DisableScheduling)
4607 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4610 case Intrinsic::objectsize: {
4611 // If we don't know by now, we're never going to know.
4612 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4614 assert(CI && "Non-constant type in __builtin_object_size?");
4616 SDValue Arg = getValue(I.getOperand(0));
4617 EVT Ty = Arg.getValueType();
4619 if (CI->getZExtValue() < 2)
4620 Res = DAG.getConstant(-1ULL, Ty);
4622 Res = DAG.getConstant(0, Ty);
4625 if (DisableScheduling)
4626 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4629 case Intrinsic::var_annotation:
4630 // Discard annotate attributes
4633 case Intrinsic::init_trampoline: {
4634 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4638 Ops[1] = getValue(I.getOperand(1));
4639 Ops[2] = getValue(I.getOperand(2));
4640 Ops[3] = getValue(I.getOperand(3));
4641 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4642 Ops[5] = DAG.getSrcValue(F);
4644 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4645 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4649 DAG.setRoot(Res.getValue(1));
4650 if (DisableScheduling)
4651 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4654 case Intrinsic::gcroot:
4656 Value *Alloca = I.getOperand(1);
4657 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4659 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4660 GFI->addStackRoot(FI->getIndex(), TypeMap);
4663 case Intrinsic::gcread:
4664 case Intrinsic::gcwrite:
4665 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4667 case Intrinsic::flt_rounds:
4668 Res = DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32);
4670 if (DisableScheduling)
4671 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4673 case Intrinsic::trap:
4674 Res = DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot());
4676 if (DisableScheduling)
4677 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4679 case Intrinsic::uadd_with_overflow:
4680 return implVisitAluOverflow(I, ISD::UADDO);
4681 case Intrinsic::sadd_with_overflow:
4682 return implVisitAluOverflow(I, ISD::SADDO);
4683 case Intrinsic::usub_with_overflow:
4684 return implVisitAluOverflow(I, ISD::USUBO);
4685 case Intrinsic::ssub_with_overflow:
4686 return implVisitAluOverflow(I, ISD::SSUBO);
4687 case Intrinsic::umul_with_overflow:
4688 return implVisitAluOverflow(I, ISD::UMULO);
4689 case Intrinsic::smul_with_overflow:
4690 return implVisitAluOverflow(I, ISD::SMULO);
4692 case Intrinsic::prefetch: {
4695 Ops[1] = getValue(I.getOperand(1));
4696 Ops[2] = getValue(I.getOperand(2));
4697 Ops[3] = getValue(I.getOperand(3));
4698 Res = DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4);
4700 if (DisableScheduling)
4701 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4705 case Intrinsic::memory_barrier: {
4708 for (int x = 1; x < 6; ++x)
4709 Ops[x] = getValue(I.getOperand(x));
4711 Res = DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6);
4713 if (DisableScheduling)
4714 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4717 case Intrinsic::atomic_cmp_swap: {
4718 SDValue Root = getRoot();
4720 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4721 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4723 getValue(I.getOperand(1)),
4724 getValue(I.getOperand(2)),
4725 getValue(I.getOperand(3)),
4728 DAG.setRoot(L.getValue(1));
4729 if (DisableScheduling)
4730 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
4733 case Intrinsic::atomic_load_add:
4734 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4735 case Intrinsic::atomic_load_sub:
4736 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4737 case Intrinsic::atomic_load_or:
4738 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4739 case Intrinsic::atomic_load_xor:
4740 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4741 case Intrinsic::atomic_load_and:
4742 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4743 case Intrinsic::atomic_load_nand:
4744 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4745 case Intrinsic::atomic_load_max:
4746 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4747 case Intrinsic::atomic_load_min:
4748 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4749 case Intrinsic::atomic_load_umin:
4750 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4751 case Intrinsic::atomic_load_umax:
4752 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4753 case Intrinsic::atomic_swap:
4754 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4756 case Intrinsic::invariant_start:
4757 case Intrinsic::lifetime_start:
4758 // Discard region information.
4759 Res = DAG.getUNDEF(TLI.getPointerTy());
4761 if (DisableScheduling)
4762 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4764 case Intrinsic::invariant_end:
4765 case Intrinsic::lifetime_end:
4766 // Discard region information.
4771 /// Test if the given instruction is in a position to be optimized
4772 /// with a tail-call. This roughly means that it's in a block with
4773 /// a return and there's nothing that needs to be scheduled
4774 /// between it and the return.
4776 /// This function only tests target-independent requirements.
4777 /// For target-dependent requirements, a target should override
4778 /// TargetLowering::IsEligibleForTailCallOptimization.
4781 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
4782 const TargetLowering &TLI) {
4783 const BasicBlock *ExitBB = I->getParent();
4784 const TerminatorInst *Term = ExitBB->getTerminator();
4785 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4786 const Function *F = ExitBB->getParent();
4788 // The block must end in a return statement or an unreachable.
4789 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4791 // If I will have a chain, make sure no other instruction that will have a
4792 // chain interposes between I and the return.
4793 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4794 !I->isSafeToSpeculativelyExecute())
4795 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4799 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4800 !BBI->isSafeToSpeculativelyExecute())
4804 // If the block ends with a void return or unreachable, it doesn't matter
4805 // what the call's return type is.
4806 if (!Ret || Ret->getNumOperands() == 0) return true;
4808 // If the return value is undef, it doesn't matter what the call's
4810 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4812 // Conservatively require the attributes of the call to match those of
4813 // the return. Ignore noalias because it doesn't affect the call sequence.
4814 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4815 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4818 // Otherwise, make sure the unmodified return value of I is the return value.
4819 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4820 U = dyn_cast<Instruction>(U->getOperand(0))) {
4823 if (!U->hasOneUse())
4827 // Check for a truly no-op truncate.
4828 if (isa<TruncInst>(U) &&
4829 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4831 // Check for a truly no-op bitcast.
4832 if (isa<BitCastInst>(U) &&
4833 (U->getOperand(0)->getType() == U->getType() ||
4834 (isa<PointerType>(U->getOperand(0)->getType()) &&
4835 isa<PointerType>(U->getType()))))
4837 // Otherwise it's not a true no-op.
4844 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4846 MachineBasicBlock *LandingPad) {
4847 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4848 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4849 const Type *RetTy = FTy->getReturnType();
4850 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4851 unsigned BeginLabel = 0, EndLabel = 0;
4853 TargetLowering::ArgListTy Args;
4854 TargetLowering::ArgListEntry Entry;
4855 Args.reserve(CS.arg_size());
4857 // Check whether the function can return without sret-demotion.
4858 SmallVector<EVT, 4> OutVTs;
4859 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4860 SmallVector<uint64_t, 4> Offsets;
4861 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4862 OutVTs, OutsFlags, TLI, &Offsets);
4864 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4865 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4867 SDValue DemoteStackSlot;
4869 if (!CanLowerReturn) {
4870 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4871 FTy->getReturnType());
4872 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4873 FTy->getReturnType());
4874 MachineFunction &MF = DAG.getMachineFunction();
4875 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4876 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4878 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4879 Entry.Node = DemoteStackSlot;
4880 Entry.Ty = StackSlotPtrType;
4881 Entry.isSExt = false;
4882 Entry.isZExt = false;
4883 Entry.isInReg = false;
4884 Entry.isSRet = true;
4885 Entry.isNest = false;
4886 Entry.isByVal = false;
4887 Entry.Alignment = Align;
4888 Args.push_back(Entry);
4889 RetTy = Type::getVoidTy(FTy->getContext());
4892 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4894 SDValue ArgNode = getValue(*i);
4895 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4897 unsigned attrInd = i - CS.arg_begin() + 1;
4898 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4899 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4900 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4901 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4902 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4903 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4904 Entry.Alignment = CS.getParamAlignment(attrInd);
4905 Args.push_back(Entry);
4908 if (LandingPad && MMI) {
4909 // Insert a label before the invoke call to mark the try range. This can be
4910 // used to detect deletion of the invoke via the MachineModuleInfo.
4911 BeginLabel = MMI->NextLabelID();
4913 // Both PendingLoads and PendingExports must be flushed here;
4914 // this call might not return.
4916 SDValue Label = DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4917 getControlRoot(), BeginLabel);
4919 if (DisableScheduling)
4920 DAG.AssignOrdering(Label.getNode(), SDNodeOrder);
4923 // Check if target-independent constraints permit a tail call here.
4924 // Target-dependent constraints are checked within TLI.LowerCallTo.
4926 !isInTailCallPosition(CS.getInstruction(),
4927 CS.getAttributes().getRetAttributes(),
4931 std::pair<SDValue,SDValue> Result =
4932 TLI.LowerCallTo(getRoot(), RetTy,
4933 CS.paramHasAttr(0, Attribute::SExt),
4934 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4935 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4936 CS.getCallingConv(),
4938 !CS.getInstruction()->use_empty(),
4939 Callee, Args, DAG, getCurDebugLoc());
4940 assert((isTailCall || Result.second.getNode()) &&
4941 "Non-null chain expected with non-tail call!");
4942 assert((Result.second.getNode() || !Result.first.getNode()) &&
4943 "Null value expected with tail call!");
4944 if (Result.first.getNode()) {
4945 setValue(CS.getInstruction(), Result.first);
4946 if (DisableScheduling)
4947 DAG.AssignOrdering(Result.first.getNode(), SDNodeOrder);
4948 } else if (!CanLowerReturn && Result.second.getNode()) {
4949 // The instruction result is the result of loading from the
4950 // hidden sret parameter.
4951 SmallVector<EVT, 1> PVTs;
4952 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4954 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4955 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4956 EVT PtrVT = PVTs[0];
4957 unsigned NumValues = OutVTs.size();
4958 SmallVector<SDValue, 4> Values(NumValues);
4959 SmallVector<SDValue, 4> Chains(NumValues);
4961 for (unsigned i = 0; i < NumValues; ++i) {
4962 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4964 DAG.getConstant(Offsets[i], PtrVT));
4965 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4966 Add, NULL, Offsets[i], false, 1);
4968 Chains[i] = L.getValue(1);
4970 if (DisableScheduling) {
4971 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
4972 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
4976 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4977 MVT::Other, &Chains[0], NumValues);
4978 PendingLoads.push_back(Chain);
4980 SDValue MV = DAG.getNode(ISD::MERGE_VALUES,
4982 DAG.getVTList(&OutVTs[0], NumValues),
4983 &Values[0], NumValues);
4984 setValue(CS.getInstruction(), MV);
4986 if (DisableScheduling) {
4987 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
4988 DAG.AssignOrdering(MV.getNode(), SDNodeOrder);
4992 // As a special case, a null chain means that a tail call has been emitted and
4993 // the DAG root is already updated.
4994 if (Result.second.getNode()) {
4995 DAG.setRoot(Result.second);
4996 if (DisableScheduling)
4997 DAG.AssignOrdering(Result.second.getNode(), SDNodeOrder);
5002 if (LandingPad && MMI) {
5003 // Insert a label at the end of the invoke call to mark the try range. This
5004 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5005 EndLabel = MMI->NextLabelID();
5006 SDValue Label = DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
5007 getRoot(), EndLabel);
5010 if (DisableScheduling)
5011 DAG.AssignOrdering(Label.getNode(), SDNodeOrder);
5013 // Inform MachineModuleInfo of range.
5014 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
5018 void SelectionDAGBuilder::visitCall(CallInst &I) {
5019 const char *RenameFn = 0;
5020 if (Function *F = I.getCalledFunction()) {
5021 if (F->isDeclaration()) {
5022 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
5024 if (unsigned IID = II->getIntrinsicID(F)) {
5025 RenameFn = visitIntrinsicCall(I, IID);
5030 if (unsigned IID = F->getIntrinsicID()) {
5031 RenameFn = visitIntrinsicCall(I, IID);
5037 // Check for well-known libc/libm calls. If the function is internal, it
5038 // can't be a library call.
5039 if (!F->hasLocalLinkage() && F->hasName()) {
5040 StringRef Name = F->getName();
5041 if (Name == "copysign" || Name == "copysignf") {
5042 if (I.getNumOperands() == 3 && // Basic sanity checks.
5043 I.getOperand(1)->getType()->isFloatingPoint() &&
5044 I.getType() == I.getOperand(1)->getType() &&
5045 I.getType() == I.getOperand(2)->getType()) {
5046 SDValue LHS = getValue(I.getOperand(1));
5047 SDValue RHS = getValue(I.getOperand(2));
5048 SDValue Res = DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5049 LHS.getValueType(), LHS, RHS);
5051 if (DisableScheduling)
5052 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5055 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5056 if (I.getNumOperands() == 2 && // Basic sanity checks.
5057 I.getOperand(1)->getType()->isFloatingPoint() &&
5058 I.getType() == I.getOperand(1)->getType()) {
5059 SDValue Tmp = getValue(I.getOperand(1));
5060 SDValue Res = DAG.getNode(ISD::FABS, getCurDebugLoc(),
5061 Tmp.getValueType(), Tmp);
5063 if (DisableScheduling)
5064 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5067 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5068 if (I.getNumOperands() == 2 && // Basic sanity checks.
5069 I.getOperand(1)->getType()->isFloatingPoint() &&
5070 I.getType() == I.getOperand(1)->getType() &&
5071 I.onlyReadsMemory()) {
5072 SDValue Tmp = getValue(I.getOperand(1));
5073 SDValue Res = DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5074 Tmp.getValueType(), Tmp);
5076 if (DisableScheduling)
5077 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5080 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5081 if (I.getNumOperands() == 2 && // Basic sanity checks.
5082 I.getOperand(1)->getType()->isFloatingPoint() &&
5083 I.getType() == I.getOperand(1)->getType() &&
5084 I.onlyReadsMemory()) {
5085 SDValue Tmp = getValue(I.getOperand(1));
5086 SDValue Res = DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5087 Tmp.getValueType(), Tmp);
5089 if (DisableScheduling)
5090 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5093 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5094 if (I.getNumOperands() == 2 && // Basic sanity checks.
5095 I.getOperand(1)->getType()->isFloatingPoint() &&
5096 I.getType() == I.getOperand(1)->getType() &&
5097 I.onlyReadsMemory()) {
5098 SDValue Tmp = getValue(I.getOperand(1));
5099 SDValue Res = DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5100 Tmp.getValueType(), Tmp);
5102 if (DisableScheduling)
5103 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5108 } else if (isa<InlineAsm>(I.getOperand(0))) {
5115 Callee = getValue(I.getOperand(0));
5117 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5119 if (DisableScheduling)
5120 DAG.AssignOrdering(Callee.getNode(), SDNodeOrder);
5122 // Check if we can potentially perform a tail call. More detailed
5123 // checking is be done within LowerCallTo, after more information
5124 // about the call is known.
5125 bool isTailCall = PerformTailCallOpt && I.isTailCall();
5127 LowerCallTo(&I, Callee, isTailCall);
5130 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
5131 /// this value and returns the result as a ValueVT value. This uses
5132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5133 /// If the Flag pointer is NULL, no flag is used.
5134 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
5135 unsigned Order, SDValue &Chain,
5136 SDValue *Flag) const {
5137 // Assemble the legal parts into the final values.
5138 SmallVector<SDValue, 4> Values(ValueVTs.size());
5139 SmallVector<SDValue, 8> Parts;
5140 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5141 // Copy the legal parts from the registers.
5142 EVT ValueVT = ValueVTs[Value];
5143 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5144 EVT RegisterVT = RegVTs[Value];
5146 Parts.resize(NumRegs);
5147 for (unsigned i = 0; i != NumRegs; ++i) {
5150 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
5152 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
5153 *Flag = P.getValue(2);
5156 Chain = P.getValue(1);
5158 if (DisableScheduling)
5159 DAG.AssignOrdering(P.getNode(), Order);
5161 // If the source register was virtual and if we know something about it,
5162 // add an assert node.
5163 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
5164 RegisterVT.isInteger() && !RegisterVT.isVector()) {
5165 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
5166 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5167 if (FLI.LiveOutRegInfo.size() > SlotNo) {
5168 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
5170 unsigned RegSize = RegisterVT.getSizeInBits();
5171 unsigned NumSignBits = LOI.NumSignBits;
5172 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
5174 // FIXME: We capture more information than the dag can represent. For
5175 // now, just use the tightest assertzext/assertsext possible.
5177 EVT FromVT(MVT::Other);
5178 if (NumSignBits == RegSize)
5179 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
5180 else if (NumZeroBits >= RegSize-1)
5181 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
5182 else if (NumSignBits > RegSize-8)
5183 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
5184 else if (NumZeroBits >= RegSize-8)
5185 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
5186 else if (NumSignBits > RegSize-16)
5187 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
5188 else if (NumZeroBits >= RegSize-16)
5189 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
5190 else if (NumSignBits > RegSize-32)
5191 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
5192 else if (NumZeroBits >= RegSize-32)
5193 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
5195 if (FromVT != MVT::Other) {
5196 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
5197 RegisterVT, P, DAG.getValueType(FromVT));
5199 if (DisableScheduling)
5200 DAG.AssignOrdering(P.getNode(), Order);
5208 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
5209 NumRegs, RegisterVT, ValueVT);
5210 if (DisableScheduling)
5211 DAG.AssignOrdering(Values[Value].getNode(), Order);
5216 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5217 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
5218 &Values[0], ValueVTs.size());
5219 if (DisableScheduling)
5220 DAG.AssignOrdering(Res.getNode(), Order);
5224 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
5225 /// specified value into the registers specified by this object. This uses
5226 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5227 /// If the Flag pointer is NULL, no flag is used.
5228 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
5229 unsigned Order, SDValue &Chain,
5230 SDValue *Flag) const {
5231 // Get the list of the values's legal parts.
5232 unsigned NumRegs = Regs.size();
5233 SmallVector<SDValue, 8> Parts(NumRegs);
5234 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5235 EVT ValueVT = ValueVTs[Value];
5236 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5237 EVT RegisterVT = RegVTs[Value];
5239 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
5240 &Parts[Part], NumParts, RegisterVT);
5244 // Copy the parts into the registers.
5245 SmallVector<SDValue, 8> Chains(NumRegs);
5246 for (unsigned i = 0; i != NumRegs; ++i) {
5249 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
5251 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
5252 *Flag = Part.getValue(1);
5255 Chains[i] = Part.getValue(0);
5257 if (DisableScheduling)
5258 DAG.AssignOrdering(Part.getNode(), Order);
5261 if (NumRegs == 1 || Flag)
5262 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
5263 // flagged to it. That is the CopyToReg nodes and the user are considered
5264 // a single scheduling unit. If we create a TokenFactor and return it as
5265 // chain, then the TokenFactor is both a predecessor (operand) of the
5266 // user as well as a successor (the TF operands are flagged to the user).
5267 // c1, f1 = CopyToReg
5268 // c2, f2 = CopyToReg
5269 // c3 = TokenFactor c1, c2
5272 Chain = Chains[NumRegs-1];
5274 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
5276 if (DisableScheduling)
5277 DAG.AssignOrdering(Chain.getNode(), Order);
5280 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
5281 /// operand list. This adds the code marker and includes the number of
5282 /// values added into it.
5283 void RegsForValue::AddInlineAsmOperands(unsigned Code,
5284 bool HasMatching,unsigned MatchingIdx,
5285 SelectionDAG &DAG, unsigned Order,
5286 std::vector<SDValue> &Ops) const {
5287 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5288 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
5289 unsigned Flag = Code | (Regs.size() << 3);
5291 Flag |= 0x80000000 | (MatchingIdx << 16);
5293 SDValue Res = DAG.getTargetConstant(Flag, IntPtrTy);
5296 if (DisableScheduling)
5297 DAG.AssignOrdering(Res.getNode(), Order);
5299 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
5300 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
5301 EVT RegisterVT = RegVTs[Value];
5302 for (unsigned i = 0; i != NumRegs; ++i) {
5303 assert(Reg < Regs.size() && "Mismatch in # registers expected");
5304 SDValue Res = DAG.getRegister(Regs[Reg++], RegisterVT);
5307 if (DisableScheduling)
5308 DAG.AssignOrdering(Res.getNode(), Order);
5313 /// isAllocatableRegister - If the specified register is safe to allocate,
5314 /// i.e. it isn't a stack pointer or some other special register, return the
5315 /// register class for the register. Otherwise, return null.
5316 static const TargetRegisterClass *
5317 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5318 const TargetLowering &TLI,
5319 const TargetRegisterInfo *TRI) {
5320 EVT FoundVT = MVT::Other;
5321 const TargetRegisterClass *FoundRC = 0;
5322 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5323 E = TRI->regclass_end(); RCI != E; ++RCI) {
5324 EVT ThisVT = MVT::Other;
5326 const TargetRegisterClass *RC = *RCI;
5327 // If none of the the value types for this register class are valid, we
5328 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5329 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5331 if (TLI.isTypeLegal(*I)) {
5332 // If we have already found this register in a different register class,
5333 // choose the one with the largest VT specified. For example, on
5334 // PowerPC, we favor f64 register classes over f32.
5335 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5342 if (ThisVT == MVT::Other) continue;
5344 // NOTE: This isn't ideal. In particular, this might allocate the
5345 // frame pointer in functions that need it (due to them not being taken
5346 // out of allocation, because a variable sized allocation hasn't been seen
5347 // yet). This is a slight code pessimization, but should still work.
5348 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5349 E = RC->allocation_order_end(MF); I != E; ++I)
5351 // We found a matching register class. Keep looking at others in case
5352 // we find one with larger registers that this physreg is also in.
5363 /// AsmOperandInfo - This contains information for each constraint that we are
5365 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
5366 public TargetLowering::AsmOperandInfo {
5368 /// CallOperand - If this is the result output operand or a clobber
5369 /// this is null, otherwise it is the incoming operand to the CallInst.
5370 /// This gets modified as the asm is processed.
5371 SDValue CallOperand;
5373 /// AssignedRegs - If this is a register or register class operand, this
5374 /// contains the set of register corresponding to the operand.
5375 RegsForValue AssignedRegs;
5377 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
5378 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5381 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5382 /// busy in OutputRegs/InputRegs.
5383 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5384 std::set<unsigned> &OutputRegs,
5385 std::set<unsigned> &InputRegs,
5386 const TargetRegisterInfo &TRI) const {
5388 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5389 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5392 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5393 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5397 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5398 /// corresponds to. If there is no Value* for this operand, it returns
5400 EVT getCallOperandValEVT(LLVMContext &Context,
5401 const TargetLowering &TLI,
5402 const TargetData *TD) const {
5403 if (CallOperandVal == 0) return MVT::Other;
5405 if (isa<BasicBlock>(CallOperandVal))
5406 return TLI.getPointerTy();
5408 const llvm::Type *OpTy = CallOperandVal->getType();
5410 // If this is an indirect operand, the operand is a pointer to the
5413 OpTy = cast<PointerType>(OpTy)->getElementType();
5415 // If OpTy is not a single value, it may be a struct/union that we
5416 // can tile with integers.
5417 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5418 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5427 OpTy = IntegerType::get(Context, BitSize);
5432 return TLI.getValueType(OpTy, true);
5436 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5438 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5439 const TargetRegisterInfo &TRI) {
5440 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5442 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5443 for (; *Aliases; ++Aliases)
5444 Regs.insert(*Aliases);
5447 } // end llvm namespace.
5450 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5451 /// specified operand. We prefer to assign virtual registers, to allow the
5452 /// register allocator to handle the assignment process. However, if the asm
5453 /// uses features that we can't model on machineinstrs, we have SDISel do the
5454 /// allocation. This produces generally horrible, but correct, code.
5456 /// OpInfo describes the operand.
5457 /// Input and OutputRegs are the set of already allocated physical registers.
5459 void SelectionDAGBuilder::
5460 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5461 std::set<unsigned> &OutputRegs,
5462 std::set<unsigned> &InputRegs) {
5463 LLVMContext &Context = FuncInfo.Fn->getContext();
5465 // Compute whether this value requires an input register, an output register,
5467 bool isOutReg = false;
5468 bool isInReg = false;
5469 switch (OpInfo.Type) {
5470 case InlineAsm::isOutput:
5473 // If there is an input constraint that matches this, we need to reserve
5474 // the input register so no other inputs allocate to it.
5475 isInReg = OpInfo.hasMatchingInput();
5477 case InlineAsm::isInput:
5481 case InlineAsm::isClobber:
5488 MachineFunction &MF = DAG.getMachineFunction();
5489 SmallVector<unsigned, 4> Regs;
5491 // If this is a constraint for a single physreg, or a constraint for a
5492 // register class, find it.
5493 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5494 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5495 OpInfo.ConstraintVT);
5497 unsigned NumRegs = 1;
5498 if (OpInfo.ConstraintVT != MVT::Other) {
5499 // If this is a FP input in an integer register (or visa versa) insert a bit
5500 // cast of the input value. More generally, handle any case where the input
5501 // value disagrees with the register class we plan to stick this in.
5502 if (OpInfo.Type == InlineAsm::isInput &&
5503 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5504 // Try to convert to the first EVT that the reg class contains. If the
5505 // types are identical size, use a bitcast to convert (e.g. two differing
5507 EVT RegVT = *PhysReg.second->vt_begin();
5508 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5509 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5510 RegVT, OpInfo.CallOperand);
5511 OpInfo.ConstraintVT = RegVT;
5512 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5513 // If the input is a FP value and we want it in FP registers, do a
5514 // bitcast to the corresponding integer type. This turns an f64 value
5515 // into i64, which can be passed with two i32 values on a 32-bit
5517 RegVT = EVT::getIntegerVT(Context,
5518 OpInfo.ConstraintVT.getSizeInBits());
5519 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5520 RegVT, OpInfo.CallOperand);
5521 OpInfo.ConstraintVT = RegVT;
5524 if (DisableScheduling)
5525 DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder);
5528 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5532 EVT ValueVT = OpInfo.ConstraintVT;
5534 // If this is a constraint for a specific physical register, like {r17},
5536 if (unsigned AssignedReg = PhysReg.first) {
5537 const TargetRegisterClass *RC = PhysReg.second;
5538 if (OpInfo.ConstraintVT == MVT::Other)
5539 ValueVT = *RC->vt_begin();
5541 // Get the actual register value type. This is important, because the user
5542 // may have asked for (e.g.) the AX register in i32 type. We need to
5543 // remember that AX is actually i16 to get the right extension.
5544 RegVT = *RC->vt_begin();
5546 // This is a explicit reference to a physical register.
5547 Regs.push_back(AssignedReg);
5549 // If this is an expanded reference, add the rest of the regs to Regs.
5551 TargetRegisterClass::iterator I = RC->begin();
5552 for (; *I != AssignedReg; ++I)
5553 assert(I != RC->end() && "Didn't find reg!");
5555 // Already added the first reg.
5557 for (; NumRegs; --NumRegs, ++I) {
5558 assert(I != RC->end() && "Ran out of registers to allocate!");
5563 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5564 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5565 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5569 // Otherwise, if this was a reference to an LLVM register class, create vregs
5570 // for this reference.
5571 if (const TargetRegisterClass *RC = PhysReg.second) {
5572 RegVT = *RC->vt_begin();
5573 if (OpInfo.ConstraintVT == MVT::Other)
5576 // Create the appropriate number of virtual registers.
5577 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5578 for (; NumRegs; --NumRegs)
5579 Regs.push_back(RegInfo.createVirtualRegister(RC));
5581 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5585 // This is a reference to a register class that doesn't directly correspond
5586 // to an LLVM register class. Allocate NumRegs consecutive, available,
5587 // registers from the class.
5588 std::vector<unsigned> RegClassRegs
5589 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5590 OpInfo.ConstraintVT);
5592 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5593 unsigned NumAllocated = 0;
5594 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5595 unsigned Reg = RegClassRegs[i];
5596 // See if this register is available.
5597 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5598 (isInReg && InputRegs.count(Reg))) { // Already used.
5599 // Make sure we find consecutive registers.
5604 // Check to see if this register is allocatable (i.e. don't give out the
5606 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5607 if (!RC) { // Couldn't allocate this register.
5608 // Reset NumAllocated to make sure we return consecutive registers.
5613 // Okay, this register is good, we can use it.
5616 // If we allocated enough consecutive registers, succeed.
5617 if (NumAllocated == NumRegs) {
5618 unsigned RegStart = (i-NumAllocated)+1;
5619 unsigned RegEnd = i+1;
5620 // Mark all of the allocated registers used.
5621 for (unsigned i = RegStart; i != RegEnd; ++i)
5622 Regs.push_back(RegClassRegs[i]);
5624 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5625 OpInfo.ConstraintVT);
5626 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5631 // Otherwise, we couldn't allocate enough registers for this.
5634 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5635 /// processed uses a memory 'm' constraint.
5637 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5638 const TargetLowering &TLI) {
5639 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5640 InlineAsm::ConstraintInfo &CI = CInfos[i];
5641 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5642 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5643 if (CType == TargetLowering::C_Memory)
5647 // Indirect operand accesses access memory.
5655 /// visitInlineAsm - Handle a call to an InlineAsm object.
5657 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5658 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5660 /// ConstraintOperands - Information about all of the constraints.
5661 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5663 std::set<unsigned> OutputRegs, InputRegs;
5665 // Do a prepass over the constraints, canonicalizing them, and building up the
5666 // ConstraintOperands list.
5667 std::vector<InlineAsm::ConstraintInfo>
5668 ConstraintInfos = IA->ParseConstraints();
5670 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5672 SDValue Chain, Flag;
5674 // We won't need to flush pending loads if this asm doesn't touch
5675 // memory and is nonvolatile.
5676 if (hasMemory || IA->hasSideEffects())
5679 Chain = DAG.getRoot();
5681 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5682 unsigned ResNo = 0; // ResNo - The result number of the next output.
5683 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5684 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5685 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5687 EVT OpVT = MVT::Other;
5689 // Compute the value type for each operand.
5690 switch (OpInfo.Type) {
5691 case InlineAsm::isOutput:
5692 // Indirect outputs just consume an argument.
5693 if (OpInfo.isIndirect) {
5694 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5698 // The return value of the call is this value. As such, there is no
5699 // corresponding argument.
5700 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5702 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5703 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5705 assert(ResNo == 0 && "Asm only has one result!");
5706 OpVT = TLI.getValueType(CS.getType());
5710 case InlineAsm::isInput:
5711 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5713 case InlineAsm::isClobber:
5718 // If this is an input or an indirect output, process the call argument.
5719 // BasicBlocks are labels, currently appearing only in asm's.
5720 if (OpInfo.CallOperandVal) {
5721 // Strip bitcasts, if any. This mostly comes up for functions.
5722 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5724 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5725 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5727 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5730 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5733 OpInfo.ConstraintVT = OpVT;
5736 // Second pass over the constraints: compute which constraint option to use
5737 // and assign registers to constraints that want a specific physreg.
5738 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5739 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5741 // If this is an output operand with a matching input operand, look up the
5742 // matching input. If their types mismatch, e.g. one is an integer, the
5743 // other is floating point, or their sizes are different, flag it as an
5745 if (OpInfo.hasMatchingInput()) {
5746 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5747 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5748 if ((OpInfo.ConstraintVT.isInteger() !=
5749 Input.ConstraintVT.isInteger()) ||
5750 (OpInfo.ConstraintVT.getSizeInBits() !=
5751 Input.ConstraintVT.getSizeInBits())) {
5752 llvm_report_error("Unsupported asm: input constraint"
5753 " with a matching output constraint of incompatible"
5756 Input.ConstraintVT = OpInfo.ConstraintVT;
5760 // Compute the constraint code and ConstraintType to use.
5761 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5763 // If this is a memory input, and if the operand is not indirect, do what we
5764 // need to to provide an address for the memory input.
5765 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5766 !OpInfo.isIndirect) {
5767 assert(OpInfo.Type == InlineAsm::isInput &&
5768 "Can only indirectify direct input operands!");
5770 // Memory operands really want the address of the value. If we don't have
5771 // an indirect input, put it in the constpool if we can, otherwise spill
5772 // it to a stack slot.
5774 // If the operand is a float, integer, or vector constant, spill to a
5775 // constant pool entry to get its address.
5776 Value *OpVal = OpInfo.CallOperandVal;
5777 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5778 isa<ConstantVector>(OpVal)) {
5779 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5780 TLI.getPointerTy());
5782 // Otherwise, create a stack slot and emit a store to it before the
5784 const Type *Ty = OpVal->getType();
5785 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5786 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5787 MachineFunction &MF = DAG.getMachineFunction();
5788 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5789 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5790 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5791 OpInfo.CallOperand, StackSlot, NULL, 0);
5792 OpInfo.CallOperand = StackSlot;
5793 if (DisableScheduling)
5794 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
5797 // There is no longer a Value* corresponding to this operand.
5798 OpInfo.CallOperandVal = 0;
5800 // It is now an indirect operand.
5801 OpInfo.isIndirect = true;
5803 if (DisableScheduling)
5804 DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder);
5807 // If this constraint is for a specific register, allocate it before
5809 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5810 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5813 ConstraintInfos.clear();
5815 // Second pass - Loop over all of the operands, assigning virtual or physregs
5816 // to register class operands.
5817 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5818 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5820 // C_Register operands have already been allocated, Other/Memory don't need
5822 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5823 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5826 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5827 std::vector<SDValue> AsmNodeOperands;
5828 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5829 AsmNodeOperands.push_back(
5830 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5833 // Loop over all of the inputs, copying the operand values into the
5834 // appropriate registers and processing the output regs.
5835 RegsForValue RetValRegs;
5837 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5838 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5840 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5841 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5843 switch (OpInfo.Type) {
5844 case InlineAsm::isOutput: {
5845 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5846 OpInfo.ConstraintType != TargetLowering::C_Register) {
5847 // Memory output, or 'other' output (e.g. 'X' constraint).
5848 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5850 // Add information to the INLINEASM node to know about this output.
5851 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5852 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5853 TLI.getPointerTy()));
5854 AsmNodeOperands.push_back(OpInfo.CallOperand);
5858 // Otherwise, this is a register or register class output.
5860 // Copy the output from the appropriate register. Find a register that
5862 if (OpInfo.AssignedRegs.Regs.empty()) {
5863 llvm_report_error("Couldn't allocate output reg for"
5864 " constraint '" + OpInfo.ConstraintCode + "'!");
5867 // If this is an indirect operand, store through the pointer after the
5869 if (OpInfo.isIndirect) {
5870 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5871 OpInfo.CallOperandVal));
5873 // This is the result value of the call.
5874 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5876 // Concatenate this output onto the outputs list.
5877 RetValRegs.append(OpInfo.AssignedRegs);
5880 // Add information to the INLINEASM node to know that this register is
5882 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5883 6 /* EARLYCLOBBER REGDEF */ :
5891 case InlineAsm::isInput: {
5892 SDValue InOperandVal = OpInfo.CallOperand;
5894 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5895 // If this is required to match an output register we have already set,
5896 // just use its register.
5897 unsigned OperandNo = OpInfo.getMatchedOperand();
5899 // Scan until we find the definition we already emitted of this operand.
5900 // When we find it, create a RegsForValue operand.
5901 unsigned CurOp = 2; // The first operand.
5902 for (; OperandNo; --OperandNo) {
5903 // Advance to the next operand.
5905 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5906 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5907 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5908 (OpFlag & 7) == 4 /*MEM*/) &&
5909 "Skipped past definitions?");
5910 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5914 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5915 if ((OpFlag & 7) == 2 /*REGDEF*/
5916 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5917 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5918 if (OpInfo.isIndirect) {
5919 llvm_report_error("Don't know how to handle tied indirect "
5920 "register inputs yet!");
5922 RegsForValue MatchedRegs;
5923 MatchedRegs.TLI = &TLI;
5924 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5925 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5926 MatchedRegs.RegVTs.push_back(RegVT);
5927 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5928 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5931 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5933 // Use the produced MatchedRegs object to
5934 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5935 SDNodeOrder, Chain, &Flag);
5936 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5937 true, OpInfo.getMatchedOperand(),
5938 DAG, SDNodeOrder, AsmNodeOperands);
5941 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5942 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5943 "Unexpected number of operands");
5944 // Add information to the INLINEASM node to know about this input.
5945 // See InlineAsm.h isUseOperandTiedToDef.
5946 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5947 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5948 TLI.getPointerTy()));
5949 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5954 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5955 assert(!OpInfo.isIndirect &&
5956 "Don't know how to handle indirect other inputs yet!");
5958 std::vector<SDValue> Ops;
5959 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5960 hasMemory, Ops, DAG);
5962 llvm_report_error("Invalid operand for inline asm"
5963 " constraint '" + OpInfo.ConstraintCode + "'!");
5966 // Add information to the INLINEASM node to know about this input.
5967 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5968 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5969 TLI.getPointerTy()));
5970 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5972 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5973 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5974 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5975 "Memory operands expect pointer values");
5977 // Add information to the INLINEASM node to know about this input.
5978 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5979 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5980 TLI.getPointerTy()));
5981 AsmNodeOperands.push_back(InOperandVal);
5985 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5986 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5987 "Unknown constraint type!");
5988 assert(!OpInfo.isIndirect &&
5989 "Don't know how to handle indirect register inputs yet!");
5991 // Copy the input into the appropriate registers.
5992 if (OpInfo.AssignedRegs.Regs.empty()) {
5993 llvm_report_error("Couldn't allocate input reg for"
5994 " constraint '"+ OpInfo.ConstraintCode +"'!");
5997 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5998 SDNodeOrder, Chain, &Flag);
6000 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
6005 case InlineAsm::isClobber: {
6006 // Add the clobbered value to the operand list, so that the register
6007 // allocator is aware that the physreg got clobbered.
6008 if (!OpInfo.AssignedRegs.Regs.empty())
6009 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
6010 false, 0, DAG, SDNodeOrder,
6017 // Finish up input operands.
6018 AsmNodeOperands[0] = Chain;
6019 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6021 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6022 DAG.getVTList(MVT::Other, MVT::Flag),
6023 &AsmNodeOperands[0], AsmNodeOperands.size());
6024 Flag = Chain.getValue(1);
6026 if (DisableScheduling)
6027 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
6029 // If this asm returns a register value, copy the result from that register
6030 // and set it as the value of the call.
6031 if (!RetValRegs.Regs.empty()) {
6032 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6033 SDNodeOrder, Chain, &Flag);
6035 // FIXME: Why don't we do this for inline asms with MRVs?
6036 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6037 EVT ResultType = TLI.getValueType(CS.getType());
6039 // If any of the results of the inline asm is a vector, it may have the
6040 // wrong width/num elts. This can happen for register classes that can
6041 // contain multiple different value types. The preg or vreg allocated may
6042 // not have the same VT as was expected. Convert it to the right type
6043 // with bit_convert.
6044 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6045 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
6048 } else if (ResultType != Val.getValueType() &&
6049 ResultType.isInteger() && Val.getValueType().isInteger()) {
6050 // If a result value was tied to an input value, the computed result may
6051 // have a wider width than the expected result. Extract the relevant
6053 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6056 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6058 if (DisableScheduling)
6059 DAG.AssignOrdering(Val.getNode(), SDNodeOrder);
6062 setValue(CS.getInstruction(), Val);
6063 // Don't need to use this as a chain in this case.
6064 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6068 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
6070 // Process indirect outputs, first output all of the flagged copies out of
6072 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6073 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6074 Value *Ptr = IndirectStoresToEmit[i].second;
6075 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6076 SDNodeOrder, Chain, &Flag);
6077 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6081 // Emit the non-flagged stores from the physregs.
6082 SmallVector<SDValue, 8> OutChains;
6083 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6084 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6085 StoresToEmit[i].first,
6086 getValue(StoresToEmit[i].second),
6087 StoresToEmit[i].second, 0);
6088 OutChains.push_back(Val);
6089 if (DisableScheduling)
6090 DAG.AssignOrdering(Val.getNode(), SDNodeOrder);
6093 if (!OutChains.empty())
6094 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6095 &OutChains[0], OutChains.size());
6097 if (DisableScheduling)
6098 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
6103 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
6104 SDValue Res = DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6105 MVT::Other, getRoot(),
6106 getValue(I.getOperand(1)),
6107 DAG.getSrcValue(I.getOperand(1)));
6109 if (DisableScheduling)
6110 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6113 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
6114 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6115 getRoot(), getValue(I.getOperand(0)),
6116 DAG.getSrcValue(I.getOperand(0)));
6118 DAG.setRoot(V.getValue(1));
6119 if (DisableScheduling)
6120 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
6123 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
6124 SDValue Res = DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6125 MVT::Other, getRoot(),
6126 getValue(I.getOperand(1)),
6127 DAG.getSrcValue(I.getOperand(1)));
6129 if (DisableScheduling)
6130 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6133 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
6134 SDValue Res = DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6135 MVT::Other, getRoot(),
6136 getValue(I.getOperand(1)),
6137 getValue(I.getOperand(2)),
6138 DAG.getSrcValue(I.getOperand(1)),
6139 DAG.getSrcValue(I.getOperand(2)));
6141 if (DisableScheduling)
6142 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6145 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6146 /// implementation, which just calls LowerCall.
6147 /// FIXME: When all targets are
6148 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6149 std::pair<SDValue, SDValue>
6150 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6151 bool RetSExt, bool RetZExt, bool isVarArg,
6152 bool isInreg, unsigned NumFixedArgs,
6153 CallingConv::ID CallConv, bool isTailCall,
6154 bool isReturnValueUsed,
6156 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
6158 assert((!isTailCall || PerformTailCallOpt) &&
6159 "isTailCall set when tail-call optimizations are disabled!");
6161 // Handle all of the outgoing arguments.
6162 SmallVector<ISD::OutputArg, 32> Outs;
6163 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6164 SmallVector<EVT, 4> ValueVTs;
6165 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6166 for (unsigned Value = 0, NumValues = ValueVTs.size();
6167 Value != NumValues; ++Value) {
6168 EVT VT = ValueVTs[Value];
6169 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6170 SDValue Op = SDValue(Args[i].Node.getNode(),
6171 Args[i].Node.getResNo() + Value);
6172 ISD::ArgFlagsTy Flags;
6173 unsigned OriginalAlignment =
6174 getTargetData()->getABITypeAlignment(ArgTy);
6180 if (Args[i].isInReg)
6184 if (Args[i].isByVal) {
6186 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6187 const Type *ElementTy = Ty->getElementType();
6188 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
6189 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
6190 // For ByVal, alignment should come from FE. BE will guess if this
6191 // info is not there but there are cases it cannot get right.
6192 if (Args[i].Alignment)
6193 FrameAlign = Args[i].Alignment;
6194 Flags.setByValAlign(FrameAlign);
6195 Flags.setByValSize(FrameSize);
6199 Flags.setOrigAlign(OriginalAlignment);
6201 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6202 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6203 SmallVector<SDValue, 4> Parts(NumParts);
6204 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6207 ExtendKind = ISD::SIGN_EXTEND;
6208 else if (Args[i].isZExt)
6209 ExtendKind = ISD::ZERO_EXTEND;
6211 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
6213 for (unsigned j = 0; j != NumParts; ++j) {
6214 // if it isn't first piece, alignment must be 1
6215 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
6216 if (NumParts > 1 && j == 0)
6217 MyFlags.Flags.setSplit();
6219 MyFlags.Flags.setOrigAlign(1);
6221 Outs.push_back(MyFlags);
6226 // Handle the incoming return values from the call.
6227 SmallVector<ISD::InputArg, 32> Ins;
6228 SmallVector<EVT, 4> RetTys;
6229 ComputeValueVTs(*this, RetTy, RetTys);
6230 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6232 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6233 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6234 for (unsigned i = 0; i != NumRegs; ++i) {
6235 ISD::InputArg MyFlags;
6236 MyFlags.VT = RegisterVT;
6237 MyFlags.Used = isReturnValueUsed;
6239 MyFlags.Flags.setSExt();
6241 MyFlags.Flags.setZExt();
6243 MyFlags.Flags.setInReg();
6244 Ins.push_back(MyFlags);
6248 // Check if target-dependent constraints permit a tail call here.
6249 // Target-independent constraints should be checked by the caller.
6251 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
6254 SmallVector<SDValue, 4> InVals;
6255 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6256 Outs, Ins, dl, DAG, InVals);
6258 // Verify that the target's LowerCall behaved as expected.
6259 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6260 "LowerCall didn't return a valid chain!");
6261 assert((!isTailCall || InVals.empty()) &&
6262 "LowerCall emitted a return value for a tail call!");
6263 assert((isTailCall || InVals.size() == Ins.size()) &&
6264 "LowerCall didn't emit the correct number of values!");
6265 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6266 assert(InVals[i].getNode() &&
6267 "LowerCall emitted a null value!");
6268 assert(Ins[i].VT == InVals[i].getValueType() &&
6269 "LowerCall emitted a value with the wrong type!");
6272 // For a tail call, the return value is merely live-out and there aren't
6273 // any nodes in the DAG representing it. Return a special value to
6274 // indicate that a tail call has been emitted and no more Instructions
6275 // should be processed in the current block.
6278 return std::make_pair(SDValue(), SDValue());
6281 // Collect the legal value parts into potentially illegal values
6282 // that correspond to the original function's return values.
6283 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6285 AssertOp = ISD::AssertSext;
6287 AssertOp = ISD::AssertZext;
6288 SmallVector<SDValue, 4> ReturnValues;
6289 unsigned CurReg = 0;
6290 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6292 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6293 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6295 SDValue ReturnValue =
6296 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
6298 ReturnValues.push_back(ReturnValue);
6302 // For a function returning void, there is no return value. We can't create
6303 // such a node, so we just return a null return value in that case. In
6304 // that case, nothing will actualy look at the value.
6305 if (ReturnValues.empty())
6306 return std::make_pair(SDValue(), Chain);
6308 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6309 DAG.getVTList(&RetTys[0], RetTys.size()),
6310 &ReturnValues[0], ReturnValues.size());
6312 return std::make_pair(Res, Chain);
6315 void TargetLowering::LowerOperationWrapper(SDNode *N,
6316 SmallVectorImpl<SDValue> &Results,
6317 SelectionDAG &DAG) {
6318 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6320 Results.push_back(Res);
6323 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6324 llvm_unreachable("LowerOperation not implemented for this target!");
6329 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
6330 SDValue Op = getValue(V);
6331 assert((Op.getOpcode() != ISD::CopyFromReg ||
6332 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6333 "Copy from a reg to the same reg!");
6334 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6336 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6337 SDValue Chain = DAG.getEntryNode();
6338 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
6339 PendingExports.push_back(Chain);
6342 #include "llvm/CodeGen/SelectionDAGISel.h"
6344 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
6345 // If this is the entry block, emit arguments.
6346 Function &F = *LLVMBB->getParent();
6347 SelectionDAG &DAG = SDB->DAG;
6348 SDValue OldRoot = DAG.getRoot();
6349 DebugLoc dl = SDB->getCurDebugLoc();
6350 const TargetData *TD = TLI.getTargetData();
6351 SmallVector<ISD::InputArg, 16> Ins;
6353 // Check whether the function can return without sret-demotion.
6354 SmallVector<EVT, 4> OutVTs;
6355 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
6356 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6357 OutVTs, OutsFlags, TLI);
6358 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
6360 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
6361 OutVTs, OutsFlags, DAG);
6362 if (!FLI.CanLowerReturn) {
6363 // Put in an sret pointer parameter before all the other parameters.
6364 SmallVector<EVT, 1> ValueVTs;
6365 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6367 // NOTE: Assuming that a pointer will never break down to more than one VT
6369 ISD::ArgFlagsTy Flags;
6371 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
6372 ISD::InputArg RetArg(Flags, RegisterVT, true);
6373 Ins.push_back(RetArg);
6376 // Set up the incoming argument description vector.
6378 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
6379 I != E; ++I, ++Idx) {
6380 SmallVector<EVT, 4> ValueVTs;
6381 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6382 bool isArgValueUsed = !I->use_empty();
6383 for (unsigned Value = 0, NumValues = ValueVTs.size();
6384 Value != NumValues; ++Value) {
6385 EVT VT = ValueVTs[Value];
6386 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6387 ISD::ArgFlagsTy Flags;
6388 unsigned OriginalAlignment =
6389 TD->getABITypeAlignment(ArgTy);
6391 if (F.paramHasAttr(Idx, Attribute::ZExt))
6393 if (F.paramHasAttr(Idx, Attribute::SExt))
6395 if (F.paramHasAttr(Idx, Attribute::InReg))
6397 if (F.paramHasAttr(Idx, Attribute::StructRet))
6399 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6401 const PointerType *Ty = cast<PointerType>(I->getType());
6402 const Type *ElementTy = Ty->getElementType();
6403 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6404 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
6405 // For ByVal, alignment should be passed from FE. BE will guess if
6406 // this info is not there but there are cases it cannot get right.
6407 if (F.getParamAlignment(Idx))
6408 FrameAlign = F.getParamAlignment(Idx);
6409 Flags.setByValAlign(FrameAlign);
6410 Flags.setByValSize(FrameSize);
6412 if (F.paramHasAttr(Idx, Attribute::Nest))
6414 Flags.setOrigAlign(OriginalAlignment);
6416 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6417 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6418 for (unsigned i = 0; i != NumRegs; ++i) {
6419 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6420 if (NumRegs > 1 && i == 0)
6421 MyFlags.Flags.setSplit();
6422 // if it isn't first piece, alignment must be 1
6424 MyFlags.Flags.setOrigAlign(1);
6425 Ins.push_back(MyFlags);
6430 // Call the target to set up the argument values.
6431 SmallVector<SDValue, 8> InVals;
6432 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6436 // Verify that the target's LowerFormalArguments behaved as expected.
6437 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6438 "LowerFormalArguments didn't return a valid chain!");
6439 assert(InVals.size() == Ins.size() &&
6440 "LowerFormalArguments didn't emit the correct number of values!");
6441 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6442 assert(InVals[i].getNode() &&
6443 "LowerFormalArguments emitted a null value!");
6444 assert(Ins[i].VT == InVals[i].getValueType() &&
6445 "LowerFormalArguments emitted a value with the wrong type!");
6448 // Update the DAG with the new chain value resulting from argument lowering.
6449 DAG.setRoot(NewRoot);
6451 // Set up the argument values.
6454 if (!FLI.CanLowerReturn) {
6455 // Create a virtual register for the sret pointer, and put in a copy
6456 // from the sret argument into it.
6457 SmallVector<EVT, 1> ValueVTs;
6458 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6459 EVT VT = ValueVTs[0];
6460 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6461 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6462 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
6465 MachineFunction& MF = SDB->DAG.getMachineFunction();
6466 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6467 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6468 FLI.DemoteRegister = SRetReg;
6469 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue);
6470 DAG.setRoot(NewRoot);
6472 // i indexes lowered arguments. Bump it past the hidden sret argument.
6473 // Idx indexes LLVM arguments. Don't touch it.
6476 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6478 SmallVector<SDValue, 4> ArgValues;
6479 SmallVector<EVT, 4> ValueVTs;
6480 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6481 unsigned NumValues = ValueVTs.size();
6482 for (unsigned Value = 0; Value != NumValues; ++Value) {
6483 EVT VT = ValueVTs[Value];
6484 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6485 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6487 if (!I->use_empty()) {
6488 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6489 if (F.paramHasAttr(Idx, Attribute::SExt))
6490 AssertOp = ISD::AssertSext;
6491 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6492 AssertOp = ISD::AssertZext;
6494 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
6495 PartVT, VT, AssertOp));
6499 if (!I->use_empty()) {
6500 SDB->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
6501 SDB->getCurDebugLoc()));
6502 // If this argument is live outside of the entry block, insert a copy from
6503 // whereever we got it to the vreg that other BB's will reference it as.
6504 SDB->CopyToExportRegsIfNeeded(I);
6507 assert(i == InVals.size() && "Argument register count mismatch!");
6509 // Finally, if the target has anything special to do, allow it to do so.
6510 // FIXME: this should insert code into the DAG!
6511 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6514 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6515 /// ensure constants are generated when needed. Remember the virtual registers
6516 /// that need to be added to the Machine PHI nodes as input. We cannot just
6517 /// directly add them, because expansion might result in multiple MBB's for one
6518 /// BB. As such, the start of the BB might correspond to a different MBB than
6522 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6523 TerminatorInst *TI = LLVMBB->getTerminator();
6525 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6527 // Check successor nodes' PHI nodes that expect a constant to be available
6529 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6530 BasicBlock *SuccBB = TI->getSuccessor(succ);
6531 if (!isa<PHINode>(SuccBB->begin())) continue;
6532 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6534 // If this terminator has multiple identical successors (common for
6535 // switches), only handle each succ once.
6536 if (!SuccsHandled.insert(SuccMBB)) continue;
6538 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6541 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6542 // nodes and Machine PHI nodes, but the incoming operands have not been
6544 for (BasicBlock::iterator I = SuccBB->begin();
6545 (PN = dyn_cast<PHINode>(I)); ++I) {
6546 // Ignore dead phi's.
6547 if (PN->use_empty()) continue;
6550 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6552 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6553 unsigned &RegOut = SDB->ConstantsOut[C];
6555 RegOut = FuncInfo->CreateRegForValue(C);
6556 SDB->CopyValueToVirtualRegister(C, RegOut);
6560 Reg = FuncInfo->ValueMap[PHIOp];
6562 assert(isa<AllocaInst>(PHIOp) &&
6563 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6564 "Didn't codegen value into a register!??");
6565 Reg = FuncInfo->CreateRegForValue(PHIOp);
6566 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6570 // Remember that this register needs to added to the machine PHI node as
6571 // the input for this MBB.
6572 SmallVector<EVT, 4> ValueVTs;
6573 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6574 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6575 EVT VT = ValueVTs[vti];
6576 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6577 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6578 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6579 Reg += NumRegisters;
6583 SDB->ConstantsOut.clear();
6586 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6587 /// supports legal types, and it emits MachineInstrs directly instead of
6588 /// creating SelectionDAG nodes.
6591 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6593 TerminatorInst *TI = LLVMBB->getTerminator();
6595 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6596 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6598 // Check successor nodes' PHI nodes that expect a constant to be available
6600 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6601 BasicBlock *SuccBB = TI->getSuccessor(succ);
6602 if (!isa<PHINode>(SuccBB->begin())) continue;
6603 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6605 // If this terminator has multiple identical successors (common for
6606 // switches), only handle each succ once.
6607 if (!SuccsHandled.insert(SuccMBB)) continue;
6609 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6612 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6613 // nodes and Machine PHI nodes, but the incoming operands have not been
6615 for (BasicBlock::iterator I = SuccBB->begin();
6616 (PN = dyn_cast<PHINode>(I)); ++I) {
6617 // Ignore dead phi's.
6618 if (PN->use_empty()) continue;
6620 // Only handle legal types. Two interesting things to note here. First,
6621 // by bailing out early, we may leave behind some dead instructions,
6622 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6623 // own moves. Second, this check is necessary becuase FastISel doesn't
6624 // use CreateRegForValue to create registers, so it always creates
6625 // exactly one register for each non-void instruction.
6626 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6627 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6630 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6632 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6637 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6639 unsigned Reg = F->getRegForValue(PHIOp);
6641 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6644 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));