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,
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 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, std::vector<SDValue> &Ops) const;
166 /// getCopyFromParts - Create a value that contains the specified legal parts
167 /// combined into the value they represent. If the parts combine to a type
168 /// larger then ValueVT then AssertOp can be used to specify whether the extra
169 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
170 /// (ISD::AssertSext).
171 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
172 const SDValue *Parts,
173 unsigned NumParts, EVT PartVT, EVT ValueVT,
174 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
175 assert(NumParts > 0 && "No parts to assemble!");
176 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
177 SDValue Val = Parts[0];
180 // Assemble the value from multiple parts.
181 if (!ValueVT.isVector() && ValueVT.isInteger()) {
182 unsigned PartBits = PartVT.getSizeInBits();
183 unsigned ValueBits = ValueVT.getSizeInBits();
185 // Assemble the power of 2 part.
186 unsigned RoundParts = NumParts & (NumParts - 1) ?
187 1 << Log2_32(NumParts) : NumParts;
188 unsigned RoundBits = PartBits * RoundParts;
189 EVT RoundVT = RoundBits == ValueBits ?
190 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
193 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
195 if (RoundParts > 2) {
196 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
197 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
200 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
201 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
203 if (TLI.isBigEndian())
205 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
207 if (RoundParts < NumParts) {
208 // Assemble the trailing non-power-of-2 part.
209 unsigned OddParts = NumParts - RoundParts;
210 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
211 Hi = getCopyFromParts(DAG, dl,
212 Parts+RoundParts, OddParts, PartVT, OddVT);
214 // Combine the round and odd parts.
216 if (TLI.isBigEndian())
218 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
219 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
220 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
221 DAG.getConstant(Lo.getValueType().getSizeInBits(),
222 TLI.getPointerTy()));
223 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
224 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
226 } else if (ValueVT.isVector()) {
227 // Handle a multi-element vector.
228 EVT IntermediateVT, RegisterVT;
229 unsigned NumIntermediates;
231 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
232 NumIntermediates, RegisterVT);
233 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
234 NumParts = NumRegs; // Silence a compiler warning.
235 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
236 assert(RegisterVT == Parts[0].getValueType() &&
237 "Part type doesn't match part!");
239 // Assemble the parts into intermediate operands.
240 SmallVector<SDValue, 8> Ops(NumIntermediates);
241 if (NumIntermediates == NumParts) {
242 // If the register was not expanded, truncate or copy the value,
244 for (unsigned i = 0; i != NumParts; ++i)
245 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
246 PartVT, IntermediateVT);
247 } else if (NumParts > 0) {
248 // If the intermediate type was expanded, build the intermediate operands
250 assert(NumParts % NumIntermediates == 0 &&
251 "Must expand into a divisible number of parts!");
252 unsigned Factor = NumParts / NumIntermediates;
253 for (unsigned i = 0; i != NumIntermediates; ++i)
254 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
255 PartVT, IntermediateVT);
258 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
260 Val = DAG.getNode(IntermediateVT.isVector() ?
261 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
262 ValueVT, &Ops[0], NumIntermediates);
263 } else if (PartVT.isFloatingPoint()) {
264 // FP split into multiple FP parts (for ppcf128)
265 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
268 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
269 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
270 if (TLI.isBigEndian())
272 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
274 // FP split into integer parts (soft fp)
275 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
276 !PartVT.isVector() && "Unexpected split");
277 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
278 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
282 // There is now one part, held in Val. Correct it to match ValueVT.
283 PartVT = Val.getValueType();
285 if (PartVT == ValueVT)
288 if (PartVT.isVector()) {
289 assert(ValueVT.isVector() && "Unknown vector conversion!");
290 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
293 if (ValueVT.isVector()) {
294 assert(ValueVT.getVectorElementType() == PartVT &&
295 ValueVT.getVectorNumElements() == 1 &&
296 "Only trivial scalar-to-vector conversions should get here!");
297 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
300 if (PartVT.isInteger() &&
301 ValueVT.isInteger()) {
302 if (ValueVT.bitsLT(PartVT)) {
303 // For a truncate, see if we have any information to
304 // indicate whether the truncated bits will always be
305 // zero or sign-extension.
306 if (AssertOp != ISD::DELETED_NODE)
307 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
308 DAG.getValueType(ValueVT));
309 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
311 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
315 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316 if (ValueVT.bitsLT(Val.getValueType()))
317 // FP_ROUND's are always exact here.
318 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
319 DAG.getIntPtrConstant(1));
320 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
323 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
324 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
326 llvm_unreachable("Unknown mismatch!");
330 /// getCopyToParts - Create a series of nodes that contain the specified value
331 /// split into legal parts. If the parts contain more bits than Val, then, for
332 /// integers, ExtendKind can be used to specify how to generate the extra bits.
333 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
334 SDValue *Parts, unsigned NumParts, EVT PartVT,
335 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
337 EVT PtrVT = TLI.getPointerTy();
338 EVT ValueVT = Val.getValueType();
339 unsigned PartBits = PartVT.getSizeInBits();
340 unsigned OrigNumParts = NumParts;
341 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
346 if (!ValueVT.isVector()) {
347 if (PartVT == ValueVT) {
348 assert(NumParts == 1 && "No-op copy with multiple parts!");
353 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
354 // If the parts cover more bits than the value has, promote the value.
355 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
356 assert(NumParts == 1 && "Do not know what to promote to!");
357 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
358 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
359 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
360 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
362 llvm_unreachable("Unknown mismatch!");
364 } else if (PartBits == ValueVT.getSizeInBits()) {
365 // Different types of the same size.
366 assert(NumParts == 1 && PartVT != ValueVT);
367 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
368 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
369 // If the parts cover less bits than value has, truncate the value.
370 if (PartVT.isInteger() && ValueVT.isInteger()) {
371 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
372 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
374 llvm_unreachable("Unknown mismatch!");
378 // The value may have changed - recompute ValueVT.
379 ValueVT = Val.getValueType();
380 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
381 "Failed to tile the value with PartVT!");
384 assert(PartVT == ValueVT && "Type conversion failed!");
389 // Expand the value into multiple parts.
390 if (NumParts & (NumParts - 1)) {
391 // The number of parts is not a power of 2. Split off and copy the tail.
392 assert(PartVT.isInteger() && ValueVT.isInteger() &&
393 "Do not know what to expand to!");
394 unsigned RoundParts = 1 << Log2_32(NumParts);
395 unsigned RoundBits = RoundParts * PartBits;
396 unsigned OddParts = NumParts - RoundParts;
397 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
398 DAG.getConstant(RoundBits,
399 TLI.getPointerTy()));
400 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
401 if (TLI.isBigEndian())
402 // The odd parts were reversed by getCopyToParts - unreverse them.
403 std::reverse(Parts + RoundParts, Parts + NumParts);
404 NumParts = RoundParts;
405 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
406 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
409 // The number of parts is a power of 2. Repeatedly bisect the value using
411 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
412 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
414 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
415 for (unsigned i = 0; i < NumParts; i += StepSize) {
416 unsigned ThisBits = StepSize * PartBits / 2;
417 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
418 SDValue &Part0 = Parts[i];
419 SDValue &Part1 = Parts[i+StepSize/2];
421 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
423 DAG.getConstant(1, PtrVT));
424 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
426 DAG.getConstant(0, PtrVT));
428 if (ThisBits == PartBits && ThisVT != PartVT) {
429 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
431 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
437 if (TLI.isBigEndian())
438 std::reverse(Parts, Parts + OrigNumParts);
445 if (PartVT != ValueVT) {
446 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
447 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
449 assert(ValueVT.getVectorElementType() == PartVT &&
450 ValueVT.getVectorNumElements() == 1 &&
451 "Only trivial vector-to-scalar conversions should get here!");
452 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
454 DAG.getConstant(0, PtrVT));
462 // Handle a multi-element vector.
463 EVT IntermediateVT, RegisterVT;
464 unsigned NumIntermediates;
465 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
466 IntermediateVT, NumIntermediates, RegisterVT);
467 unsigned NumElements = ValueVT.getVectorNumElements();
469 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
470 NumParts = NumRegs; // Silence a compiler warning.
471 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
473 // Split the vector into intermediate operands.
474 SmallVector<SDValue, 8> Ops(NumIntermediates);
475 for (unsigned i = 0; i != NumIntermediates; ++i)
476 if (IntermediateVT.isVector())
477 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
479 DAG.getConstant(i * (NumElements / NumIntermediates),
482 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
484 DAG.getConstant(i, PtrVT));
486 // Split the intermediate operands into legal parts.
487 if (NumParts == NumIntermediates) {
488 // If the register was not expanded, promote or copy the value,
490 for (unsigned i = 0; i != NumParts; ++i)
491 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
492 } else if (NumParts > 0) {
493 // If the intermediate type was expanded, split each the value into
495 assert(NumParts % NumIntermediates == 0 &&
496 "Must expand into a divisible number of parts!");
497 unsigned Factor = NumParts / NumIntermediates;
498 for (unsigned i = 0; i != NumIntermediates; ++i)
499 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
504 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
507 TD = DAG.getTarget().getTargetData();
510 /// clear - Clear out the curret SelectionDAG and the associated
511 /// state and prepare this SelectionDAGBuilder object to be used
512 /// for a new block. This doesn't clear out information about
513 /// additional blocks that are needed to complete switch lowering
514 /// or PHI node updating; that information is cleared out as it is
516 void SelectionDAGBuilder::clear() {
518 PendingLoads.clear();
519 PendingExports.clear();
522 CurDebugLoc = DebugLoc::getUnknownLoc();
526 /// getRoot - Return the current virtual root of the Selection DAG,
527 /// flushing any PendingLoad items. This must be done before emitting
528 /// a store or any other node that may need to be ordered after any
529 /// prior load instructions.
531 SDValue SelectionDAGBuilder::getRoot() {
532 if (PendingLoads.empty())
533 return DAG.getRoot();
535 if (PendingLoads.size() == 1) {
536 SDValue Root = PendingLoads[0];
538 PendingLoads.clear();
542 // Otherwise, we have to make a token factor node.
543 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
544 &PendingLoads[0], PendingLoads.size());
545 PendingLoads.clear();
550 /// getControlRoot - Similar to getRoot, but instead of flushing all the
551 /// PendingLoad items, flush all the PendingExports items. It is necessary
552 /// to do this before emitting a terminator instruction.
554 SDValue SelectionDAGBuilder::getControlRoot() {
555 SDValue Root = DAG.getRoot();
557 if (PendingExports.empty())
560 // Turn all of the CopyToReg chains into one factored node.
561 if (Root.getOpcode() != ISD::EntryToken) {
562 unsigned i = 0, e = PendingExports.size();
563 for (; i != e; ++i) {
564 assert(PendingExports[i].getNode()->getNumOperands() > 1);
565 if (PendingExports[i].getNode()->getOperand(0) == Root)
566 break; // Don't add the root if we already indirectly depend on it.
570 PendingExports.push_back(Root);
573 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
575 PendingExports.size());
576 PendingExports.clear();
581 void SelectionDAGBuilder::visit(Instruction &I) {
582 visit(I.getOpcode(), I);
585 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
586 // We're processing a new instruction.
589 // Note: this doesn't use InstVisitor, because it has to work with
590 // ConstantExpr's in addition to instructions.
592 default: llvm_unreachable("Unknown instruction type encountered!");
593 // Build the switch statement using the Instruction.def file.
594 #define HANDLE_INST(NUM, OPCODE, CLASS) \
595 case Instruction::OPCODE: return visit##OPCODE((CLASS&)I);
596 #include "llvm/Instruction.def"
600 SDValue SelectionDAGBuilder::getValue(const Value *V) {
601 SDValue &N = NodeMap[V];
602 if (N.getNode()) return N;
604 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
605 EVT VT = TLI.getValueType(V->getType(), true);
607 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
608 return N = DAG.getConstant(*CI, VT);
610 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
611 return N = DAG.getGlobalAddress(GV, VT);
613 if (isa<ConstantPointerNull>(C))
614 return N = DAG.getConstant(0, TLI.getPointerTy());
616 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
617 return N = DAG.getConstantFP(*CFP, VT);
619 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
620 return N = DAG.getUNDEF(VT);
622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
623 visit(CE->getOpcode(), *CE);
624 SDValue N1 = NodeMap[V];
625 assert(N1.getNode() && "visit didn't populate the ValueMap!");
629 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
630 SmallVector<SDValue, 4> Constants;
631 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
633 SDNode *Val = getValue(*OI).getNode();
634 // If the operand is an empty aggregate, there are no values.
636 // Add each leaf value from the operand to the Constants list
637 // to form a flattened list of all the values.
638 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
639 Constants.push_back(SDValue(Val, i));
642 SDValue Res = DAG.getMergeValues(&Constants[0], Constants.size(),
644 if (DisableScheduling)
645 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
649 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
650 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
651 "Unknown struct or array constant!");
653 SmallVector<EVT, 4> ValueVTs;
654 ComputeValueVTs(TLI, C->getType(), ValueVTs);
655 unsigned NumElts = ValueVTs.size();
657 return SDValue(); // empty struct
658 SmallVector<SDValue, 4> Constants(NumElts);
659 for (unsigned i = 0; i != NumElts; ++i) {
660 EVT EltVT = ValueVTs[i];
661 if (isa<UndefValue>(C))
662 Constants[i] = DAG.getUNDEF(EltVT);
663 else if (EltVT.isFloatingPoint())
664 Constants[i] = DAG.getConstantFP(0, EltVT);
666 Constants[i] = DAG.getConstant(0, EltVT);
669 SDValue Res = DAG.getMergeValues(&Constants[0], NumElts,
671 if (DisableScheduling)
672 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
676 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
677 return DAG.getBlockAddress(BA, VT);
679 const VectorType *VecTy = cast<VectorType>(V->getType());
680 unsigned NumElements = VecTy->getNumElements();
682 // Now that we know the number and type of the elements, get that number of
683 // elements into the Ops array based on what kind of constant it is.
684 SmallVector<SDValue, 16> Ops;
685 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
686 for (unsigned i = 0; i != NumElements; ++i)
687 Ops.push_back(getValue(CP->getOperand(i)));
689 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
690 EVT EltVT = TLI.getValueType(VecTy->getElementType());
693 if (EltVT.isFloatingPoint())
694 Op = DAG.getConstantFP(0, EltVT);
696 Op = DAG.getConstant(0, EltVT);
697 Ops.assign(NumElements, Op);
700 // Create a BUILD_VECTOR node.
701 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
702 VT, &Ops[0], Ops.size());
703 if (DisableScheduling)
704 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
706 return NodeMap[V] = Res;
709 // If this is a static alloca, generate it as the frameindex instead of
711 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
712 DenseMap<const AllocaInst*, int>::iterator SI =
713 FuncInfo.StaticAllocaMap.find(AI);
714 if (SI != FuncInfo.StaticAllocaMap.end())
715 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
718 unsigned InReg = FuncInfo.ValueMap[V];
719 assert(InReg && "Value not in map!");
721 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
722 SDValue Chain = DAG.getEntryNode();
723 SDValue Res = RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
724 if (DisableScheduling)
725 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
729 /// Get the EVTs and ArgFlags collections that represent the return type
730 /// of the given function. This does not require a DAG or a return value, and
731 /// is suitable for use before any DAGs for the function are constructed.
732 static void getReturnInfo(const Type* ReturnType,
733 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
734 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
736 SmallVectorImpl<uint64_t> *Offsets = 0) {
737 SmallVector<EVT, 4> ValueVTs;
738 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
739 unsigned NumValues = ValueVTs.size();
740 if ( NumValues == 0 ) return;
742 for (unsigned j = 0, f = NumValues; j != f; ++j) {
743 EVT VT = ValueVTs[j];
744 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
746 if (attr & Attribute::SExt)
747 ExtendKind = ISD::SIGN_EXTEND;
748 else if (attr & Attribute::ZExt)
749 ExtendKind = ISD::ZERO_EXTEND;
751 // FIXME: C calling convention requires the return type to be promoted to
752 // at least 32-bit. But this is not necessary for non-C calling
753 // conventions. The frontend should mark functions whose return values
754 // require promoting with signext or zeroext attributes.
755 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
756 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
757 if (VT.bitsLT(MinVT))
761 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
762 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
763 // 'inreg' on function refers to return value
764 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
765 if (attr & Attribute::InReg)
768 // Propagate extension type if any
769 if (attr & Attribute::SExt)
771 else if (attr & Attribute::ZExt)
774 for (unsigned i = 0; i < NumParts; ++i) {
775 OutVTs.push_back(PartVT);
776 OutFlags.push_back(Flags);
781 void SelectionDAGBuilder::visitRet(ReturnInst &I) {
782 SDValue Chain = getControlRoot();
783 SmallVector<ISD::OutputArg, 8> Outs;
784 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
786 if (!FLI.CanLowerReturn) {
787 unsigned DemoteReg = FLI.DemoteRegister;
788 const Function *F = I.getParent()->getParent();
790 // Emit a store of the return value through the virtual register.
791 // Leave Outs empty so that LowerReturn won't try to load return
792 // registers the usual way.
793 SmallVector<EVT, 1> PtrValueVTs;
794 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
797 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
798 SDValue RetOp = getValue(I.getOperand(0));
800 SmallVector<EVT, 4> ValueVTs;
801 SmallVector<uint64_t, 4> Offsets;
802 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
803 unsigned NumValues = ValueVTs.size();
805 SmallVector<SDValue, 4> Chains(NumValues);
806 EVT PtrVT = PtrValueVTs[0];
807 for (unsigned i = 0; i != NumValues; ++i) {
808 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
809 DAG.getConstant(Offsets[i], PtrVT));
811 DAG.getStore(Chain, getCurDebugLoc(),
812 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
813 Add, NULL, Offsets[i], false, 0);
815 if (DisableScheduling) {
816 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
817 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
821 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
822 MVT::Other, &Chains[0], NumValues);
824 if (DisableScheduling)
825 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
827 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
828 SmallVector<EVT, 4> ValueVTs;
829 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
830 unsigned NumValues = ValueVTs.size();
831 if (NumValues == 0) continue;
833 SDValue RetOp = getValue(I.getOperand(i));
834 for (unsigned j = 0, f = NumValues; j != f; ++j) {
835 EVT VT = ValueVTs[j];
837 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
839 const Function *F = I.getParent()->getParent();
840 if (F->paramHasAttr(0, Attribute::SExt))
841 ExtendKind = ISD::SIGN_EXTEND;
842 else if (F->paramHasAttr(0, Attribute::ZExt))
843 ExtendKind = ISD::ZERO_EXTEND;
845 // FIXME: C calling convention requires the return type to be promoted to
846 // at least 32-bit. But this is not necessary for non-C calling
847 // conventions. The frontend should mark functions whose return values
848 // require promoting with signext or zeroext attributes.
849 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
850 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
851 if (VT.bitsLT(MinVT))
855 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
856 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
857 SmallVector<SDValue, 4> Parts(NumParts);
858 getCopyToParts(DAG, getCurDebugLoc(),
859 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
860 &Parts[0], NumParts, PartVT, ExtendKind);
862 // 'inreg' on function refers to return value
863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
864 if (F->paramHasAttr(0, Attribute::InReg))
867 // Propagate extension type if any
868 if (F->paramHasAttr(0, Attribute::SExt))
870 else if (F->paramHasAttr(0, Attribute::ZExt))
873 for (unsigned i = 0; i < NumParts; ++i)
874 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
879 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
880 CallingConv::ID CallConv =
881 DAG.getMachineFunction().getFunction()->getCallingConv();
882 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
883 Outs, getCurDebugLoc(), DAG);
885 // Verify that the target's LowerReturn behaved as expected.
886 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
887 "LowerReturn didn't return a valid chain!");
889 // Update the DAG with the new chain value resulting from return lowering.
892 if (DisableScheduling)
893 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
896 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
897 /// created for it, emit nodes to copy the value into the virtual
899 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
900 if (!V->use_empty()) {
901 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
902 if (VMI != FuncInfo.ValueMap.end())
903 CopyValueToVirtualRegister(V, VMI->second);
907 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
908 /// the current basic block, add it to ValueMap now so that we'll get a
910 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
911 // No need to export constants.
912 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
915 if (FuncInfo.isExportedInst(V)) return;
917 unsigned Reg = FuncInfo.InitializeRegForValue(V);
918 CopyValueToVirtualRegister(V, Reg);
921 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
922 const BasicBlock *FromBB) {
923 // The operands of the setcc have to be in this block. We don't know
924 // how to export them from some other block.
925 if (Instruction *VI = dyn_cast<Instruction>(V)) {
926 // Can export from current BB.
927 if (VI->getParent() == FromBB)
930 // Is already exported, noop.
931 return FuncInfo.isExportedInst(V);
934 // If this is an argument, we can export it if the BB is the entry block or
935 // if it is already exported.
936 if (isa<Argument>(V)) {
937 if (FromBB == &FromBB->getParent()->getEntryBlock())
940 // Otherwise, can only export this if it is already exported.
941 return FuncInfo.isExportedInst(V);
944 // Otherwise, constants can always be exported.
948 static bool InBlock(const Value *V, const BasicBlock *BB) {
949 if (const Instruction *I = dyn_cast<Instruction>(V))
950 return I->getParent() == BB;
954 /// getFCmpCondCode - Return the ISD condition code corresponding to
955 /// the given LLVM IR floating-point condition code. This includes
956 /// consideration of global floating-point math flags.
958 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
959 ISD::CondCode FPC, FOC;
961 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
962 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
963 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
964 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
965 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
966 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
967 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
968 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
969 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
970 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
971 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
972 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
973 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
974 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
975 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
976 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
978 llvm_unreachable("Invalid FCmp predicate opcode!");
979 FOC = FPC = ISD::SETFALSE;
982 if (FiniteOnlyFPMath())
988 /// getICmpCondCode - Return the ISD condition code corresponding to
989 /// the given LLVM IR integer condition code.
991 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
993 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
994 case ICmpInst::ICMP_NE: return ISD::SETNE;
995 case ICmpInst::ICMP_SLE: return ISD::SETLE;
996 case ICmpInst::ICMP_ULE: return ISD::SETULE;
997 case ICmpInst::ICMP_SGE: return ISD::SETGE;
998 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
999 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1000 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1001 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1002 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1004 llvm_unreachable("Invalid ICmp predicate opcode!");
1009 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1010 /// This function emits a branch and is used at the leaves of an OR or an
1011 /// AND operator tree.
1014 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1015 MachineBasicBlock *TBB,
1016 MachineBasicBlock *FBB,
1017 MachineBasicBlock *CurBB) {
1018 const BasicBlock *BB = CurBB->getBasicBlock();
1020 // If the leaf of the tree is a comparison, merge the condition into
1022 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1023 // The operands of the cmp have to be in this block. We don't know
1024 // how to export them from some other block. If this is the first block
1025 // of the sequence, no exporting is needed.
1026 if (CurBB == CurMBB ||
1027 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1028 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1029 ISD::CondCode Condition;
1030 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1031 Condition = getICmpCondCode(IC->getPredicate());
1032 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1033 Condition = getFCmpCondCode(FC->getPredicate());
1035 Condition = ISD::SETEQ; // silence warning.
1036 llvm_unreachable("Unknown compare instruction");
1039 CaseBlock CB(Condition, BOp->getOperand(0),
1040 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1041 SwitchCases.push_back(CB);
1046 // Create a CaseBlock record representing this branch.
1047 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1048 NULL, TBB, FBB, CurBB);
1049 SwitchCases.push_back(CB);
1052 /// FindMergedConditions - If Cond is an expression like
1053 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1054 MachineBasicBlock *TBB,
1055 MachineBasicBlock *FBB,
1056 MachineBasicBlock *CurBB,
1058 // If this node is not part of the or/and tree, emit it as a branch.
1059 Instruction *BOp = dyn_cast<Instruction>(Cond);
1060 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1061 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1062 BOp->getParent() != CurBB->getBasicBlock() ||
1063 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1064 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1065 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1069 // Create TmpBB after CurBB.
1070 MachineFunction::iterator BBI = CurBB;
1071 MachineFunction &MF = DAG.getMachineFunction();
1072 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1073 CurBB->getParent()->insert(++BBI, TmpBB);
1075 if (Opc == Instruction::Or) {
1076 // Codegen X | Y as:
1084 // Emit the LHS condition.
1085 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1087 // Emit the RHS condition into TmpBB.
1088 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1090 assert(Opc == Instruction::And && "Unknown merge op!");
1091 // Codegen X & Y as:
1098 // This requires creation of TmpBB after CurBB.
1100 // Emit the LHS condition.
1101 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1103 // Emit the RHS condition into TmpBB.
1104 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1108 /// If the set of cases should be emitted as a series of branches, return true.
1109 /// If we should emit this as a bunch of and/or'd together conditions, return
1112 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1113 if (Cases.size() != 2) return true;
1115 // If this is two comparisons of the same values or'd or and'd together, they
1116 // will get folded into a single comparison, so don't emit two blocks.
1117 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1118 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1119 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1120 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1127 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1128 // Update machine-CFG edges.
1129 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1131 // Figure out which block is immediately after the current one.
1132 MachineBasicBlock *NextBlock = 0;
1133 MachineFunction::iterator BBI = CurMBB;
1134 if (++BBI != FuncInfo.MF->end())
1137 if (I.isUnconditional()) {
1138 // Update machine-CFG edges.
1139 CurMBB->addSuccessor(Succ0MBB);
1141 // If this is not a fall-through branch, emit the branch.
1142 if (Succ0MBB != NextBlock) {
1143 SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(),
1144 MVT::Other, getControlRoot(),
1145 DAG.getBasicBlock(Succ0MBB));
1148 if (DisableScheduling)
1149 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
1155 // If this condition is one of the special cases we handle, do special stuff
1157 Value *CondVal = I.getCondition();
1158 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1160 // If this is a series of conditions that are or'd or and'd together, emit
1161 // this as a sequence of branches instead of setcc's with and/or operations.
1162 // For example, instead of something like:
1175 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1176 if (BOp->hasOneUse() &&
1177 (BOp->getOpcode() == Instruction::And ||
1178 BOp->getOpcode() == Instruction::Or)) {
1179 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1180 // If the compares in later blocks need to use values not currently
1181 // exported from this block, export them now. This block should always
1182 // be the first entry.
1183 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1185 // Allow some cases to be rejected.
1186 if (ShouldEmitAsBranches(SwitchCases)) {
1187 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1188 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1189 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1192 // Emit the branch for this block.
1193 visitSwitchCase(SwitchCases[0]);
1194 SwitchCases.erase(SwitchCases.begin());
1198 // Okay, we decided not to do this, remove any inserted MBB's and clear
1200 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1201 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1203 SwitchCases.clear();
1207 // Create a CaseBlock record representing this branch.
1208 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1209 NULL, Succ0MBB, Succ1MBB, CurMBB);
1211 // Use visitSwitchCase to actually insert the fast branch sequence for this
1213 visitSwitchCase(CB);
1216 /// visitSwitchCase - Emits the necessary code to represent a single node in
1217 /// the binary search tree resulting from lowering a switch instruction.
1218 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1220 SDValue CondLHS = getValue(CB.CmpLHS);
1221 DebugLoc dl = getCurDebugLoc();
1223 // Build the setcc now.
1224 if (CB.CmpMHS == NULL) {
1225 // Fold "(X == true)" to X and "(X == false)" to !X to
1226 // handle common cases produced by branch lowering.
1227 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1228 CB.CC == ISD::SETEQ)
1230 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1231 CB.CC == ISD::SETEQ) {
1232 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1233 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1235 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1237 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1239 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1240 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1242 SDValue CmpOp = getValue(CB.CmpMHS);
1243 EVT VT = CmpOp.getValueType();
1245 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1246 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1249 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1250 VT, CmpOp, DAG.getConstant(Low, VT));
1251 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1252 DAG.getConstant(High-Low, VT), ISD::SETULE);
1256 if (DisableScheduling)
1257 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1259 // Update successor info
1260 CurMBB->addSuccessor(CB.TrueBB);
1261 CurMBB->addSuccessor(CB.FalseBB);
1263 // Set NextBlock to be the MBB immediately after the current one, if any.
1264 // This is used to avoid emitting unnecessary branches to the next block.
1265 MachineBasicBlock *NextBlock = 0;
1266 MachineFunction::iterator BBI = CurMBB;
1267 if (++BBI != FuncInfo.MF->end())
1270 // If the lhs block is the next block, invert the condition so that we can
1271 // fall through to the lhs instead of the rhs block.
1272 if (CB.TrueBB == NextBlock) {
1273 std::swap(CB.TrueBB, CB.FalseBB);
1274 SDValue True = DAG.getConstant(1, Cond.getValueType());
1275 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1277 if (DisableScheduling)
1278 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1281 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1282 MVT::Other, getControlRoot(), Cond,
1283 DAG.getBasicBlock(CB.TrueBB));
1285 if (DisableScheduling)
1286 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1288 // If the branch was constant folded, fix up the CFG.
1289 if (BrCond.getOpcode() == ISD::BR) {
1290 CurMBB->removeSuccessor(CB.FalseBB);
1292 // Otherwise, go ahead and insert the false branch.
1293 if (BrCond == getControlRoot())
1294 CurMBB->removeSuccessor(CB.TrueBB);
1296 if (CB.FalseBB != NextBlock) {
1297 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1298 DAG.getBasicBlock(CB.FalseBB));
1300 if (DisableScheduling)
1301 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1305 DAG.setRoot(BrCond);
1308 /// visitJumpTable - Emit JumpTable node in the current MBB
1309 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1310 // Emit the code for the jump table
1311 assert(JT.Reg != -1U && "Should lower JT Header first!");
1312 EVT PTy = TLI.getPointerTy();
1313 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1315 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1316 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1317 MVT::Other, Index.getValue(1),
1319 DAG.setRoot(BrJumpTable);
1321 if (DisableScheduling) {
1322 DAG.AssignOrdering(Index.getNode(), SDNodeOrder);
1323 DAG.AssignOrdering(Table.getNode(), SDNodeOrder);
1324 DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder);
1328 /// visitJumpTableHeader - This function emits necessary code to produce index
1329 /// in the JumpTable from switch case.
1330 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1331 JumpTableHeader &JTH) {
1332 // Subtract the lowest switch case value from the value being switched on and
1333 // conditional branch to default mbb if the result is greater than the
1334 // difference between smallest and largest cases.
1335 SDValue SwitchOp = getValue(JTH.SValue);
1336 EVT VT = SwitchOp.getValueType();
1337 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1338 DAG.getConstant(JTH.First, VT));
1340 // The SDNode we just created, which holds the value being switched on minus
1341 // the the smallest case value, needs to be copied to a virtual register so it
1342 // can be used as an index into the jump table in a subsequent basic block.
1343 // This value may be smaller or larger than the target's pointer type, and
1344 // therefore require extension or truncating.
1345 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1347 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1348 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1349 JumpTableReg, SwitchOp);
1350 JT.Reg = JumpTableReg;
1352 // Emit the range check for the jump table, and branch to the default block
1353 // for the switch statement if the value being switched on exceeds the largest
1354 // case in the switch.
1355 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1356 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1357 DAG.getConstant(JTH.Last-JTH.First,VT),
1360 if (DisableScheduling) {
1361 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1362 DAG.AssignOrdering(SwitchOp.getNode(), SDNodeOrder);
1363 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1364 DAG.AssignOrdering(CMP.getNode(), SDNodeOrder);
1367 // Set NextBlock to be the MBB immediately after the current one, if any.
1368 // This is used to avoid emitting unnecessary branches to the next block.
1369 MachineBasicBlock *NextBlock = 0;
1370 MachineFunction::iterator BBI = CurMBB;
1372 if (++BBI != FuncInfo.MF->end())
1375 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1376 MVT::Other, CopyTo, CMP,
1377 DAG.getBasicBlock(JT.Default));
1379 if (DisableScheduling)
1380 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1382 if (JT.MBB != NextBlock) {
1383 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1384 DAG.getBasicBlock(JT.MBB));
1386 if (DisableScheduling)
1387 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1390 DAG.setRoot(BrCond);
1393 /// visitBitTestHeader - This function emits necessary code to produce value
1394 /// suitable for "bit tests"
1395 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1396 // Subtract the minimum value
1397 SDValue SwitchOp = getValue(B.SValue);
1398 EVT VT = SwitchOp.getValueType();
1399 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1400 DAG.getConstant(B.First, VT));
1403 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1404 TLI.getSetCCResultType(Sub.getValueType()),
1405 Sub, DAG.getConstant(B.Range, VT),
1408 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1409 TLI.getPointerTy());
1411 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1412 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1415 if (DisableScheduling) {
1416 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1417 DAG.AssignOrdering(RangeCmp.getNode(), SDNodeOrder);
1418 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1419 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1422 // Set NextBlock to be the MBB immediately after the current one, if any.
1423 // This is used to avoid emitting unnecessary branches to the next block.
1424 MachineBasicBlock *NextBlock = 0;
1425 MachineFunction::iterator BBI = CurMBB;
1426 if (++BBI != FuncInfo.MF->end())
1429 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1431 CurMBB->addSuccessor(B.Default);
1432 CurMBB->addSuccessor(MBB);
1434 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1435 MVT::Other, CopyTo, RangeCmp,
1436 DAG.getBasicBlock(B.Default));
1438 if (DisableScheduling)
1439 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1441 if (MBB != NextBlock) {
1442 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1443 DAG.getBasicBlock(MBB));
1445 if (DisableScheduling)
1446 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1449 DAG.setRoot(BrRange);
1452 /// visitBitTestCase - this function produces one "bit test"
1453 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1456 // Make desired shift
1457 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1458 TLI.getPointerTy());
1459 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1461 DAG.getConstant(1, TLI.getPointerTy()),
1464 // Emit bit tests and jumps
1465 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1466 TLI.getPointerTy(), SwitchVal,
1467 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1468 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1469 TLI.getSetCCResultType(AndOp.getValueType()),
1470 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1473 if (DisableScheduling) {
1474 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1475 DAG.AssignOrdering(SwitchVal.getNode(), SDNodeOrder);
1476 DAG.AssignOrdering(AndOp.getNode(), SDNodeOrder);
1477 DAG.AssignOrdering(AndCmp.getNode(), SDNodeOrder);
1480 CurMBB->addSuccessor(B.TargetBB);
1481 CurMBB->addSuccessor(NextMBB);
1483 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1484 MVT::Other, getControlRoot(),
1485 AndCmp, DAG.getBasicBlock(B.TargetBB));
1487 if (DisableScheduling)
1488 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1490 // Set NextBlock to be the MBB immediately after the current one, if any.
1491 // This is used to avoid emitting unnecessary branches to the next block.
1492 MachineBasicBlock *NextBlock = 0;
1493 MachineFunction::iterator BBI = CurMBB;
1494 if (++BBI != FuncInfo.MF->end())
1497 if (NextMBB != NextBlock) {
1498 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1499 DAG.getBasicBlock(NextMBB));
1501 if (DisableScheduling)
1502 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1508 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1509 // Retrieve successors.
1510 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1511 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1513 const Value *Callee(I.getCalledValue());
1514 if (isa<InlineAsm>(Callee))
1517 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1519 // If the value of the invoke is used outside of its defining block, make it
1520 // available as a virtual register.
1521 CopyToExportRegsIfNeeded(&I);
1523 // Update successor info
1524 CurMBB->addSuccessor(Return);
1525 CurMBB->addSuccessor(LandingPad);
1527 // Drop into normal successor.
1528 SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(),
1529 MVT::Other, getControlRoot(),
1530 DAG.getBasicBlock(Return));
1531 DAG.setRoot(Branch);
1533 if (DisableScheduling)
1534 DAG.AssignOrdering(Branch.getNode(), SDNodeOrder);
1537 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1540 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1541 /// small case ranges).
1542 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1543 CaseRecVector& WorkList,
1545 MachineBasicBlock* Default) {
1546 Case& BackCase = *(CR.Range.second-1);
1548 // Size is the number of Cases represented by this range.
1549 size_t Size = CR.Range.second - CR.Range.first;
1553 // Get the MachineFunction which holds the current MBB. This is used when
1554 // inserting any additional MBBs necessary to represent the switch.
1555 MachineFunction *CurMF = FuncInfo.MF;
1557 // Figure out which block is immediately after the current one.
1558 MachineBasicBlock *NextBlock = 0;
1559 MachineFunction::iterator BBI = CR.CaseBB;
1561 if (++BBI != FuncInfo.MF->end())
1564 // TODO: If any two of the cases has the same destination, and if one value
1565 // is the same as the other, but has one bit unset that the other has set,
1566 // use bit manipulation to do two compares at once. For example:
1567 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1569 // Rearrange the case blocks so that the last one falls through if possible.
1570 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1571 // The last case block won't fall through into 'NextBlock' if we emit the
1572 // branches in this order. See if rearranging a case value would help.
1573 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1574 if (I->BB == NextBlock) {
1575 std::swap(*I, BackCase);
1581 // Create a CaseBlock record representing a conditional branch to
1582 // the Case's target mbb if the value being switched on SV is equal
1584 MachineBasicBlock *CurBlock = CR.CaseBB;
1585 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1586 MachineBasicBlock *FallThrough;
1588 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1589 CurMF->insert(BBI, FallThrough);
1591 // Put SV in a virtual register to make it available from the new blocks.
1592 ExportFromCurrentBlock(SV);
1594 // If the last case doesn't match, go to the default block.
1595 FallThrough = Default;
1598 Value *RHS, *LHS, *MHS;
1600 if (I->High == I->Low) {
1601 // This is just small small case range :) containing exactly 1 case
1603 LHS = SV; RHS = I->High; MHS = NULL;
1606 LHS = I->Low; MHS = SV; RHS = I->High;
1608 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1610 // If emitting the first comparison, just call visitSwitchCase to emit the
1611 // code into the current block. Otherwise, push the CaseBlock onto the
1612 // vector to be later processed by SDISel, and insert the node's MBB
1613 // before the next MBB.
1614 if (CurBlock == CurMBB)
1615 visitSwitchCase(CB);
1617 SwitchCases.push_back(CB);
1619 CurBlock = FallThrough;
1625 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1626 return !DisableJumpTables &&
1627 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1628 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1631 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1632 APInt LastExt(Last), FirstExt(First);
1633 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1634 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1635 return (LastExt - FirstExt + 1ULL);
1638 /// handleJTSwitchCase - Emit jumptable for current switch case range
1639 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1640 CaseRecVector& WorkList,
1642 MachineBasicBlock* Default) {
1643 Case& FrontCase = *CR.Range.first;
1644 Case& BackCase = *(CR.Range.second-1);
1646 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1647 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1649 APInt TSize(First.getBitWidth(), 0);
1650 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1654 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1657 APInt Range = ComputeRange(First, Last);
1658 double Density = TSize.roundToDouble() / Range.roundToDouble();
1662 DEBUG(errs() << "Lowering jump table\n"
1663 << "First entry: " << First << ". Last entry: " << Last << '\n'
1664 << "Range: " << Range
1665 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1667 // Get the MachineFunction which holds the current MBB. This is used when
1668 // inserting any additional MBBs necessary to represent the switch.
1669 MachineFunction *CurMF = FuncInfo.MF;
1671 // Figure out which block is immediately after the current one.
1672 MachineFunction::iterator BBI = CR.CaseBB;
1675 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1677 // Create a new basic block to hold the code for loading the address
1678 // of the jump table, and jumping to it. Update successor information;
1679 // we will either branch to the default case for the switch, or the jump
1681 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1682 CurMF->insert(BBI, JumpTableBB);
1683 CR.CaseBB->addSuccessor(Default);
1684 CR.CaseBB->addSuccessor(JumpTableBB);
1686 // Build a vector of destination BBs, corresponding to each target
1687 // of the jump table. If the value of the jump table slot corresponds to
1688 // a case statement, push the case's BB onto the vector, otherwise, push
1690 std::vector<MachineBasicBlock*> DestBBs;
1692 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1693 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1694 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1696 if (Low.sle(TEI) && TEI.sle(High)) {
1697 DestBBs.push_back(I->BB);
1701 DestBBs.push_back(Default);
1705 // Update successor info. Add one edge to each unique successor.
1706 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1707 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1708 E = DestBBs.end(); I != E; ++I) {
1709 if (!SuccsHandled[(*I)->getNumber()]) {
1710 SuccsHandled[(*I)->getNumber()] = true;
1711 JumpTableBB->addSuccessor(*I);
1715 // Create a jump table index for this jump table, or return an existing
1717 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1719 // Set the jump table information so that we can codegen it as a second
1720 // MachineBasicBlock
1721 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1722 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1723 if (CR.CaseBB == CurMBB)
1724 visitJumpTableHeader(JT, JTH);
1726 JTCases.push_back(JumpTableBlock(JTH, JT));
1731 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1733 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1734 CaseRecVector& WorkList,
1736 MachineBasicBlock* Default) {
1737 // Get the MachineFunction which holds the current MBB. This is used when
1738 // inserting any additional MBBs necessary to represent the switch.
1739 MachineFunction *CurMF = FuncInfo.MF;
1741 // Figure out which block is immediately after the current one.
1742 MachineFunction::iterator BBI = CR.CaseBB;
1745 Case& FrontCase = *CR.Range.first;
1746 Case& BackCase = *(CR.Range.second-1);
1747 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1749 // Size is the number of Cases represented by this range.
1750 unsigned Size = CR.Range.second - CR.Range.first;
1752 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1753 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1755 CaseItr Pivot = CR.Range.first + Size/2;
1757 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1758 // (heuristically) allow us to emit JumpTable's later.
1759 APInt TSize(First.getBitWidth(), 0);
1760 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1764 APInt LSize = FrontCase.size();
1765 APInt RSize = TSize-LSize;
1766 DEBUG(errs() << "Selecting best pivot: \n"
1767 << "First: " << First << ", Last: " << Last <<'\n'
1768 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1769 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1771 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1772 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1773 APInt Range = ComputeRange(LEnd, RBegin);
1774 assert((Range - 2ULL).isNonNegative() &&
1775 "Invalid case distance");
1776 double LDensity = (double)LSize.roundToDouble() /
1777 (LEnd - First + 1ULL).roundToDouble();
1778 double RDensity = (double)RSize.roundToDouble() /
1779 (Last - RBegin + 1ULL).roundToDouble();
1780 double Metric = Range.logBase2()*(LDensity+RDensity);
1781 // Should always split in some non-trivial place
1782 DEBUG(errs() <<"=>Step\n"
1783 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1784 << "LDensity: " << LDensity
1785 << ", RDensity: " << RDensity << '\n'
1786 << "Metric: " << Metric << '\n');
1787 if (FMetric < Metric) {
1790 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1796 if (areJTsAllowed(TLI)) {
1797 // If our case is dense we *really* should handle it earlier!
1798 assert((FMetric > 0) && "Should handle dense range earlier!");
1800 Pivot = CR.Range.first + Size/2;
1803 CaseRange LHSR(CR.Range.first, Pivot);
1804 CaseRange RHSR(Pivot, CR.Range.second);
1805 Constant *C = Pivot->Low;
1806 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1808 // We know that we branch to the LHS if the Value being switched on is
1809 // less than the Pivot value, C. We use this to optimize our binary
1810 // tree a bit, by recognizing that if SV is greater than or equal to the
1811 // LHS's Case Value, and that Case Value is exactly one less than the
1812 // Pivot's Value, then we can branch directly to the LHS's Target,
1813 // rather than creating a leaf node for it.
1814 if ((LHSR.second - LHSR.first) == 1 &&
1815 LHSR.first->High == CR.GE &&
1816 cast<ConstantInt>(C)->getValue() ==
1817 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1818 TrueBB = LHSR.first->BB;
1820 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1821 CurMF->insert(BBI, TrueBB);
1822 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1824 // Put SV in a virtual register to make it available from the new blocks.
1825 ExportFromCurrentBlock(SV);
1828 // Similar to the optimization above, if the Value being switched on is
1829 // known to be less than the Constant CR.LT, and the current Case Value
1830 // is CR.LT - 1, then we can branch directly to the target block for
1831 // the current Case Value, rather than emitting a RHS leaf node for it.
1832 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1833 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1834 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1835 FalseBB = RHSR.first->BB;
1837 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1838 CurMF->insert(BBI, FalseBB);
1839 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1841 // Put SV in a virtual register to make it available from the new blocks.
1842 ExportFromCurrentBlock(SV);
1845 // Create a CaseBlock record representing a conditional branch to
1846 // the LHS node if the value being switched on SV is less than C.
1847 // Otherwise, branch to LHS.
1848 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1850 if (CR.CaseBB == CurMBB)
1851 visitSwitchCase(CB);
1853 SwitchCases.push_back(CB);
1858 /// handleBitTestsSwitchCase - if current case range has few destination and
1859 /// range span less, than machine word bitwidth, encode case range into series
1860 /// of masks and emit bit tests with these masks.
1861 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1862 CaseRecVector& WorkList,
1864 MachineBasicBlock* Default){
1865 EVT PTy = TLI.getPointerTy();
1866 unsigned IntPtrBits = PTy.getSizeInBits();
1868 Case& FrontCase = *CR.Range.first;
1869 Case& BackCase = *(CR.Range.second-1);
1871 // Get the MachineFunction which holds the current MBB. This is used when
1872 // inserting any additional MBBs necessary to represent the switch.
1873 MachineFunction *CurMF = FuncInfo.MF;
1875 // If target does not have legal shift left, do not emit bit tests at all.
1876 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1880 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1882 // Single case counts one, case range - two.
1883 numCmps += (I->Low == I->High ? 1 : 2);
1886 // Count unique destinations
1887 SmallSet<MachineBasicBlock*, 4> Dests;
1888 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1889 Dests.insert(I->BB);
1890 if (Dests.size() > 3)
1891 // Don't bother the code below, if there are too much unique destinations
1894 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1895 << "Total number of comparisons: " << numCmps << '\n');
1897 // Compute span of values.
1898 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1899 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1900 APInt cmpRange = maxValue - minValue;
1902 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1903 << "Low bound: " << minValue << '\n'
1904 << "High bound: " << maxValue << '\n');
1906 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1907 (!(Dests.size() == 1 && numCmps >= 3) &&
1908 !(Dests.size() == 2 && numCmps >= 5) &&
1909 !(Dests.size() >= 3 && numCmps >= 6)))
1912 DEBUG(errs() << "Emitting bit tests\n");
1913 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1915 // Optimize the case where all the case values fit in a
1916 // word without having to subtract minValue. In this case,
1917 // we can optimize away the subtraction.
1918 if (minValue.isNonNegative() &&
1919 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1920 cmpRange = maxValue;
1922 lowBound = minValue;
1925 CaseBitsVector CasesBits;
1926 unsigned i, count = 0;
1928 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1929 MachineBasicBlock* Dest = I->BB;
1930 for (i = 0; i < count; ++i)
1931 if (Dest == CasesBits[i].BB)
1935 assert((count < 3) && "Too much destinations to test!");
1936 CasesBits.push_back(CaseBits(0, Dest, 0));
1940 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1941 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1943 uint64_t lo = (lowValue - lowBound).getZExtValue();
1944 uint64_t hi = (highValue - lowBound).getZExtValue();
1946 for (uint64_t j = lo; j <= hi; j++) {
1947 CasesBits[i].Mask |= 1ULL << j;
1948 CasesBits[i].Bits++;
1952 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1956 // Figure out which block is immediately after the current one.
1957 MachineFunction::iterator BBI = CR.CaseBB;
1960 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1962 DEBUG(errs() << "Cases:\n");
1963 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1964 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1965 << ", Bits: " << CasesBits[i].Bits
1966 << ", BB: " << CasesBits[i].BB << '\n');
1968 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1969 CurMF->insert(BBI, CaseBB);
1970 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1974 // Put SV in a virtual register to make it available from the new blocks.
1975 ExportFromCurrentBlock(SV);
1978 BitTestBlock BTB(lowBound, cmpRange, SV,
1979 -1U, (CR.CaseBB == CurMBB),
1980 CR.CaseBB, Default, BTC);
1982 if (CR.CaseBB == CurMBB)
1983 visitBitTestHeader(BTB);
1985 BitTestCases.push_back(BTB);
1990 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1991 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1992 const SwitchInst& SI) {
1995 // Start with "simple" cases
1996 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1997 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1998 Cases.push_back(Case(SI.getSuccessorValue(i),
1999 SI.getSuccessorValue(i),
2002 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2004 // Merge case into clusters
2005 if (Cases.size() >= 2)
2006 // Must recompute end() each iteration because it may be
2007 // invalidated by erase if we hold on to it
2008 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2009 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2010 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2011 MachineBasicBlock* nextBB = J->BB;
2012 MachineBasicBlock* currentBB = I->BB;
2014 // If the two neighboring cases go to the same destination, merge them
2015 // into a single case.
2016 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2024 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2025 if (I->Low != I->High)
2026 // A range counts double, since it requires two compares.
2033 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
2034 // Figure out which block is immediately after the current one.
2035 MachineBasicBlock *NextBlock = 0;
2036 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2038 // If there is only the default destination, branch to it if it is not the
2039 // next basic block. Otherwise, just fall through.
2040 if (SI.getNumOperands() == 2) {
2041 // Update machine-CFG edges.
2043 // If this is not a fall-through branch, emit the branch.
2044 CurMBB->addSuccessor(Default);
2045 if (Default != NextBlock) {
2046 SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(),
2047 MVT::Other, getControlRoot(),
2048 DAG.getBasicBlock(Default));
2051 if (DisableScheduling)
2052 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2058 // If there are any non-default case statements, create a vector of Cases
2059 // representing each one, and sort the vector so that we can efficiently
2060 // create a binary search tree from them.
2062 size_t numCmps = Clusterify(Cases, SI);
2063 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2064 << ". Total compares: " << numCmps << '\n');
2067 // Get the Value to be switched on and default basic blocks, which will be
2068 // inserted into CaseBlock records, representing basic blocks in the binary
2070 Value *SV = SI.getOperand(0);
2072 // Push the initial CaseRec onto the worklist
2073 CaseRecVector WorkList;
2074 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2076 while (!WorkList.empty()) {
2077 // Grab a record representing a case range to process off the worklist
2078 CaseRec CR = WorkList.back();
2079 WorkList.pop_back();
2081 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2084 // If the range has few cases (two or less) emit a series of specific
2086 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2089 // If the switch has more than 5 blocks, and at least 40% dense, and the
2090 // target supports indirect branches, then emit a jump table rather than
2091 // lowering the switch to a binary tree of conditional branches.
2092 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2095 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2096 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2097 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2101 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2102 // Update machine-CFG edges.
2103 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2104 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2106 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2107 MVT::Other, getControlRoot(),
2108 getValue(I.getAddress()));
2111 if (DisableScheduling)
2112 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2115 void SelectionDAGBuilder::visitFSub(User &I) {
2116 // -0.0 - X --> fneg
2117 const Type *Ty = I.getType();
2118 if (isa<VectorType>(Ty)) {
2119 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2120 const VectorType *DestTy = cast<VectorType>(I.getType());
2121 const Type *ElTy = DestTy->getElementType();
2122 unsigned VL = DestTy->getNumElements();
2123 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2124 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2126 SDValue Op2 = getValue(I.getOperand(1));
2127 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2128 Op2.getValueType(), Op2);
2131 if (DisableScheduling)
2132 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2139 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2140 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2141 SDValue Op2 = getValue(I.getOperand(1));
2142 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2143 Op2.getValueType(), Op2);
2146 if (DisableScheduling)
2147 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2152 visitBinary(I, ISD::FSUB);
2155 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2156 SDValue Op1 = getValue(I.getOperand(0));
2157 SDValue Op2 = getValue(I.getOperand(1));
2158 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(),
2159 Op1.getValueType(), Op1, Op2);
2162 if (DisableScheduling)
2163 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2166 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2167 SDValue Op1 = getValue(I.getOperand(0));
2168 SDValue Op2 = getValue(I.getOperand(1));
2169 if (!isa<VectorType>(I.getType()) &&
2170 Op2.getValueType() != TLI.getShiftAmountTy()) {
2171 // If the operand is smaller than the shift count type, promote it.
2172 EVT PTy = TLI.getPointerTy();
2173 EVT STy = TLI.getShiftAmountTy();
2174 if (STy.bitsGT(Op2.getValueType()))
2175 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2176 TLI.getShiftAmountTy(), Op2);
2177 // If the operand is larger than the shift count type but the shift
2178 // count type has enough bits to represent any shift value, truncate
2179 // it now. This is a common case and it exposes the truncate to
2180 // optimization early.
2181 else if (STy.getSizeInBits() >=
2182 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2183 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2184 TLI.getShiftAmountTy(), Op2);
2185 // Otherwise we'll need to temporarily settle for some other
2186 // convenient type; type legalization will make adjustments as
2188 else if (PTy.bitsLT(Op2.getValueType()))
2189 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2190 TLI.getPointerTy(), Op2);
2191 else if (PTy.bitsGT(Op2.getValueType()))
2192 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2193 TLI.getPointerTy(), Op2);
2196 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(),
2197 Op1.getValueType(), Op1, Op2);
2200 if (DisableScheduling) {
2201 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
2202 DAG.AssignOrdering(Op2.getNode(), SDNodeOrder);
2203 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2207 void SelectionDAGBuilder::visitICmp(User &I) {
2208 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2209 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2210 predicate = IC->getPredicate();
2211 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2212 predicate = ICmpInst::Predicate(IC->getPredicate());
2213 SDValue Op1 = getValue(I.getOperand(0));
2214 SDValue Op2 = getValue(I.getOperand(1));
2215 ISD::CondCode Opcode = getICmpCondCode(predicate);
2217 EVT DestVT = TLI.getValueType(I.getType());
2218 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode);
2221 if (DisableScheduling)
2222 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2225 void SelectionDAGBuilder::visitFCmp(User &I) {
2226 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2227 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2228 predicate = FC->getPredicate();
2229 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2230 predicate = FCmpInst::Predicate(FC->getPredicate());
2231 SDValue Op1 = getValue(I.getOperand(0));
2232 SDValue Op2 = getValue(I.getOperand(1));
2233 ISD::CondCode Condition = getFCmpCondCode(predicate);
2234 EVT DestVT = TLI.getValueType(I.getType());
2235 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition);
2238 if (DisableScheduling)
2239 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2242 void SelectionDAGBuilder::visitSelect(User &I) {
2243 SmallVector<EVT, 4> ValueVTs;
2244 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2245 unsigned NumValues = ValueVTs.size();
2246 if (NumValues == 0) return;
2248 SmallVector<SDValue, 4> Values(NumValues);
2249 SDValue Cond = getValue(I.getOperand(0));
2250 SDValue TrueVal = getValue(I.getOperand(1));
2251 SDValue FalseVal = getValue(I.getOperand(2));
2253 for (unsigned i = 0; i != NumValues; ++i) {
2254 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2255 TrueVal.getNode()->getValueType(i), Cond,
2256 SDValue(TrueVal.getNode(),
2257 TrueVal.getResNo() + i),
2258 SDValue(FalseVal.getNode(),
2259 FalseVal.getResNo() + i));
2261 if (DisableScheduling)
2262 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder);
2265 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2266 DAG.getVTList(&ValueVTs[0], NumValues),
2267 &Values[0], NumValues);
2270 if (DisableScheduling)
2271 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2274 void SelectionDAGBuilder::visitTrunc(User &I) {
2275 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2276 SDValue N = getValue(I.getOperand(0));
2277 EVT DestVT = TLI.getValueType(I.getType());
2278 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2281 if (DisableScheduling)
2282 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2285 void SelectionDAGBuilder::visitZExt(User &I) {
2286 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2287 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2288 SDValue N = getValue(I.getOperand(0));
2289 EVT DestVT = TLI.getValueType(I.getType());
2290 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2293 if (DisableScheduling)
2294 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2297 void SelectionDAGBuilder::visitSExt(User &I) {
2298 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2299 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2300 SDValue N = getValue(I.getOperand(0));
2301 EVT DestVT = TLI.getValueType(I.getType());
2302 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N);
2305 if (DisableScheduling)
2306 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2309 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2310 // FPTrunc is never a no-op cast, no need to check
2311 SDValue N = getValue(I.getOperand(0));
2312 EVT DestVT = TLI.getValueType(I.getType());
2313 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2314 DestVT, N, DAG.getIntPtrConstant(0));
2317 if (DisableScheduling)
2318 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2321 void SelectionDAGBuilder::visitFPExt(User &I){
2322 // FPTrunc is never a no-op cast, no need to check
2323 SDValue N = getValue(I.getOperand(0));
2324 EVT DestVT = TLI.getValueType(I.getType());
2325 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N);
2328 if (DisableScheduling)
2329 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2332 void SelectionDAGBuilder::visitFPToUI(User &I) {
2333 // FPToUI is never a no-op cast, no need to check
2334 SDValue N = getValue(I.getOperand(0));
2335 EVT DestVT = TLI.getValueType(I.getType());
2336 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N);
2339 if (DisableScheduling)
2340 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2343 void SelectionDAGBuilder::visitFPToSI(User &I) {
2344 // FPToSI is never a no-op cast, no need to check
2345 SDValue N = getValue(I.getOperand(0));
2346 EVT DestVT = TLI.getValueType(I.getType());
2347 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N);
2350 if (DisableScheduling)
2351 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2354 void SelectionDAGBuilder::visitUIToFP(User &I) {
2355 // UIToFP is never a no-op cast, no need to check
2356 SDValue N = getValue(I.getOperand(0));
2357 EVT DestVT = TLI.getValueType(I.getType());
2358 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N);
2361 if (DisableScheduling)
2362 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2365 void SelectionDAGBuilder::visitSIToFP(User &I){
2366 // SIToFP is never a no-op cast, no need to check
2367 SDValue N = getValue(I.getOperand(0));
2368 EVT DestVT = TLI.getValueType(I.getType());
2369 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N);
2372 if (DisableScheduling)
2373 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2376 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2377 // What to do depends on the size of the integer and the size of the pointer.
2378 // We can either truncate, zero extend, or no-op, accordingly.
2379 SDValue N = getValue(I.getOperand(0));
2380 EVT SrcVT = N.getValueType();
2381 EVT DestVT = TLI.getValueType(I.getType());
2382 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2385 if (DisableScheduling)
2386 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2389 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2390 // What to do depends on the size of the integer and the size of the pointer.
2391 // We can either truncate, zero extend, or no-op, accordingly.
2392 SDValue N = getValue(I.getOperand(0));
2393 EVT SrcVT = N.getValueType();
2394 EVT DestVT = TLI.getValueType(I.getType());
2395 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2398 if (DisableScheduling)
2399 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2402 void SelectionDAGBuilder::visitBitCast(User &I) {
2403 SDValue N = getValue(I.getOperand(0));
2404 EVT DestVT = TLI.getValueType(I.getType());
2406 // BitCast assures us that source and destination are the same size so this is
2407 // either a BIT_CONVERT or a no-op.
2408 if (DestVT != N.getValueType()) {
2409 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2410 DestVT, N); // convert types.
2413 if (DisableScheduling)
2414 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2416 setValue(&I, N); // noop cast.
2420 void SelectionDAGBuilder::visitInsertElement(User &I) {
2421 SDValue InVec = getValue(I.getOperand(0));
2422 SDValue InVal = getValue(I.getOperand(1));
2423 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2425 getValue(I.getOperand(2)));
2426 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2427 TLI.getValueType(I.getType()),
2428 InVec, InVal, InIdx);
2431 if (DisableScheduling) {
2432 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2433 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2437 void SelectionDAGBuilder::visitExtractElement(User &I) {
2438 SDValue InVec = getValue(I.getOperand(0));
2439 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2441 getValue(I.getOperand(1)));
2442 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2443 TLI.getValueType(I.getType()), InVec, InIdx);
2446 if (DisableScheduling) {
2447 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2448 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2453 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2454 // from SIndx and increasing to the element length (undefs are allowed).
2455 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2456 unsigned MaskNumElts = Mask.size();
2457 for (unsigned i = 0; i != MaskNumElts; ++i)
2458 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2463 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2464 SmallVector<int, 8> Mask;
2465 SDValue Src1 = getValue(I.getOperand(0));
2466 SDValue Src2 = getValue(I.getOperand(1));
2468 // Convert the ConstantVector mask operand into an array of ints, with -1
2469 // representing undef values.
2470 SmallVector<Constant*, 8> MaskElts;
2471 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2473 unsigned MaskNumElts = MaskElts.size();
2474 for (unsigned i = 0; i != MaskNumElts; ++i) {
2475 if (isa<UndefValue>(MaskElts[i]))
2478 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2481 EVT VT = TLI.getValueType(I.getType());
2482 EVT SrcVT = Src1.getValueType();
2483 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2485 if (SrcNumElts == MaskNumElts) {
2486 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2490 if (DisableScheduling)
2491 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2496 // Normalize the shuffle vector since mask and vector length don't match.
2497 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2498 // Mask is longer than the source vectors and is a multiple of the source
2499 // vectors. We can use concatenate vector to make the mask and vectors
2501 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2502 // The shuffle is concatenating two vectors together.
2503 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2507 if (DisableScheduling)
2508 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2513 // Pad both vectors with undefs to make them the same length as the mask.
2514 unsigned NumConcat = MaskNumElts / SrcNumElts;
2515 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2516 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2517 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2519 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2520 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2524 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2525 getCurDebugLoc(), VT,
2526 &MOps1[0], NumConcat);
2527 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2528 getCurDebugLoc(), VT,
2529 &MOps2[0], NumConcat);
2531 // Readjust mask for new input vector length.
2532 SmallVector<int, 8> MappedOps;
2533 for (unsigned i = 0; i != MaskNumElts; ++i) {
2535 if (Idx < (int)SrcNumElts)
2536 MappedOps.push_back(Idx);
2538 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2541 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2545 if (DisableScheduling) {
2546 DAG.AssignOrdering(Src1.getNode(), SDNodeOrder);
2547 DAG.AssignOrdering(Src2.getNode(), SDNodeOrder);
2548 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2554 if (SrcNumElts > MaskNumElts) {
2555 // Analyze the access pattern of the vector to see if we can extract
2556 // two subvectors and do the shuffle. The analysis is done by calculating
2557 // the range of elements the mask access on both vectors.
2558 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2559 int MaxRange[2] = {-1, -1};
2561 for (unsigned i = 0; i != MaskNumElts; ++i) {
2567 if (Idx >= (int)SrcNumElts) {
2571 if (Idx > MaxRange[Input])
2572 MaxRange[Input] = Idx;
2573 if (Idx < MinRange[Input])
2574 MinRange[Input] = Idx;
2577 // Check if the access is smaller than the vector size and can we find
2578 // a reasonable extract index.
2579 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2580 int StartIdx[2]; // StartIdx to extract from
2581 for (int Input=0; Input < 2; ++Input) {
2582 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2583 RangeUse[Input] = 0; // Unused
2584 StartIdx[Input] = 0;
2585 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2586 // Fits within range but we should see if we can find a good
2587 // start index that is a multiple of the mask length.
2588 if (MaxRange[Input] < (int)MaskNumElts) {
2589 RangeUse[Input] = 1; // Extract from beginning of the vector
2590 StartIdx[Input] = 0;
2592 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2593 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2594 StartIdx[Input] + MaskNumElts < SrcNumElts)
2595 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2600 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2601 SDValue Res = DAG.getUNDEF(VT);
2602 setValue(&I, Res); // Vectors are not used.
2604 if (DisableScheduling)
2605 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2609 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2610 // Extract appropriate subvector and generate a vector shuffle
2611 for (int Input=0; Input < 2; ++Input) {
2612 SDValue &Src = Input == 0 ? Src1 : Src2;
2613 if (RangeUse[Input] == 0)
2614 Src = DAG.getUNDEF(VT);
2616 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2617 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2619 if (DisableScheduling)
2620 DAG.AssignOrdering(Src.getNode(), SDNodeOrder);
2623 // Calculate new mask.
2624 SmallVector<int, 8> MappedOps;
2625 for (unsigned i = 0; i != MaskNumElts; ++i) {
2628 MappedOps.push_back(Idx);
2629 else if (Idx < (int)SrcNumElts)
2630 MappedOps.push_back(Idx - StartIdx[0]);
2632 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2635 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2639 if (DisableScheduling)
2640 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2646 // We can't use either concat vectors or extract subvectors so fall back to
2647 // replacing the shuffle with extract and build vector.
2648 // to insert and build vector.
2649 EVT EltVT = VT.getVectorElementType();
2650 EVT PtrVT = TLI.getPointerTy();
2651 SmallVector<SDValue,8> Ops;
2652 for (unsigned i = 0; i != MaskNumElts; ++i) {
2654 Ops.push_back(DAG.getUNDEF(EltVT));
2659 if (Idx < (int)SrcNumElts)
2660 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2661 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2663 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2665 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2669 if (DisableScheduling)
2670 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2674 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2675 VT, &Ops[0], Ops.size());
2678 if (DisableScheduling)
2679 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2682 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2683 const Value *Op0 = I.getOperand(0);
2684 const Value *Op1 = I.getOperand(1);
2685 const Type *AggTy = I.getType();
2686 const Type *ValTy = Op1->getType();
2687 bool IntoUndef = isa<UndefValue>(Op0);
2688 bool FromUndef = isa<UndefValue>(Op1);
2690 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2691 I.idx_begin(), I.idx_end());
2693 SmallVector<EVT, 4> AggValueVTs;
2694 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2695 SmallVector<EVT, 4> ValValueVTs;
2696 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2698 unsigned NumAggValues = AggValueVTs.size();
2699 unsigned NumValValues = ValValueVTs.size();
2700 SmallVector<SDValue, 4> Values(NumAggValues);
2702 SDValue Agg = getValue(Op0);
2703 SDValue Val = getValue(Op1);
2705 // Copy the beginning value(s) from the original aggregate.
2706 for (; i != LinearIndex; ++i)
2707 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2708 SDValue(Agg.getNode(), Agg.getResNo() + i);
2709 // Copy values from the inserted value(s).
2710 for (; i != LinearIndex + NumValValues; ++i)
2711 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2712 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2713 // Copy remaining value(s) from the original aggregate.
2714 for (; i != NumAggValues; ++i)
2715 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2716 SDValue(Agg.getNode(), Agg.getResNo() + i);
2718 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2719 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2720 &Values[0], NumAggValues);
2723 if (DisableScheduling)
2724 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2727 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2728 const Value *Op0 = I.getOperand(0);
2729 const Type *AggTy = Op0->getType();
2730 const Type *ValTy = I.getType();
2731 bool OutOfUndef = isa<UndefValue>(Op0);
2733 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2734 I.idx_begin(), I.idx_end());
2736 SmallVector<EVT, 4> ValValueVTs;
2737 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2739 unsigned NumValValues = ValValueVTs.size();
2740 SmallVector<SDValue, 4> Values(NumValValues);
2742 SDValue Agg = getValue(Op0);
2743 // Copy out the selected value(s).
2744 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2745 Values[i - LinearIndex] =
2747 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2748 SDValue(Agg.getNode(), Agg.getResNo() + i);
2750 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2751 DAG.getVTList(&ValValueVTs[0], NumValValues),
2752 &Values[0], NumValValues);
2755 if (DisableScheduling)
2756 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2759 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2760 SDValue N = getValue(I.getOperand(0));
2761 const Type *Ty = I.getOperand(0)->getType();
2763 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2766 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2767 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2770 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2771 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2772 DAG.getIntPtrConstant(Offset));
2774 if (DisableScheduling)
2775 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2778 Ty = StTy->getElementType(Field);
2780 Ty = cast<SequentialType>(Ty)->getElementType();
2782 // If this is a constant subscript, handle it quickly.
2783 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2784 if (CI->getZExtValue() == 0) continue;
2786 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2788 EVT PTy = TLI.getPointerTy();
2789 unsigned PtrBits = PTy.getSizeInBits();
2791 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2793 DAG.getConstant(Offs, MVT::i64));
2795 OffsVal = DAG.getIntPtrConstant(Offs);
2797 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2800 if (DisableScheduling) {
2801 DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder);
2802 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2808 // N = N + Idx * ElementSize;
2809 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2810 TD->getTypeAllocSize(Ty));
2811 SDValue IdxN = getValue(Idx);
2813 // If the index is smaller or larger than intptr_t, truncate or extend
2815 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2817 // If this is a multiply by a power of two, turn it into a shl
2818 // immediately. This is a very common case.
2819 if (ElementSize != 1) {
2820 if (ElementSize.isPowerOf2()) {
2821 unsigned Amt = ElementSize.logBase2();
2822 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2823 N.getValueType(), IdxN,
2824 DAG.getConstant(Amt, TLI.getPointerTy()));
2826 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2827 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2828 N.getValueType(), IdxN, Scale);
2831 if (DisableScheduling)
2832 DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder);
2835 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2836 N.getValueType(), N, IdxN);
2838 if (DisableScheduling)
2839 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2846 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2847 // If this is a fixed sized alloca in the entry block of the function,
2848 // allocate it statically on the stack.
2849 if (FuncInfo.StaticAllocaMap.count(&I))
2850 return; // getValue will auto-populate this.
2852 const Type *Ty = I.getAllocatedType();
2853 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2855 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2858 SDValue AllocSize = getValue(I.getArraySize());
2860 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2862 DAG.getConstant(TySize, AllocSize.getValueType()));
2864 if (DisableScheduling)
2865 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2867 EVT IntPtr = TLI.getPointerTy();
2868 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2870 if (DisableScheduling)
2871 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2873 // Handle alignment. If the requested alignment is less than or equal to
2874 // the stack alignment, ignore it. If the size is greater than or equal to
2875 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2876 unsigned StackAlign =
2877 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2878 if (Align <= StackAlign)
2881 // Round the size of the allocation up to the stack alignment size
2882 // by add SA-1 to the size.
2883 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2884 AllocSize.getValueType(), AllocSize,
2885 DAG.getIntPtrConstant(StackAlign-1));
2886 if (DisableScheduling)
2887 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2889 // Mask out the low bits for alignment purposes.
2890 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2891 AllocSize.getValueType(), AllocSize,
2892 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2893 if (DisableScheduling)
2894 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2896 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2897 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2898 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2901 DAG.setRoot(DSA.getValue(1));
2903 if (DisableScheduling)
2904 DAG.AssignOrdering(DSA.getNode(), SDNodeOrder);
2906 // Inform the Frame Information that we have just allocated a variable-sized
2908 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2911 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2912 const Value *SV = I.getOperand(0);
2913 SDValue Ptr = getValue(SV);
2915 const Type *Ty = I.getType();
2916 bool isVolatile = I.isVolatile();
2917 unsigned Alignment = I.getAlignment();
2919 SmallVector<EVT, 4> ValueVTs;
2920 SmallVector<uint64_t, 4> Offsets;
2921 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2922 unsigned NumValues = ValueVTs.size();
2927 bool ConstantMemory = false;
2929 // Serialize volatile loads with other side effects.
2931 else if (AA->pointsToConstantMemory(SV)) {
2932 // Do not serialize (non-volatile) loads of constant memory with anything.
2933 Root = DAG.getEntryNode();
2934 ConstantMemory = true;
2936 // Do not serialize non-volatile loads against each other.
2937 Root = DAG.getRoot();
2940 SmallVector<SDValue, 4> Values(NumValues);
2941 SmallVector<SDValue, 4> Chains(NumValues);
2942 EVT PtrVT = Ptr.getValueType();
2943 for (unsigned i = 0; i != NumValues; ++i) {
2944 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2946 DAG.getConstant(Offsets[i], PtrVT));
2947 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2948 A, SV, Offsets[i], isVolatile, Alignment);
2951 Chains[i] = L.getValue(1);
2953 if (DisableScheduling) {
2954 DAG.AssignOrdering(A.getNode(), SDNodeOrder);
2955 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
2959 if (!ConstantMemory) {
2960 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2961 MVT::Other, &Chains[0], NumValues);
2965 PendingLoads.push_back(Chain);
2967 if (DisableScheduling)
2968 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
2971 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2972 DAG.getVTList(&ValueVTs[0], NumValues),
2973 &Values[0], NumValues);
2976 if (DisableScheduling)
2977 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2980 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2981 Value *SrcV = I.getOperand(0);
2982 Value *PtrV = I.getOperand(1);
2984 SmallVector<EVT, 4> ValueVTs;
2985 SmallVector<uint64_t, 4> Offsets;
2986 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2987 unsigned NumValues = ValueVTs.size();
2991 // Get the lowered operands. Note that we do this after
2992 // checking if NumResults is zero, because with zero results
2993 // the operands won't have values in the map.
2994 SDValue Src = getValue(SrcV);
2995 SDValue Ptr = getValue(PtrV);
2997 SDValue Root = getRoot();
2998 SmallVector<SDValue, 4> Chains(NumValues);
2999 EVT PtrVT = Ptr.getValueType();
3000 bool isVolatile = I.isVolatile();
3001 unsigned Alignment = I.getAlignment();
3003 for (unsigned i = 0; i != NumValues; ++i) {
3004 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3005 DAG.getConstant(Offsets[i], PtrVT));
3006 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
3007 SDValue(Src.getNode(), Src.getResNo() + i),
3008 Add, PtrV, Offsets[i], isVolatile, Alignment);
3010 if (DisableScheduling) {
3011 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
3012 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
3016 SDValue Res = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3017 MVT::Other, &Chains[0], NumValues);
3020 if (DisableScheduling)
3021 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3024 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3026 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
3027 unsigned Intrinsic) {
3028 bool HasChain = !I.doesNotAccessMemory();
3029 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3031 // Build the operand list.
3032 SmallVector<SDValue, 8> Ops;
3033 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3035 // We don't need to serialize loads against other loads.
3036 Ops.push_back(DAG.getRoot());
3038 Ops.push_back(getRoot());
3042 // Info is set by getTgtMemInstrinsic
3043 TargetLowering::IntrinsicInfo Info;
3044 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3046 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3047 if (!IsTgtIntrinsic)
3048 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3050 // Add all operands of the call to the operand list.
3051 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3052 SDValue Op = getValue(I.getOperand(i));
3053 assert(TLI.isTypeLegal(Op.getValueType()) &&
3054 "Intrinsic uses a non-legal type?");
3058 SmallVector<EVT, 4> ValueVTs;
3059 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3061 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3062 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3063 "Intrinsic uses a non-legal type?");
3068 ValueVTs.push_back(MVT::Other);
3070 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3074 if (IsTgtIntrinsic) {
3075 // This is target intrinsic that touches memory
3076 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3077 VTs, &Ops[0], Ops.size(),
3078 Info.memVT, Info.ptrVal, Info.offset,
3079 Info.align, Info.vol,
3080 Info.readMem, Info.writeMem);
3081 } else if (!HasChain) {
3082 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3083 VTs, &Ops[0], Ops.size());
3084 } else if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3085 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3086 VTs, &Ops[0], Ops.size());
3088 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3089 VTs, &Ops[0], Ops.size());
3092 if (DisableScheduling)
3093 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3096 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3098 PendingLoads.push_back(Chain);
3103 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3104 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3105 EVT VT = TLI.getValueType(PTy);
3106 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3108 if (DisableScheduling)
3109 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3112 setValue(&I, Result);
3116 /// GetSignificand - Get the significand and build it into a floating-point
3117 /// number with exponent of 1:
3119 /// Op = (Op & 0x007fffff) | 0x3f800000;
3121 /// where Op is the hexidecimal representation of floating point value.
3123 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
3124 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3125 DAG.getConstant(0x007fffff, MVT::i32));
3126 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3127 DAG.getConstant(0x3f800000, MVT::i32));
3128 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3130 if (DisableScheduling) {
3131 DAG.AssignOrdering(t1.getNode(), Order);
3132 DAG.AssignOrdering(t2.getNode(), Order);
3133 DAG.AssignOrdering(Res.getNode(), Order);
3139 /// GetExponent - Get the exponent:
3141 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3143 /// where Op is the hexidecimal representation of floating point value.
3145 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3146 DebugLoc dl, unsigned Order) {
3147 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3148 DAG.getConstant(0x7f800000, MVT::i32));
3149 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3150 DAG.getConstant(23, TLI.getPointerTy()));
3151 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3152 DAG.getConstant(127, MVT::i32));
3153 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3155 if (DisableScheduling) {
3156 DAG.AssignOrdering(t0.getNode(), Order);
3157 DAG.AssignOrdering(t1.getNode(), Order);
3158 DAG.AssignOrdering(t2.getNode(), Order);
3159 DAG.AssignOrdering(Res.getNode(), Order);
3165 /// getF32Constant - Get 32-bit floating point constant.
3167 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3168 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3171 /// Inlined utility function to implement binary input atomic intrinsics for
3172 /// visitIntrinsicCall: I is a call instruction
3173 /// Op is the associated NodeType for I
3175 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3176 SDValue Root = getRoot();
3178 DAG.getAtomic(Op, getCurDebugLoc(),
3179 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3181 getValue(I.getOperand(1)),
3182 getValue(I.getOperand(2)),
3185 DAG.setRoot(L.getValue(1));
3187 if (DisableScheduling)
3188 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3193 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3195 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3196 SDValue Op1 = getValue(I.getOperand(1));
3197 SDValue Op2 = getValue(I.getOperand(2));
3199 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3200 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3202 setValue(&I, Result);
3204 if (DisableScheduling)
3205 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3210 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3211 /// limited-precision mode.
3213 SelectionDAGBuilder::visitExp(CallInst &I) {
3215 DebugLoc dl = getCurDebugLoc();
3217 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3218 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3219 SDValue Op = getValue(I.getOperand(1));
3221 // Put the exponent in the right bit position for later addition to the
3224 // #define LOG2OFe 1.4426950f
3225 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3227 getF32Constant(DAG, 0x3fb8aa3b));
3228 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3230 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3231 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3232 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3234 if (DisableScheduling) {
3235 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3236 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3237 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3238 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3241 // IntegerPartOfX <<= 23;
3242 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3243 DAG.getConstant(23, TLI.getPointerTy()));
3245 if (DisableScheduling)
3246 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3248 if (LimitFloatPrecision <= 6) {
3249 // For floating-point precision of 6:
3251 // TwoToFractionalPartOfX =
3253 // (0.735607626f + 0.252464424f * x) * x;
3255 // error 0.0144103317, which is 6 bits
3256 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3257 getF32Constant(DAG, 0x3e814304));
3258 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3259 getF32Constant(DAG, 0x3f3c50c8));
3260 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3261 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3262 getF32Constant(DAG, 0x3f7f5e7e));
3263 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3265 // Add the exponent into the result in integer domain.
3266 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3267 TwoToFracPartOfX, IntegerPartOfX);
3269 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3271 if (DisableScheduling) {
3272 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3273 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3274 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3275 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3276 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3277 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3278 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3280 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3281 // For floating-point precision of 12:
3283 // TwoToFractionalPartOfX =
3286 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3288 // 0.000107046256 error, which is 13 to 14 bits
3289 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3290 getF32Constant(DAG, 0x3da235e3));
3291 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3292 getF32Constant(DAG, 0x3e65b8f3));
3293 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3294 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3295 getF32Constant(DAG, 0x3f324b07));
3296 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3297 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3298 getF32Constant(DAG, 0x3f7ff8fd));
3299 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3301 // Add the exponent into the result in integer domain.
3302 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3303 TwoToFracPartOfX, IntegerPartOfX);
3305 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3307 if (DisableScheduling) {
3308 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3309 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3310 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3311 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3312 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3313 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3314 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3315 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3316 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3318 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3319 // For floating-point precision of 18:
3321 // TwoToFractionalPartOfX =
3325 // (0.554906021e-1f +
3326 // (0.961591928e-2f +
3327 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3329 // error 2.47208000*10^(-7), which is better than 18 bits
3330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3331 getF32Constant(DAG, 0x3924b03e));
3332 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3333 getF32Constant(DAG, 0x3ab24b87));
3334 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3335 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3336 getF32Constant(DAG, 0x3c1d8c17));
3337 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3338 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3339 getF32Constant(DAG, 0x3d634a1d));
3340 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3341 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3342 getF32Constant(DAG, 0x3e75fe14));
3343 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3344 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3345 getF32Constant(DAG, 0x3f317234));
3346 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3347 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3348 getF32Constant(DAG, 0x3f800000));
3349 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3352 // Add the exponent into the result in integer domain.
3353 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3354 TwoToFracPartOfX, IntegerPartOfX);
3356 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3358 if (DisableScheduling) {
3359 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3360 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3361 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3362 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3363 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3364 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3365 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3366 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3367 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3368 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3369 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3370 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3371 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3372 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3373 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3377 // No special expansion.
3378 result = DAG.getNode(ISD::FEXP, dl,
3379 getValue(I.getOperand(1)).getValueType(),
3380 getValue(I.getOperand(1)));
3381 if (DisableScheduling)
3382 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3385 setValue(&I, result);
3388 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3389 /// limited-precision mode.
3391 SelectionDAGBuilder::visitLog(CallInst &I) {
3393 DebugLoc dl = getCurDebugLoc();
3395 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3396 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3397 SDValue Op = getValue(I.getOperand(1));
3398 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3400 if (DisableScheduling)
3401 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3403 // Scale the exponent by log(2) [0.69314718f].
3404 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3405 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3406 getF32Constant(DAG, 0x3f317218));
3408 if (DisableScheduling)
3409 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3411 // Get the significand and build it into a floating-point number with
3413 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3415 if (LimitFloatPrecision <= 6) {
3416 // For floating-point precision of 6:
3420 // (1.4034025f - 0.23903021f * x) * x;
3422 // error 0.0034276066, which is better than 8 bits
3423 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3424 getF32Constant(DAG, 0xbe74c456));
3425 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3426 getF32Constant(DAG, 0x3fb3a2b1));
3427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3428 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3429 getF32Constant(DAG, 0x3f949a29));
3431 result = DAG.getNode(ISD::FADD, dl,
3432 MVT::f32, LogOfExponent, LogOfMantissa);
3434 if (DisableScheduling) {
3435 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3436 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3437 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3438 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3439 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3441 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3442 // For floating-point precision of 12:
3448 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3450 // error 0.000061011436, which is 14 bits
3451 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3452 getF32Constant(DAG, 0xbd67b6d6));
3453 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3454 getF32Constant(DAG, 0x3ee4f4b8));
3455 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3456 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3457 getF32Constant(DAG, 0x3fbc278b));
3458 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3459 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3460 getF32Constant(DAG, 0x40348e95));
3461 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3462 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3463 getF32Constant(DAG, 0x3fdef31a));
3465 result = DAG.getNode(ISD::FADD, dl,
3466 MVT::f32, LogOfExponent, LogOfMantissa);
3468 if (DisableScheduling) {
3469 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3470 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3471 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3472 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3473 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3474 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3475 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3476 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3477 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3479 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3480 // For floating-point precision of 18:
3488 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3490 // error 0.0000023660568, which is better than 18 bits
3491 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3492 getF32Constant(DAG, 0xbc91e5ac));
3493 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3494 getF32Constant(DAG, 0x3e4350aa));
3495 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3496 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3497 getF32Constant(DAG, 0x3f60d3e3));
3498 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3499 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3500 getF32Constant(DAG, 0x4011cdf0));
3501 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3502 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3503 getF32Constant(DAG, 0x406cfd1c));
3504 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3505 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3506 getF32Constant(DAG, 0x408797cb));
3507 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3508 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3509 getF32Constant(DAG, 0x4006dcab));
3511 result = DAG.getNode(ISD::FADD, dl,
3512 MVT::f32, LogOfExponent, LogOfMantissa);
3514 if (DisableScheduling) {
3515 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3516 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3517 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3518 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3519 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3520 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3521 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3522 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3523 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3524 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3525 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3526 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3527 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3531 // No special expansion.
3532 result = DAG.getNode(ISD::FLOG, dl,
3533 getValue(I.getOperand(1)).getValueType(),
3534 getValue(I.getOperand(1)));
3536 if (DisableScheduling)
3537 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3540 setValue(&I, result);
3543 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3544 /// limited-precision mode.
3546 SelectionDAGBuilder::visitLog2(CallInst &I) {
3548 DebugLoc dl = getCurDebugLoc();
3550 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3551 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3552 SDValue Op = getValue(I.getOperand(1));
3553 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3555 if (DisableScheduling)
3556 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3558 // Get the exponent.
3559 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3561 if (DisableScheduling)
3562 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3564 // Get the significand and build it into a floating-point number with
3566 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3568 // Different possible minimax approximations of significand in
3569 // floating-point for various degrees of accuracy over [1,2].
3570 if (LimitFloatPrecision <= 6) {
3571 // For floating-point precision of 6:
3573 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3575 // error 0.0049451742, which is more than 7 bits
3576 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3577 getF32Constant(DAG, 0xbeb08fe0));
3578 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3579 getF32Constant(DAG, 0x40019463));
3580 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3581 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3582 getF32Constant(DAG, 0x3fd6633d));
3584 result = DAG.getNode(ISD::FADD, dl,
3585 MVT::f32, LogOfExponent, Log2ofMantissa);
3587 if (DisableScheduling) {
3588 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3589 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3590 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3591 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3592 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3594 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3595 // For floating-point precision of 12:
3601 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3603 // error 0.0000876136000, which is better than 13 bits
3604 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3605 getF32Constant(DAG, 0xbda7262e));
3606 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3607 getF32Constant(DAG, 0x3f25280b));
3608 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3609 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3610 getF32Constant(DAG, 0x4007b923));
3611 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3612 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3613 getF32Constant(DAG, 0x40823e2f));
3614 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3615 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3616 getF32Constant(DAG, 0x4020d29c));
3618 result = DAG.getNode(ISD::FADD, dl,
3619 MVT::f32, LogOfExponent, Log2ofMantissa);
3621 if (DisableScheduling) {
3622 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3623 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3624 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3625 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3626 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3627 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3628 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3629 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3630 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3632 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3633 // For floating-point precision of 18:
3642 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3644 // error 0.0000018516, which is better than 18 bits
3645 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3646 getF32Constant(DAG, 0xbcd2769e));
3647 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3648 getF32Constant(DAG, 0x3e8ce0b9));
3649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3650 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3651 getF32Constant(DAG, 0x3fa22ae7));
3652 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3653 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3654 getF32Constant(DAG, 0x40525723));
3655 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3656 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3657 getF32Constant(DAG, 0x40aaf200));
3658 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3659 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3660 getF32Constant(DAG, 0x40c39dad));
3661 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3662 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3663 getF32Constant(DAG, 0x4042902c));
3665 result = DAG.getNode(ISD::FADD, dl,
3666 MVT::f32, LogOfExponent, Log2ofMantissa);
3668 if (DisableScheduling) {
3669 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3670 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3671 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3672 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3673 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3674 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3675 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3676 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3677 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3678 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3679 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3680 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3681 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3685 // No special expansion.
3686 result = DAG.getNode(ISD::FLOG2, dl,
3687 getValue(I.getOperand(1)).getValueType(),
3688 getValue(I.getOperand(1)));
3690 if (DisableScheduling)
3691 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3694 setValue(&I, result);
3697 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3698 /// limited-precision mode.
3700 SelectionDAGBuilder::visitLog10(CallInst &I) {
3702 DebugLoc dl = getCurDebugLoc();
3704 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3705 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3706 SDValue Op = getValue(I.getOperand(1));
3707 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3709 if (DisableScheduling)
3710 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3712 // Scale the exponent by log10(2) [0.30102999f].
3713 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3714 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3715 getF32Constant(DAG, 0x3e9a209a));
3717 if (DisableScheduling)
3718 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3720 // Get the significand and build it into a floating-point number with
3722 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3724 if (LimitFloatPrecision <= 6) {
3725 // For floating-point precision of 6:
3727 // Log10ofMantissa =
3729 // (0.60948995f - 0.10380950f * x) * x;
3731 // error 0.0014886165, which is 6 bits
3732 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3733 getF32Constant(DAG, 0xbdd49a13));
3734 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3735 getF32Constant(DAG, 0x3f1c0789));
3736 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3737 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3738 getF32Constant(DAG, 0x3f011300));
3740 result = DAG.getNode(ISD::FADD, dl,
3741 MVT::f32, LogOfExponent, Log10ofMantissa);
3743 if (DisableScheduling) {
3744 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3745 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3746 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3747 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3748 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3750 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3751 // For floating-point precision of 12:
3753 // Log10ofMantissa =
3756 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3758 // error 0.00019228036, which is better than 12 bits
3759 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3760 getF32Constant(DAG, 0x3d431f31));
3761 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3762 getF32Constant(DAG, 0x3ea21fb2));
3763 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3764 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3765 getF32Constant(DAG, 0x3f6ae232));
3766 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3767 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3768 getF32Constant(DAG, 0x3f25f7c3));
3770 result = DAG.getNode(ISD::FADD, dl,
3771 MVT::f32, LogOfExponent, Log10ofMantissa);
3773 if (DisableScheduling) {
3774 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3775 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3776 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3777 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3778 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3779 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3780 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3782 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3783 // For floating-point precision of 18:
3785 // Log10ofMantissa =
3790 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3792 // error 0.0000037995730, which is better than 18 bits
3793 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3794 getF32Constant(DAG, 0x3c5d51ce));
3795 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3796 getF32Constant(DAG, 0x3e00685a));
3797 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3798 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3799 getF32Constant(DAG, 0x3efb6798));
3800 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3801 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3802 getF32Constant(DAG, 0x3f88d192));
3803 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3804 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3805 getF32Constant(DAG, 0x3fc4316c));
3806 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3807 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3808 getF32Constant(DAG, 0x3f57ce70));
3810 result = DAG.getNode(ISD::FADD, dl,
3811 MVT::f32, LogOfExponent, Log10ofMantissa);
3813 if (DisableScheduling) {
3814 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3815 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3816 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3817 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3818 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3819 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3820 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3821 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3822 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3823 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3824 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3828 // No special expansion.
3829 result = DAG.getNode(ISD::FLOG10, dl,
3830 getValue(I.getOperand(1)).getValueType(),
3831 getValue(I.getOperand(1)));
3833 if (DisableScheduling)
3834 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3837 setValue(&I, result);
3840 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3841 /// limited-precision mode.
3843 SelectionDAGBuilder::visitExp2(CallInst &I) {
3845 DebugLoc dl = getCurDebugLoc();
3847 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3848 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3849 SDValue Op = getValue(I.getOperand(1));
3851 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3853 if (DisableScheduling)
3854 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3856 // FractionalPartOfX = x - (float)IntegerPartOfX;
3857 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3858 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3860 // IntegerPartOfX <<= 23;
3861 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3862 DAG.getConstant(23, TLI.getPointerTy()));
3864 if (DisableScheduling) {
3865 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3866 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3867 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3870 if (LimitFloatPrecision <= 6) {
3871 // For floating-point precision of 6:
3873 // TwoToFractionalPartOfX =
3875 // (0.735607626f + 0.252464424f * x) * x;
3877 // error 0.0144103317, which is 6 bits
3878 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3879 getF32Constant(DAG, 0x3e814304));
3880 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3881 getF32Constant(DAG, 0x3f3c50c8));
3882 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3883 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3884 getF32Constant(DAG, 0x3f7f5e7e));
3885 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3886 SDValue TwoToFractionalPartOfX =
3887 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3889 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3890 MVT::f32, TwoToFractionalPartOfX);
3892 if (DisableScheduling) {
3893 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3894 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3895 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3896 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3897 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3898 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3899 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3901 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3902 // For floating-point precision of 12:
3904 // TwoToFractionalPartOfX =
3907 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3909 // error 0.000107046256, which is 13 to 14 bits
3910 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3911 getF32Constant(DAG, 0x3da235e3));
3912 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3913 getF32Constant(DAG, 0x3e65b8f3));
3914 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3915 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3916 getF32Constant(DAG, 0x3f324b07));
3917 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3918 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3919 getF32Constant(DAG, 0x3f7ff8fd));
3920 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3921 SDValue TwoToFractionalPartOfX =
3922 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3924 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3925 MVT::f32, TwoToFractionalPartOfX);
3927 if (DisableScheduling) {
3928 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3929 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3930 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3931 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3932 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3933 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3934 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3935 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3936 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3938 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3939 // For floating-point precision of 18:
3941 // TwoToFractionalPartOfX =
3945 // (0.554906021e-1f +
3946 // (0.961591928e-2f +
3947 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3948 // error 2.47208000*10^(-7), which is better than 18 bits
3949 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3950 getF32Constant(DAG, 0x3924b03e));
3951 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3952 getF32Constant(DAG, 0x3ab24b87));
3953 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3954 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3955 getF32Constant(DAG, 0x3c1d8c17));
3956 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3957 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3958 getF32Constant(DAG, 0x3d634a1d));
3959 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3960 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3961 getF32Constant(DAG, 0x3e75fe14));
3962 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3963 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3964 getF32Constant(DAG, 0x3f317234));
3965 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3966 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3967 getF32Constant(DAG, 0x3f800000));
3968 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3969 SDValue TwoToFractionalPartOfX =
3970 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3972 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3973 MVT::f32, TwoToFractionalPartOfX);
3975 if (DisableScheduling) {
3976 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3977 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3978 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3979 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3980 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3981 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3982 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3983 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3984 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3985 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3986 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3987 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3988 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3989 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3990 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3994 // No special expansion.
3995 result = DAG.getNode(ISD::FEXP2, dl,
3996 getValue(I.getOperand(1)).getValueType(),
3997 getValue(I.getOperand(1)));
3999 if (DisableScheduling)
4000 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4003 setValue(&I, result);
4006 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4007 /// limited-precision mode with x == 10.0f.
4009 SelectionDAGBuilder::visitPow(CallInst &I) {
4011 Value *Val = I.getOperand(1);
4012 DebugLoc dl = getCurDebugLoc();
4013 bool IsExp10 = false;
4015 if (getValue(Val).getValueType() == MVT::f32 &&
4016 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
4017 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4018 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4019 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4021 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4026 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4027 SDValue Op = getValue(I.getOperand(2));
4029 // Put the exponent in the right bit position for later addition to the
4032 // #define LOG2OF10 3.3219281f
4033 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4034 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4035 getF32Constant(DAG, 0x40549a78));
4036 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4038 // FractionalPartOfX = x - (float)IntegerPartOfX;
4039 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4040 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4042 if (DisableScheduling) {
4043 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
4044 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
4045 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4046 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
4049 // IntegerPartOfX <<= 23;
4050 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4051 DAG.getConstant(23, TLI.getPointerTy()));
4053 if (DisableScheduling)
4054 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4056 if (LimitFloatPrecision <= 6) {
4057 // For floating-point precision of 6:
4059 // twoToFractionalPartOfX =
4061 // (0.735607626f + 0.252464424f * x) * x;
4063 // error 0.0144103317, which is 6 bits
4064 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4065 getF32Constant(DAG, 0x3e814304));
4066 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4067 getF32Constant(DAG, 0x3f3c50c8));
4068 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4069 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4070 getF32Constant(DAG, 0x3f7f5e7e));
4071 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
4072 SDValue TwoToFractionalPartOfX =
4073 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4075 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4076 MVT::f32, TwoToFractionalPartOfX);
4078 if (DisableScheduling) {
4079 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4080 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4081 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4082 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4083 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4084 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4085 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4087 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4088 // For floating-point precision of 12:
4090 // TwoToFractionalPartOfX =
4093 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4095 // error 0.000107046256, which is 13 to 14 bits
4096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4097 getF32Constant(DAG, 0x3da235e3));
4098 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4099 getF32Constant(DAG, 0x3e65b8f3));
4100 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4101 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4102 getF32Constant(DAG, 0x3f324b07));
4103 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4104 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4105 getF32Constant(DAG, 0x3f7ff8fd));
4106 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
4107 SDValue TwoToFractionalPartOfX =
4108 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4110 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4111 MVT::f32, TwoToFractionalPartOfX);
4113 if (DisableScheduling) {
4114 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4115 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4116 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4117 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4118 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4119 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4120 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4121 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4122 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4124 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4125 // For floating-point precision of 18:
4127 // TwoToFractionalPartOfX =
4131 // (0.554906021e-1f +
4132 // (0.961591928e-2f +
4133 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4134 // error 2.47208000*10^(-7), which is better than 18 bits
4135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4136 getF32Constant(DAG, 0x3924b03e));
4137 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4138 getF32Constant(DAG, 0x3ab24b87));
4139 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4140 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4141 getF32Constant(DAG, 0x3c1d8c17));
4142 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4143 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4144 getF32Constant(DAG, 0x3d634a1d));
4145 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4146 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4147 getF32Constant(DAG, 0x3e75fe14));
4148 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4149 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4150 getF32Constant(DAG, 0x3f317234));
4151 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4152 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4153 getF32Constant(DAG, 0x3f800000));
4154 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4155 SDValue TwoToFractionalPartOfX =
4156 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4158 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4159 MVT::f32, TwoToFractionalPartOfX);
4161 if (DisableScheduling) {
4162 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4163 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4164 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4165 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4166 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4167 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4168 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4169 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4170 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4171 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4172 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4173 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4174 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4175 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4176 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4180 // No special expansion.
4181 result = DAG.getNode(ISD::FPOW, dl,
4182 getValue(I.getOperand(1)).getValueType(),
4183 getValue(I.getOperand(1)),
4184 getValue(I.getOperand(2)));
4186 if (DisableScheduling)
4187 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4190 setValue(&I, result);
4193 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4194 /// we want to emit this as a call to a named external function, return the name
4195 /// otherwise lower it and return null.
4197 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
4198 DebugLoc dl = getCurDebugLoc();
4199 switch (Intrinsic) {
4201 // By default, turn this into a target intrinsic node.
4202 visitTargetIntrinsic(I, Intrinsic);
4204 case Intrinsic::vastart: visitVAStart(I); return 0;
4205 case Intrinsic::vaend: visitVAEnd(I); return 0;
4206 case Intrinsic::vacopy: visitVACopy(I); return 0;
4207 case Intrinsic::returnaddress:
4208 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4209 getValue(I.getOperand(1))));
4211 case Intrinsic::frameaddress:
4212 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4213 getValue(I.getOperand(1))));
4215 case Intrinsic::setjmp:
4216 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4218 case Intrinsic::longjmp:
4219 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4221 case Intrinsic::memcpy: {
4222 SDValue Op1 = getValue(I.getOperand(1));
4223 SDValue Op2 = getValue(I.getOperand(2));
4224 SDValue Op3 = getValue(I.getOperand(3));
4225 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4226 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4227 I.getOperand(1), 0, I.getOperand(2), 0));
4230 case Intrinsic::memset: {
4231 SDValue Op1 = getValue(I.getOperand(1));
4232 SDValue Op2 = getValue(I.getOperand(2));
4233 SDValue Op3 = getValue(I.getOperand(3));
4234 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4235 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
4236 I.getOperand(1), 0));
4239 case Intrinsic::memmove: {
4240 SDValue Op1 = getValue(I.getOperand(1));
4241 SDValue Op2 = getValue(I.getOperand(2));
4242 SDValue Op3 = getValue(I.getOperand(3));
4243 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4245 // If the source and destination are known to not be aliases, we can
4246 // lower memmove as memcpy.
4247 uint64_t Size = -1ULL;
4248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4249 Size = C->getZExtValue();
4250 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4251 AliasAnalysis::NoAlias) {
4252 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4253 I.getOperand(1), 0, I.getOperand(2), 0));
4257 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
4258 I.getOperand(1), 0, I.getOperand(2), 0));
4261 case Intrinsic::dbg_stoppoint:
4262 case Intrinsic::dbg_region_start:
4263 case Intrinsic::dbg_region_end:
4264 case Intrinsic::dbg_func_start:
4265 // FIXME - Remove this instructions once the dust settles.
4267 case Intrinsic::dbg_declare: {
4268 if (OptLevel != CodeGenOpt::None)
4269 // FIXME: Variable debug info is not supported here.
4271 DwarfWriter *DW = DAG.getDwarfWriter();
4274 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4275 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
4278 MDNode *Variable = DI.getVariable();
4279 Value *Address = DI.getAddress();
4280 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4281 Address = BCI->getOperand(0);
4282 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4283 // Don't handle byval struct arguments or VLAs, for example.
4286 DenseMap<const AllocaInst*, int>::iterator SI =
4287 FuncInfo.StaticAllocaMap.find(AI);
4288 if (SI == FuncInfo.StaticAllocaMap.end())
4290 int FI = SI->second;
4292 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4294 MetadataContext &TheMetadata =
4295 DI.getParent()->getContext().getMetadata();
4296 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
4297 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
4298 MMI->setVariableDbgInfo(Variable, FI, Dbg);
4302 case Intrinsic::eh_exception: {
4303 // Insert the EXCEPTIONADDR instruction.
4304 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
4305 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4307 Ops[0] = DAG.getRoot();
4308 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4310 DAG.setRoot(Op.getValue(1));
4314 case Intrinsic::eh_selector: {
4315 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4317 if (CurMBB->isLandingPad())
4318 AddCatchInfo(I, MMI, CurMBB);
4321 FuncInfo.CatchInfoLost.insert(&I);
4323 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4324 unsigned Reg = TLI.getExceptionSelectorRegister();
4325 if (Reg) CurMBB->addLiveIn(Reg);
4328 // Insert the EHSELECTION instruction.
4329 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4331 Ops[0] = getValue(I.getOperand(1));
4333 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4335 DAG.setRoot(Op.getValue(1));
4337 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4341 case Intrinsic::eh_typeid_for: {
4342 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4345 // Find the type id for the given typeinfo.
4346 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4348 unsigned TypeID = MMI->getTypeIDFor(GV);
4349 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
4351 // Return something different to eh_selector.
4352 setValue(&I, DAG.getConstant(1, MVT::i32));
4358 case Intrinsic::eh_return_i32:
4359 case Intrinsic::eh_return_i64:
4360 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4361 MMI->setCallsEHReturn(true);
4362 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4365 getValue(I.getOperand(1)),
4366 getValue(I.getOperand(2))));
4368 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4372 case Intrinsic::eh_unwind_init:
4373 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4374 MMI->setCallsUnwindInit(true);
4379 case Intrinsic::eh_dwarf_cfa: {
4380 EVT VT = getValue(I.getOperand(1)).getValueType();
4381 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4382 TLI.getPointerTy());
4384 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4386 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4387 TLI.getPointerTy()),
4389 setValue(&I, DAG.getNode(ISD::ADD, dl,
4391 DAG.getNode(ISD::FRAMEADDR, dl,
4394 TLI.getPointerTy())),
4398 case Intrinsic::convertff:
4399 case Intrinsic::convertfsi:
4400 case Intrinsic::convertfui:
4401 case Intrinsic::convertsif:
4402 case Intrinsic::convertuif:
4403 case Intrinsic::convertss:
4404 case Intrinsic::convertsu:
4405 case Intrinsic::convertus:
4406 case Intrinsic::convertuu: {
4407 ISD::CvtCode Code = ISD::CVT_INVALID;
4408 switch (Intrinsic) {
4409 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4410 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4411 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4412 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4413 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4414 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4415 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4416 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4417 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4419 EVT DestVT = TLI.getValueType(I.getType());
4420 Value* Op1 = I.getOperand(1);
4421 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4422 DAG.getValueType(DestVT),
4423 DAG.getValueType(getValue(Op1).getValueType()),
4424 getValue(I.getOperand(2)),
4425 getValue(I.getOperand(3)),
4430 case Intrinsic::sqrt:
4431 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4432 getValue(I.getOperand(1)).getValueType(),
4433 getValue(I.getOperand(1))));
4435 case Intrinsic::powi:
4436 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4437 getValue(I.getOperand(1)).getValueType(),
4438 getValue(I.getOperand(1)),
4439 getValue(I.getOperand(2))));
4441 case Intrinsic::sin:
4442 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4443 getValue(I.getOperand(1)).getValueType(),
4444 getValue(I.getOperand(1))));
4446 case Intrinsic::cos:
4447 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4448 getValue(I.getOperand(1)).getValueType(),
4449 getValue(I.getOperand(1))));
4451 case Intrinsic::log:
4454 case Intrinsic::log2:
4457 case Intrinsic::log10:
4460 case Intrinsic::exp:
4463 case Intrinsic::exp2:
4466 case Intrinsic::pow:
4469 case Intrinsic::pcmarker: {
4470 SDValue Tmp = getValue(I.getOperand(1));
4471 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4474 case Intrinsic::readcyclecounter: {
4475 SDValue Op = getRoot();
4476 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4477 DAG.getVTList(MVT::i64, MVT::Other),
4480 DAG.setRoot(Tmp.getValue(1));
4483 case Intrinsic::bswap:
4484 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4485 getValue(I.getOperand(1)).getValueType(),
4486 getValue(I.getOperand(1))));
4488 case Intrinsic::cttz: {
4489 SDValue Arg = getValue(I.getOperand(1));
4490 EVT Ty = Arg.getValueType();
4491 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4492 setValue(&I, result);
4495 case Intrinsic::ctlz: {
4496 SDValue Arg = getValue(I.getOperand(1));
4497 EVT Ty = Arg.getValueType();
4498 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4499 setValue(&I, result);
4502 case Intrinsic::ctpop: {
4503 SDValue Arg = getValue(I.getOperand(1));
4504 EVT Ty = Arg.getValueType();
4505 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4506 setValue(&I, result);
4509 case Intrinsic::stacksave: {
4510 SDValue Op = getRoot();
4511 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4512 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4514 DAG.setRoot(Tmp.getValue(1));
4517 case Intrinsic::stackrestore: {
4518 SDValue Tmp = getValue(I.getOperand(1));
4519 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4522 case Intrinsic::stackprotector: {
4523 // Emit code into the DAG to store the stack guard onto the stack.
4524 MachineFunction &MF = DAG.getMachineFunction();
4525 MachineFrameInfo *MFI = MF.getFrameInfo();
4526 EVT PtrTy = TLI.getPointerTy();
4528 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4529 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4531 int FI = FuncInfo.StaticAllocaMap[Slot];
4532 MFI->setStackProtectorIndex(FI);
4534 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4536 // Store the stack protector onto the stack.
4537 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4538 PseudoSourceValue::getFixedStack(FI),
4540 setValue(&I, Result);
4541 DAG.setRoot(Result);
4544 case Intrinsic::objectsize: {
4545 // If we don't know by now, we're never going to know.
4546 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4548 assert(CI && "Non-constant type in __builtin_object_size?");
4550 SDValue Arg = getValue(I.getOperand(0));
4551 EVT Ty = Arg.getValueType();
4553 if (CI->getZExtValue() < 2)
4554 setValue(&I, DAG.getConstant(-1ULL, Ty));
4556 setValue(&I, DAG.getConstant(0, Ty));
4559 case Intrinsic::var_annotation:
4560 // Discard annotate attributes
4563 case Intrinsic::init_trampoline: {
4564 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4568 Ops[1] = getValue(I.getOperand(1));
4569 Ops[2] = getValue(I.getOperand(2));
4570 Ops[3] = getValue(I.getOperand(3));
4571 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4572 Ops[5] = DAG.getSrcValue(F);
4574 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4575 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4579 DAG.setRoot(Tmp.getValue(1));
4583 case Intrinsic::gcroot:
4585 Value *Alloca = I.getOperand(1);
4586 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4588 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4589 GFI->addStackRoot(FI->getIndex(), TypeMap);
4593 case Intrinsic::gcread:
4594 case Intrinsic::gcwrite:
4595 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4598 case Intrinsic::flt_rounds: {
4599 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4603 case Intrinsic::trap: {
4604 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4608 case Intrinsic::uadd_with_overflow:
4609 return implVisitAluOverflow(I, ISD::UADDO);
4610 case Intrinsic::sadd_with_overflow:
4611 return implVisitAluOverflow(I, ISD::SADDO);
4612 case Intrinsic::usub_with_overflow:
4613 return implVisitAluOverflow(I, ISD::USUBO);
4614 case Intrinsic::ssub_with_overflow:
4615 return implVisitAluOverflow(I, ISD::SSUBO);
4616 case Intrinsic::umul_with_overflow:
4617 return implVisitAluOverflow(I, ISD::UMULO);
4618 case Intrinsic::smul_with_overflow:
4619 return implVisitAluOverflow(I, ISD::SMULO);
4621 case Intrinsic::prefetch: {
4624 Ops[1] = getValue(I.getOperand(1));
4625 Ops[2] = getValue(I.getOperand(2));
4626 Ops[3] = getValue(I.getOperand(3));
4627 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4631 case Intrinsic::memory_barrier: {
4634 for (int x = 1; x < 6; ++x)
4635 Ops[x] = getValue(I.getOperand(x));
4637 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4640 case Intrinsic::atomic_cmp_swap: {
4641 SDValue Root = getRoot();
4643 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4644 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4646 getValue(I.getOperand(1)),
4647 getValue(I.getOperand(2)),
4648 getValue(I.getOperand(3)),
4651 DAG.setRoot(L.getValue(1));
4654 case Intrinsic::atomic_load_add:
4655 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4656 case Intrinsic::atomic_load_sub:
4657 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4658 case Intrinsic::atomic_load_or:
4659 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4660 case Intrinsic::atomic_load_xor:
4661 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4662 case Intrinsic::atomic_load_and:
4663 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4664 case Intrinsic::atomic_load_nand:
4665 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4666 case Intrinsic::atomic_load_max:
4667 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4668 case Intrinsic::atomic_load_min:
4669 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4670 case Intrinsic::atomic_load_umin:
4671 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4672 case Intrinsic::atomic_load_umax:
4673 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4674 case Intrinsic::atomic_swap:
4675 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4677 case Intrinsic::invariant_start:
4678 case Intrinsic::lifetime_start:
4679 // Discard region information.
4680 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4682 case Intrinsic::invariant_end:
4683 case Intrinsic::lifetime_end:
4684 // Discard region information.
4689 /// Test if the given instruction is in a position to be optimized
4690 /// with a tail-call. This roughly means that it's in a block with
4691 /// a return and there's nothing that needs to be scheduled
4692 /// between it and the return.
4694 /// This function only tests target-independent requirements.
4695 /// For target-dependent requirements, a target should override
4696 /// TargetLowering::IsEligibleForTailCallOptimization.
4699 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
4700 const TargetLowering &TLI) {
4701 const BasicBlock *ExitBB = I->getParent();
4702 const TerminatorInst *Term = ExitBB->getTerminator();
4703 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4704 const Function *F = ExitBB->getParent();
4706 // The block must end in a return statement or an unreachable.
4707 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4709 // If I will have a chain, make sure no other instruction that will have a
4710 // chain interposes between I and the return.
4711 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4712 !I->isSafeToSpeculativelyExecute())
4713 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4717 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4718 !BBI->isSafeToSpeculativelyExecute())
4722 // If the block ends with a void return or unreachable, it doesn't matter
4723 // what the call's return type is.
4724 if (!Ret || Ret->getNumOperands() == 0) return true;
4726 // If the return value is undef, it doesn't matter what the call's
4728 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4730 // Conservatively require the attributes of the call to match those of
4731 // the return. Ignore noalias because it doesn't affect the call sequence.
4732 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4733 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4736 // Otherwise, make sure the unmodified return value of I is the return value.
4737 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4738 U = dyn_cast<Instruction>(U->getOperand(0))) {
4741 if (!U->hasOneUse())
4745 // Check for a truly no-op truncate.
4746 if (isa<TruncInst>(U) &&
4747 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4749 // Check for a truly no-op bitcast.
4750 if (isa<BitCastInst>(U) &&
4751 (U->getOperand(0)->getType() == U->getType() ||
4752 (isa<PointerType>(U->getOperand(0)->getType()) &&
4753 isa<PointerType>(U->getType()))))
4755 // Otherwise it's not a true no-op.
4762 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4764 MachineBasicBlock *LandingPad) {
4765 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4766 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4767 const Type *RetTy = FTy->getReturnType();
4768 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4769 unsigned BeginLabel = 0, EndLabel = 0;
4771 TargetLowering::ArgListTy Args;
4772 TargetLowering::ArgListEntry Entry;
4773 Args.reserve(CS.arg_size());
4775 // Check whether the function can return without sret-demotion.
4776 SmallVector<EVT, 4> OutVTs;
4777 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4778 SmallVector<uint64_t, 4> Offsets;
4779 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4780 OutVTs, OutsFlags, TLI, &Offsets);
4783 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4784 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4786 SDValue DemoteStackSlot;
4788 if (!CanLowerReturn) {
4789 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4790 FTy->getReturnType());
4791 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4792 FTy->getReturnType());
4793 MachineFunction &MF = DAG.getMachineFunction();
4794 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4795 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4797 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4798 Entry.Node = DemoteStackSlot;
4799 Entry.Ty = StackSlotPtrType;
4800 Entry.isSExt = false;
4801 Entry.isZExt = false;
4802 Entry.isInReg = false;
4803 Entry.isSRet = true;
4804 Entry.isNest = false;
4805 Entry.isByVal = false;
4806 Entry.Alignment = Align;
4807 Args.push_back(Entry);
4808 RetTy = Type::getVoidTy(FTy->getContext());
4811 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4813 SDValue ArgNode = getValue(*i);
4814 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4816 unsigned attrInd = i - CS.arg_begin() + 1;
4817 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4818 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4819 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4820 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4821 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4822 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4823 Entry.Alignment = CS.getParamAlignment(attrInd);
4824 Args.push_back(Entry);
4827 if (LandingPad && MMI) {
4828 // Insert a label before the invoke call to mark the try range. This can be
4829 // used to detect deletion of the invoke via the MachineModuleInfo.
4830 BeginLabel = MMI->NextLabelID();
4832 // Both PendingLoads and PendingExports must be flushed here;
4833 // this call might not return.
4835 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4836 getControlRoot(), BeginLabel));
4839 // Check if target-independent constraints permit a tail call here.
4840 // Target-dependent constraints are checked within TLI.LowerCallTo.
4842 !isInTailCallPosition(CS.getInstruction(),
4843 CS.getAttributes().getRetAttributes(),
4847 std::pair<SDValue,SDValue> Result =
4848 TLI.LowerCallTo(getRoot(), RetTy,
4849 CS.paramHasAttr(0, Attribute::SExt),
4850 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4851 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4852 CS.getCallingConv(),
4854 !CS.getInstruction()->use_empty(),
4855 Callee, Args, DAG, getCurDebugLoc());
4856 assert((isTailCall || Result.second.getNode()) &&
4857 "Non-null chain expected with non-tail call!");
4858 assert((Result.second.getNode() || !Result.first.getNode()) &&
4859 "Null value expected with tail call!");
4860 if (Result.first.getNode())
4861 setValue(CS.getInstruction(), Result.first);
4862 else if (!CanLowerReturn && Result.second.getNode()) {
4863 // The instruction result is the result of loading from the
4864 // hidden sret parameter.
4865 SmallVector<EVT, 1> PVTs;
4866 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4868 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4869 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4870 EVT PtrVT = PVTs[0];
4871 unsigned NumValues = OutVTs.size();
4872 SmallVector<SDValue, 4> Values(NumValues);
4873 SmallVector<SDValue, 4> Chains(NumValues);
4875 for (unsigned i = 0; i < NumValues; ++i) {
4876 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4877 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot,
4878 DAG.getConstant(Offsets[i], PtrVT)),
4879 NULL, Offsets[i], false, 1);
4881 Chains[i] = L.getValue(1);
4883 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4884 MVT::Other, &Chains[0], NumValues);
4885 PendingLoads.push_back(Chain);
4887 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES,
4888 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues),
4889 &Values[0], NumValues));
4891 // As a special case, a null chain means that a tail call has
4892 // been emitted and the DAG root is already updated.
4893 if (Result.second.getNode())
4894 DAG.setRoot(Result.second);
4898 if (LandingPad && MMI) {
4899 // Insert a label at the end of the invoke call to mark the try range. This
4900 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4901 EndLabel = MMI->NextLabelID();
4902 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4903 getRoot(), EndLabel));
4905 // Inform MachineModuleInfo of range.
4906 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4911 void SelectionDAGBuilder::visitCall(CallInst &I) {
4912 const char *RenameFn = 0;
4913 if (Function *F = I.getCalledFunction()) {
4914 if (F->isDeclaration()) {
4915 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4917 if (unsigned IID = II->getIntrinsicID(F)) {
4918 RenameFn = visitIntrinsicCall(I, IID);
4923 if (unsigned IID = F->getIntrinsicID()) {
4924 RenameFn = visitIntrinsicCall(I, IID);
4930 // Check for well-known libc/libm calls. If the function is internal, it
4931 // can't be a library call.
4932 if (!F->hasLocalLinkage() && F->hasName()) {
4933 StringRef Name = F->getName();
4934 if (Name == "copysign" || Name == "copysignf") {
4935 if (I.getNumOperands() == 3 && // Basic sanity checks.
4936 I.getOperand(1)->getType()->isFloatingPoint() &&
4937 I.getType() == I.getOperand(1)->getType() &&
4938 I.getType() == I.getOperand(2)->getType()) {
4939 SDValue LHS = getValue(I.getOperand(1));
4940 SDValue RHS = getValue(I.getOperand(2));
4941 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4942 LHS.getValueType(), LHS, RHS));
4945 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4946 if (I.getNumOperands() == 2 && // Basic sanity checks.
4947 I.getOperand(1)->getType()->isFloatingPoint() &&
4948 I.getType() == I.getOperand(1)->getType()) {
4949 SDValue Tmp = getValue(I.getOperand(1));
4950 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4951 Tmp.getValueType(), Tmp));
4954 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4955 if (I.getNumOperands() == 2 && // Basic sanity checks.
4956 I.getOperand(1)->getType()->isFloatingPoint() &&
4957 I.getType() == I.getOperand(1)->getType() &&
4958 I.onlyReadsMemory()) {
4959 SDValue Tmp = getValue(I.getOperand(1));
4960 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4961 Tmp.getValueType(), Tmp));
4964 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4965 if (I.getNumOperands() == 2 && // Basic sanity checks.
4966 I.getOperand(1)->getType()->isFloatingPoint() &&
4967 I.getType() == I.getOperand(1)->getType() &&
4968 I.onlyReadsMemory()) {
4969 SDValue Tmp = getValue(I.getOperand(1));
4970 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4971 Tmp.getValueType(), Tmp));
4974 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4975 if (I.getNumOperands() == 2 && // Basic sanity checks.
4976 I.getOperand(1)->getType()->isFloatingPoint() &&
4977 I.getType() == I.getOperand(1)->getType() &&
4978 I.onlyReadsMemory()) {
4979 SDValue Tmp = getValue(I.getOperand(1));
4980 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4981 Tmp.getValueType(), Tmp));
4986 } else if (isa<InlineAsm>(I.getOperand(0))) {
4993 Callee = getValue(I.getOperand(0));
4995 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4997 // Check if we can potentially perform a tail call. More detailed
4998 // checking is be done within LowerCallTo, after more information
4999 // about the call is known.
5000 bool isTailCall = PerformTailCallOpt && I.isTailCall();
5002 LowerCallTo(&I, Callee, isTailCall);
5006 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
5007 /// this value and returns the result as a ValueVT value. This uses
5008 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5009 /// If the Flag pointer is NULL, no flag is used.
5010 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
5012 SDValue *Flag) const {
5013 // Assemble the legal parts into the final values.
5014 SmallVector<SDValue, 4> Values(ValueVTs.size());
5015 SmallVector<SDValue, 8> Parts;
5016 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5017 // Copy the legal parts from the registers.
5018 EVT ValueVT = ValueVTs[Value];
5019 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5020 EVT RegisterVT = RegVTs[Value];
5022 Parts.resize(NumRegs);
5023 for (unsigned i = 0; i != NumRegs; ++i) {
5026 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
5028 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
5029 *Flag = P.getValue(2);
5031 Chain = P.getValue(1);
5033 // If the source register was virtual and if we know something about it,
5034 // add an assert node.
5035 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
5036 RegisterVT.isInteger() && !RegisterVT.isVector()) {
5037 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
5038 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5039 if (FLI.LiveOutRegInfo.size() > SlotNo) {
5040 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
5042 unsigned RegSize = RegisterVT.getSizeInBits();
5043 unsigned NumSignBits = LOI.NumSignBits;
5044 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
5046 // FIXME: We capture more information than the dag can represent. For
5047 // now, just use the tightest assertzext/assertsext possible.
5049 EVT FromVT(MVT::Other);
5050 if (NumSignBits == RegSize)
5051 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
5052 else if (NumZeroBits >= RegSize-1)
5053 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
5054 else if (NumSignBits > RegSize-8)
5055 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
5056 else if (NumZeroBits >= RegSize-8)
5057 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
5058 else if (NumSignBits > RegSize-16)
5059 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
5060 else if (NumZeroBits >= RegSize-16)
5061 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
5062 else if (NumSignBits > RegSize-32)
5063 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
5064 else if (NumZeroBits >= RegSize-32)
5065 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
5067 if (FromVT != MVT::Other) {
5068 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
5069 RegisterVT, P, DAG.getValueType(FromVT));
5078 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
5079 NumRegs, RegisterVT, ValueVT);
5084 return DAG.getNode(ISD::MERGE_VALUES, dl,
5085 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
5086 &Values[0], ValueVTs.size());
5089 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
5090 /// specified value into the registers specified by this object. This uses
5091 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5092 /// If the Flag pointer is NULL, no flag is used.
5093 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
5094 SDValue &Chain, SDValue *Flag) const {
5095 // Get the list of the values's legal parts.
5096 unsigned NumRegs = Regs.size();
5097 SmallVector<SDValue, 8> Parts(NumRegs);
5098 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5099 EVT ValueVT = ValueVTs[Value];
5100 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5101 EVT RegisterVT = RegVTs[Value];
5103 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
5104 &Parts[Part], NumParts, RegisterVT);
5108 // Copy the parts into the registers.
5109 SmallVector<SDValue, 8> Chains(NumRegs);
5110 for (unsigned i = 0; i != NumRegs; ++i) {
5113 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
5115 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
5116 *Flag = Part.getValue(1);
5118 Chains[i] = Part.getValue(0);
5121 if (NumRegs == 1 || Flag)
5122 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
5123 // flagged to it. That is the CopyToReg nodes and the user are considered
5124 // a single scheduling unit. If we create a TokenFactor and return it as
5125 // chain, then the TokenFactor is both a predecessor (operand) of the
5126 // user as well as a successor (the TF operands are flagged to the user).
5127 // c1, f1 = CopyToReg
5128 // c2, f2 = CopyToReg
5129 // c3 = TokenFactor c1, c2
5132 Chain = Chains[NumRegs-1];
5134 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
5137 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
5138 /// operand list. This adds the code marker and includes the number of
5139 /// values added into it.
5140 void RegsForValue::AddInlineAsmOperands(unsigned Code,
5141 bool HasMatching,unsigned MatchingIdx,
5143 std::vector<SDValue> &Ops) const {
5144 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5145 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
5146 unsigned Flag = Code | (Regs.size() << 3);
5148 Flag |= 0x80000000 | (MatchingIdx << 16);
5149 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
5150 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
5151 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
5152 EVT RegisterVT = RegVTs[Value];
5153 for (unsigned i = 0; i != NumRegs; ++i) {
5154 assert(Reg < Regs.size() && "Mismatch in # registers expected");
5155 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
5160 /// isAllocatableRegister - If the specified register is safe to allocate,
5161 /// i.e. it isn't a stack pointer or some other special register, return the
5162 /// register class for the register. Otherwise, return null.
5163 static const TargetRegisterClass *
5164 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5165 const TargetLowering &TLI,
5166 const TargetRegisterInfo *TRI) {
5167 EVT FoundVT = MVT::Other;
5168 const TargetRegisterClass *FoundRC = 0;
5169 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5170 E = TRI->regclass_end(); RCI != E; ++RCI) {
5171 EVT ThisVT = MVT::Other;
5173 const TargetRegisterClass *RC = *RCI;
5174 // If none of the the value types for this register class are valid, we
5175 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5176 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5178 if (TLI.isTypeLegal(*I)) {
5179 // If we have already found this register in a different register class,
5180 // choose the one with the largest VT specified. For example, on
5181 // PowerPC, we favor f64 register classes over f32.
5182 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5189 if (ThisVT == MVT::Other) continue;
5191 // NOTE: This isn't ideal. In particular, this might allocate the
5192 // frame pointer in functions that need it (due to them not being taken
5193 // out of allocation, because a variable sized allocation hasn't been seen
5194 // yet). This is a slight code pessimization, but should still work.
5195 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5196 E = RC->allocation_order_end(MF); I != E; ++I)
5198 // We found a matching register class. Keep looking at others in case
5199 // we find one with larger registers that this physreg is also in.
5210 /// AsmOperandInfo - This contains information for each constraint that we are
5212 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
5213 public TargetLowering::AsmOperandInfo {
5215 /// CallOperand - If this is the result output operand or a clobber
5216 /// this is null, otherwise it is the incoming operand to the CallInst.
5217 /// This gets modified as the asm is processed.
5218 SDValue CallOperand;
5220 /// AssignedRegs - If this is a register or register class operand, this
5221 /// contains the set of register corresponding to the operand.
5222 RegsForValue AssignedRegs;
5224 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
5225 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5228 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5229 /// busy in OutputRegs/InputRegs.
5230 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5231 std::set<unsigned> &OutputRegs,
5232 std::set<unsigned> &InputRegs,
5233 const TargetRegisterInfo &TRI) const {
5235 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5236 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5239 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5240 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5244 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5245 /// corresponds to. If there is no Value* for this operand, it returns
5247 EVT getCallOperandValEVT(LLVMContext &Context,
5248 const TargetLowering &TLI,
5249 const TargetData *TD) const {
5250 if (CallOperandVal == 0) return MVT::Other;
5252 if (isa<BasicBlock>(CallOperandVal))
5253 return TLI.getPointerTy();
5255 const llvm::Type *OpTy = CallOperandVal->getType();
5257 // If this is an indirect operand, the operand is a pointer to the
5260 OpTy = cast<PointerType>(OpTy)->getElementType();
5262 // If OpTy is not a single value, it may be a struct/union that we
5263 // can tile with integers.
5264 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5265 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5274 OpTy = IntegerType::get(Context, BitSize);
5279 return TLI.getValueType(OpTy, true);
5283 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5285 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5286 const TargetRegisterInfo &TRI) {
5287 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5289 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5290 for (; *Aliases; ++Aliases)
5291 Regs.insert(*Aliases);
5294 } // end llvm namespace.
5297 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5298 /// specified operand. We prefer to assign virtual registers, to allow the
5299 /// register allocator to handle the assignment process. However, if the asm
5300 /// uses features that we can't model on machineinstrs, we have SDISel do the
5301 /// allocation. This produces generally horrible, but correct, code.
5303 /// OpInfo describes the operand.
5304 /// Input and OutputRegs are the set of already allocated physical registers.
5306 void SelectionDAGBuilder::
5307 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5308 std::set<unsigned> &OutputRegs,
5309 std::set<unsigned> &InputRegs) {
5310 LLVMContext &Context = FuncInfo.Fn->getContext();
5312 // Compute whether this value requires an input register, an output register,
5314 bool isOutReg = false;
5315 bool isInReg = false;
5316 switch (OpInfo.Type) {
5317 case InlineAsm::isOutput:
5320 // If there is an input constraint that matches this, we need to reserve
5321 // the input register so no other inputs allocate to it.
5322 isInReg = OpInfo.hasMatchingInput();
5324 case InlineAsm::isInput:
5328 case InlineAsm::isClobber:
5335 MachineFunction &MF = DAG.getMachineFunction();
5336 SmallVector<unsigned, 4> Regs;
5338 // If this is a constraint for a single physreg, or a constraint for a
5339 // register class, find it.
5340 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5341 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5342 OpInfo.ConstraintVT);
5344 unsigned NumRegs = 1;
5345 if (OpInfo.ConstraintVT != MVT::Other) {
5346 // If this is a FP input in an integer register (or visa versa) insert a bit
5347 // cast of the input value. More generally, handle any case where the input
5348 // value disagrees with the register class we plan to stick this in.
5349 if (OpInfo.Type == InlineAsm::isInput &&
5350 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5351 // Try to convert to the first EVT that the reg class contains. If the
5352 // types are identical size, use a bitcast to convert (e.g. two differing
5354 EVT RegVT = *PhysReg.second->vt_begin();
5355 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5356 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5357 RegVT, OpInfo.CallOperand);
5358 OpInfo.ConstraintVT = RegVT;
5359 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5360 // If the input is a FP value and we want it in FP registers, do a
5361 // bitcast to the corresponding integer type. This turns an f64 value
5362 // into i64, which can be passed with two i32 values on a 32-bit
5364 RegVT = EVT::getIntegerVT(Context,
5365 OpInfo.ConstraintVT.getSizeInBits());
5366 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5367 RegVT, OpInfo.CallOperand);
5368 OpInfo.ConstraintVT = RegVT;
5372 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5376 EVT ValueVT = OpInfo.ConstraintVT;
5378 // If this is a constraint for a specific physical register, like {r17},
5380 if (unsigned AssignedReg = PhysReg.first) {
5381 const TargetRegisterClass *RC = PhysReg.second;
5382 if (OpInfo.ConstraintVT == MVT::Other)
5383 ValueVT = *RC->vt_begin();
5385 // Get the actual register value type. This is important, because the user
5386 // may have asked for (e.g.) the AX register in i32 type. We need to
5387 // remember that AX is actually i16 to get the right extension.
5388 RegVT = *RC->vt_begin();
5390 // This is a explicit reference to a physical register.
5391 Regs.push_back(AssignedReg);
5393 // If this is an expanded reference, add the rest of the regs to Regs.
5395 TargetRegisterClass::iterator I = RC->begin();
5396 for (; *I != AssignedReg; ++I)
5397 assert(I != RC->end() && "Didn't find reg!");
5399 // Already added the first reg.
5401 for (; NumRegs; --NumRegs, ++I) {
5402 assert(I != RC->end() && "Ran out of registers to allocate!");
5406 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5407 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5408 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5412 // Otherwise, if this was a reference to an LLVM register class, create vregs
5413 // for this reference.
5414 if (const TargetRegisterClass *RC = PhysReg.second) {
5415 RegVT = *RC->vt_begin();
5416 if (OpInfo.ConstraintVT == MVT::Other)
5419 // Create the appropriate number of virtual registers.
5420 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5421 for (; NumRegs; --NumRegs)
5422 Regs.push_back(RegInfo.createVirtualRegister(RC));
5424 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5428 // This is a reference to a register class that doesn't directly correspond
5429 // to an LLVM register class. Allocate NumRegs consecutive, available,
5430 // registers from the class.
5431 std::vector<unsigned> RegClassRegs
5432 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5433 OpInfo.ConstraintVT);
5435 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5436 unsigned NumAllocated = 0;
5437 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5438 unsigned Reg = RegClassRegs[i];
5439 // See if this register is available.
5440 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5441 (isInReg && InputRegs.count(Reg))) { // Already used.
5442 // Make sure we find consecutive registers.
5447 // Check to see if this register is allocatable (i.e. don't give out the
5449 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5450 if (!RC) { // Couldn't allocate this register.
5451 // Reset NumAllocated to make sure we return consecutive registers.
5456 // Okay, this register is good, we can use it.
5459 // If we allocated enough consecutive registers, succeed.
5460 if (NumAllocated == NumRegs) {
5461 unsigned RegStart = (i-NumAllocated)+1;
5462 unsigned RegEnd = i+1;
5463 // Mark all of the allocated registers used.
5464 for (unsigned i = RegStart; i != RegEnd; ++i)
5465 Regs.push_back(RegClassRegs[i]);
5467 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5468 OpInfo.ConstraintVT);
5469 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5474 // Otherwise, we couldn't allocate enough registers for this.
5477 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5478 /// processed uses a memory 'm' constraint.
5480 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5481 const TargetLowering &TLI) {
5482 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5483 InlineAsm::ConstraintInfo &CI = CInfos[i];
5484 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5485 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5486 if (CType == TargetLowering::C_Memory)
5490 // Indirect operand accesses access memory.
5498 /// visitInlineAsm - Handle a call to an InlineAsm object.
5500 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5501 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5503 /// ConstraintOperands - Information about all of the constraints.
5504 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5506 std::set<unsigned> OutputRegs, InputRegs;
5508 // Do a prepass over the constraints, canonicalizing them, and building up the
5509 // ConstraintOperands list.
5510 std::vector<InlineAsm::ConstraintInfo>
5511 ConstraintInfos = IA->ParseConstraints();
5513 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5515 SDValue Chain, Flag;
5517 // We won't need to flush pending loads if this asm doesn't touch
5518 // memory and is nonvolatile.
5519 if (hasMemory || IA->hasSideEffects())
5522 Chain = DAG.getRoot();
5524 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5525 unsigned ResNo = 0; // ResNo - The result number of the next output.
5526 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5527 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5528 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5530 EVT OpVT = MVT::Other;
5532 // Compute the value type for each operand.
5533 switch (OpInfo.Type) {
5534 case InlineAsm::isOutput:
5535 // Indirect outputs just consume an argument.
5536 if (OpInfo.isIndirect) {
5537 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5541 // The return value of the call is this value. As such, there is no
5542 // corresponding argument.
5543 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5545 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5546 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5548 assert(ResNo == 0 && "Asm only has one result!");
5549 OpVT = TLI.getValueType(CS.getType());
5553 case InlineAsm::isInput:
5554 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5556 case InlineAsm::isClobber:
5561 // If this is an input or an indirect output, process the call argument.
5562 // BasicBlocks are labels, currently appearing only in asm's.
5563 if (OpInfo.CallOperandVal) {
5564 // Strip bitcasts, if any. This mostly comes up for functions.
5565 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5567 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5568 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5570 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5573 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5576 OpInfo.ConstraintVT = OpVT;
5579 // Second pass over the constraints: compute which constraint option to use
5580 // and assign registers to constraints that want a specific physreg.
5581 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5582 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5584 // If this is an output operand with a matching input operand, look up the
5585 // matching input. If their types mismatch, e.g. one is an integer, the
5586 // other is floating point, or their sizes are different, flag it as an
5588 if (OpInfo.hasMatchingInput()) {
5589 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5590 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5591 if ((OpInfo.ConstraintVT.isInteger() !=
5592 Input.ConstraintVT.isInteger()) ||
5593 (OpInfo.ConstraintVT.getSizeInBits() !=
5594 Input.ConstraintVT.getSizeInBits())) {
5595 llvm_report_error("Unsupported asm: input constraint"
5596 " with a matching output constraint of incompatible"
5599 Input.ConstraintVT = OpInfo.ConstraintVT;
5603 // Compute the constraint code and ConstraintType to use.
5604 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5606 // If this is a memory input, and if the operand is not indirect, do what we
5607 // need to to provide an address for the memory input.
5608 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5609 !OpInfo.isIndirect) {
5610 assert(OpInfo.Type == InlineAsm::isInput &&
5611 "Can only indirectify direct input operands!");
5613 // Memory operands really want the address of the value. If we don't have
5614 // an indirect input, put it in the constpool if we can, otherwise spill
5615 // it to a stack slot.
5617 // If the operand is a float, integer, or vector constant, spill to a
5618 // constant pool entry to get its address.
5619 Value *OpVal = OpInfo.CallOperandVal;
5620 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5621 isa<ConstantVector>(OpVal)) {
5622 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5623 TLI.getPointerTy());
5625 // Otherwise, create a stack slot and emit a store to it before the
5627 const Type *Ty = OpVal->getType();
5628 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5629 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5630 MachineFunction &MF = DAG.getMachineFunction();
5631 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5632 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5633 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5634 OpInfo.CallOperand, StackSlot, NULL, 0);
5635 OpInfo.CallOperand = StackSlot;
5638 // There is no longer a Value* corresponding to this operand.
5639 OpInfo.CallOperandVal = 0;
5640 // It is now an indirect operand.
5641 OpInfo.isIndirect = true;
5644 // If this constraint is for a specific register, allocate it before
5646 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5647 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5649 ConstraintInfos.clear();
5652 // Second pass - Loop over all of the operands, assigning virtual or physregs
5653 // to register class operands.
5654 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5655 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5657 // C_Register operands have already been allocated, Other/Memory don't need
5659 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5660 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5663 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5664 std::vector<SDValue> AsmNodeOperands;
5665 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5666 AsmNodeOperands.push_back(
5667 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5670 // Loop over all of the inputs, copying the operand values into the
5671 // appropriate registers and processing the output regs.
5672 RegsForValue RetValRegs;
5674 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5675 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5677 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5678 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5680 switch (OpInfo.Type) {
5681 case InlineAsm::isOutput: {
5682 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5683 OpInfo.ConstraintType != TargetLowering::C_Register) {
5684 // Memory output, or 'other' output (e.g. 'X' constraint).
5685 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5687 // Add information to the INLINEASM node to know about this output.
5688 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5689 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5690 TLI.getPointerTy()));
5691 AsmNodeOperands.push_back(OpInfo.CallOperand);
5695 // Otherwise, this is a register or register class output.
5697 // Copy the output from the appropriate register. Find a register that
5699 if (OpInfo.AssignedRegs.Regs.empty()) {
5700 llvm_report_error("Couldn't allocate output reg for"
5701 " constraint '" + OpInfo.ConstraintCode + "'!");
5704 // If this is an indirect operand, store through the pointer after the
5706 if (OpInfo.isIndirect) {
5707 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5708 OpInfo.CallOperandVal));
5710 // This is the result value of the call.
5711 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5713 // Concatenate this output onto the outputs list.
5714 RetValRegs.append(OpInfo.AssignedRegs);
5717 // Add information to the INLINEASM node to know that this register is
5719 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5720 6 /* EARLYCLOBBER REGDEF */ :
5724 DAG, AsmNodeOperands);
5727 case InlineAsm::isInput: {
5728 SDValue InOperandVal = OpInfo.CallOperand;
5730 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5731 // If this is required to match an output register we have already set,
5732 // just use its register.
5733 unsigned OperandNo = OpInfo.getMatchedOperand();
5735 // Scan until we find the definition we already emitted of this operand.
5736 // When we find it, create a RegsForValue operand.
5737 unsigned CurOp = 2; // The first operand.
5738 for (; OperandNo; --OperandNo) {
5739 // Advance to the next operand.
5741 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5742 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5743 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5744 (OpFlag & 7) == 4 /*MEM*/) &&
5745 "Skipped past definitions?");
5746 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5750 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5751 if ((OpFlag & 7) == 2 /*REGDEF*/
5752 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5753 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5754 if (OpInfo.isIndirect) {
5755 llvm_report_error("Don't know how to handle tied indirect "
5756 "register inputs yet!");
5758 RegsForValue MatchedRegs;
5759 MatchedRegs.TLI = &TLI;
5760 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5761 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5762 MatchedRegs.RegVTs.push_back(RegVT);
5763 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5764 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5767 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5769 // Use the produced MatchedRegs object to
5770 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5772 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5773 true, OpInfo.getMatchedOperand(),
5774 DAG, AsmNodeOperands);
5777 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5778 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5779 "Unexpected number of operands");
5780 // Add information to the INLINEASM node to know about this input.
5781 // See InlineAsm.h isUseOperandTiedToDef.
5782 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5783 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5784 TLI.getPointerTy()));
5785 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5790 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5791 assert(!OpInfo.isIndirect &&
5792 "Don't know how to handle indirect other inputs yet!");
5794 std::vector<SDValue> Ops;
5795 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5796 hasMemory, Ops, DAG);
5798 llvm_report_error("Invalid operand for inline asm"
5799 " constraint '" + OpInfo.ConstraintCode + "'!");
5802 // Add information to the INLINEASM node to know about this input.
5803 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5804 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5805 TLI.getPointerTy()));
5806 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5808 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5809 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5810 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5811 "Memory operands expect pointer values");
5813 // Add information to the INLINEASM node to know about this input.
5814 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5815 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5816 TLI.getPointerTy()));
5817 AsmNodeOperands.push_back(InOperandVal);
5821 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5822 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5823 "Unknown constraint type!");
5824 assert(!OpInfo.isIndirect &&
5825 "Don't know how to handle indirect register inputs yet!");
5827 // Copy the input into the appropriate registers.
5828 if (OpInfo.AssignedRegs.Regs.empty()) {
5829 llvm_report_error("Couldn't allocate input reg for"
5830 " constraint '"+ OpInfo.ConstraintCode +"'!");
5833 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5836 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5837 DAG, AsmNodeOperands);
5840 case InlineAsm::isClobber: {
5841 // Add the clobbered value to the operand list, so that the register
5842 // allocator is aware that the physreg got clobbered.
5843 if (!OpInfo.AssignedRegs.Regs.empty())
5844 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5845 false, 0, DAG,AsmNodeOperands);
5851 // Finish up input operands.
5852 AsmNodeOperands[0] = Chain;
5853 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5855 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5856 DAG.getVTList(MVT::Other, MVT::Flag),
5857 &AsmNodeOperands[0], AsmNodeOperands.size());
5858 Flag = Chain.getValue(1);
5860 // If this asm returns a register value, copy the result from that register
5861 // and set it as the value of the call.
5862 if (!RetValRegs.Regs.empty()) {
5863 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5866 // FIXME: Why don't we do this for inline asms with MRVs?
5867 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5868 EVT ResultType = TLI.getValueType(CS.getType());
5870 // If any of the results of the inline asm is a vector, it may have the
5871 // wrong width/num elts. This can happen for register classes that can
5872 // contain multiple different value types. The preg or vreg allocated may
5873 // not have the same VT as was expected. Convert it to the right type
5874 // with bit_convert.
5875 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5876 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5879 } else if (ResultType != Val.getValueType() &&
5880 ResultType.isInteger() && Val.getValueType().isInteger()) {
5881 // If a result value was tied to an input value, the computed result may
5882 // have a wider width than the expected result. Extract the relevant
5884 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5887 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5890 setValue(CS.getInstruction(), Val);
5891 // Don't need to use this as a chain in this case.
5892 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5896 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5898 // Process indirect outputs, first output all of the flagged copies out of
5900 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5901 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5902 Value *Ptr = IndirectStoresToEmit[i].second;
5903 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5905 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5909 // Emit the non-flagged stores from the physregs.
5910 SmallVector<SDValue, 8> OutChains;
5911 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5912 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5913 StoresToEmit[i].first,
5914 getValue(StoresToEmit[i].second),
5915 StoresToEmit[i].second, 0));
5916 if (!OutChains.empty())
5917 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5918 &OutChains[0], OutChains.size());
5922 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
5923 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5924 MVT::Other, getRoot(),
5925 getValue(I.getOperand(1)),
5926 DAG.getSrcValue(I.getOperand(1))));
5929 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
5930 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5931 getRoot(), getValue(I.getOperand(0)),
5932 DAG.getSrcValue(I.getOperand(0)));
5934 DAG.setRoot(V.getValue(1));
5937 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
5938 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5939 MVT::Other, getRoot(),
5940 getValue(I.getOperand(1)),
5941 DAG.getSrcValue(I.getOperand(1))));
5944 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
5945 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5946 MVT::Other, getRoot(),
5947 getValue(I.getOperand(1)),
5948 getValue(I.getOperand(2)),
5949 DAG.getSrcValue(I.getOperand(1)),
5950 DAG.getSrcValue(I.getOperand(2))));
5953 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5954 /// implementation, which just calls LowerCall.
5955 /// FIXME: When all targets are
5956 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5957 std::pair<SDValue, SDValue>
5958 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5959 bool RetSExt, bool RetZExt, bool isVarArg,
5960 bool isInreg, unsigned NumFixedArgs,
5961 CallingConv::ID CallConv, bool isTailCall,
5962 bool isReturnValueUsed,
5964 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5966 assert((!isTailCall || PerformTailCallOpt) &&
5967 "isTailCall set when tail-call optimizations are disabled!");
5969 // Handle all of the outgoing arguments.
5970 SmallVector<ISD::OutputArg, 32> Outs;
5971 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5972 SmallVector<EVT, 4> ValueVTs;
5973 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5974 for (unsigned Value = 0, NumValues = ValueVTs.size();
5975 Value != NumValues; ++Value) {
5976 EVT VT = ValueVTs[Value];
5977 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5978 SDValue Op = SDValue(Args[i].Node.getNode(),
5979 Args[i].Node.getResNo() + Value);
5980 ISD::ArgFlagsTy Flags;
5981 unsigned OriginalAlignment =
5982 getTargetData()->getABITypeAlignment(ArgTy);
5988 if (Args[i].isInReg)
5992 if (Args[i].isByVal) {
5994 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5995 const Type *ElementTy = Ty->getElementType();
5996 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5997 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5998 // For ByVal, alignment should come from FE. BE will guess if this
5999 // info is not there but there are cases it cannot get right.
6000 if (Args[i].Alignment)
6001 FrameAlign = Args[i].Alignment;
6002 Flags.setByValAlign(FrameAlign);
6003 Flags.setByValSize(FrameSize);
6007 Flags.setOrigAlign(OriginalAlignment);
6009 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6010 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6011 SmallVector<SDValue, 4> Parts(NumParts);
6012 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6015 ExtendKind = ISD::SIGN_EXTEND;
6016 else if (Args[i].isZExt)
6017 ExtendKind = ISD::ZERO_EXTEND;
6019 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
6021 for (unsigned j = 0; j != NumParts; ++j) {
6022 // if it isn't first piece, alignment must be 1
6023 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
6024 if (NumParts > 1 && j == 0)
6025 MyFlags.Flags.setSplit();
6027 MyFlags.Flags.setOrigAlign(1);
6029 Outs.push_back(MyFlags);
6034 // Handle the incoming return values from the call.
6035 SmallVector<ISD::InputArg, 32> Ins;
6036 SmallVector<EVT, 4> RetTys;
6037 ComputeValueVTs(*this, RetTy, RetTys);
6038 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6040 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6041 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6042 for (unsigned i = 0; i != NumRegs; ++i) {
6043 ISD::InputArg MyFlags;
6044 MyFlags.VT = RegisterVT;
6045 MyFlags.Used = isReturnValueUsed;
6047 MyFlags.Flags.setSExt();
6049 MyFlags.Flags.setZExt();
6051 MyFlags.Flags.setInReg();
6052 Ins.push_back(MyFlags);
6056 // Check if target-dependent constraints permit a tail call here.
6057 // Target-independent constraints should be checked by the caller.
6059 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
6062 SmallVector<SDValue, 4> InVals;
6063 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6064 Outs, Ins, dl, DAG, InVals);
6066 // Verify that the target's LowerCall behaved as expected.
6067 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6068 "LowerCall didn't return a valid chain!");
6069 assert((!isTailCall || InVals.empty()) &&
6070 "LowerCall emitted a return value for a tail call!");
6071 assert((isTailCall || InVals.size() == Ins.size()) &&
6072 "LowerCall didn't emit the correct number of values!");
6073 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6074 assert(InVals[i].getNode() &&
6075 "LowerCall emitted a null value!");
6076 assert(Ins[i].VT == InVals[i].getValueType() &&
6077 "LowerCall emitted a value with the wrong type!");
6080 // For a tail call, the return value is merely live-out and there aren't
6081 // any nodes in the DAG representing it. Return a special value to
6082 // indicate that a tail call has been emitted and no more Instructions
6083 // should be processed in the current block.
6086 return std::make_pair(SDValue(), SDValue());
6089 // Collect the legal value parts into potentially illegal values
6090 // that correspond to the original function's return values.
6091 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6093 AssertOp = ISD::AssertSext;
6095 AssertOp = ISD::AssertZext;
6096 SmallVector<SDValue, 4> ReturnValues;
6097 unsigned CurReg = 0;
6098 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6100 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6101 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6103 SDValue ReturnValue =
6104 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
6106 ReturnValues.push_back(ReturnValue);
6110 // For a function returning void, there is no return value. We can't create
6111 // such a node, so we just return a null return value in that case. In
6112 // that case, nothing will actualy look at the value.
6113 if (ReturnValues.empty())
6114 return std::make_pair(SDValue(), Chain);
6116 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6117 DAG.getVTList(&RetTys[0], RetTys.size()),
6118 &ReturnValues[0], ReturnValues.size());
6120 return std::make_pair(Res, Chain);
6123 void TargetLowering::LowerOperationWrapper(SDNode *N,
6124 SmallVectorImpl<SDValue> &Results,
6125 SelectionDAG &DAG) {
6126 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6128 Results.push_back(Res);
6131 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6132 llvm_unreachable("LowerOperation not implemented for this target!");
6137 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
6138 SDValue Op = getValue(V);
6139 assert((Op.getOpcode() != ISD::CopyFromReg ||
6140 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6141 "Copy from a reg to the same reg!");
6142 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6144 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6145 SDValue Chain = DAG.getEntryNode();
6146 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6147 PendingExports.push_back(Chain);
6150 #include "llvm/CodeGen/SelectionDAGISel.h"
6152 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
6153 // If this is the entry block, emit arguments.
6154 Function &F = *LLVMBB->getParent();
6155 SelectionDAG &DAG = SDB->DAG;
6156 SDValue OldRoot = DAG.getRoot();
6157 DebugLoc dl = SDB->getCurDebugLoc();
6158 const TargetData *TD = TLI.getTargetData();
6159 SmallVector<ISD::InputArg, 16> Ins;
6161 // Check whether the function can return without sret-demotion.
6162 SmallVector<EVT, 4> OutVTs;
6163 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
6164 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6165 OutVTs, OutsFlags, TLI);
6166 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
6168 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
6169 OutVTs, OutsFlags, DAG);
6170 if (!FLI.CanLowerReturn) {
6171 // Put in an sret pointer parameter before all the other parameters.
6172 SmallVector<EVT, 1> ValueVTs;
6173 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6175 // NOTE: Assuming that a pointer will never break down to more than one VT
6177 ISD::ArgFlagsTy Flags;
6179 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
6180 ISD::InputArg RetArg(Flags, RegisterVT, true);
6181 Ins.push_back(RetArg);
6184 // Set up the incoming argument description vector.
6186 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
6187 I != E; ++I, ++Idx) {
6188 SmallVector<EVT, 4> ValueVTs;
6189 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6190 bool isArgValueUsed = !I->use_empty();
6191 for (unsigned Value = 0, NumValues = ValueVTs.size();
6192 Value != NumValues; ++Value) {
6193 EVT VT = ValueVTs[Value];
6194 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6195 ISD::ArgFlagsTy Flags;
6196 unsigned OriginalAlignment =
6197 TD->getABITypeAlignment(ArgTy);
6199 if (F.paramHasAttr(Idx, Attribute::ZExt))
6201 if (F.paramHasAttr(Idx, Attribute::SExt))
6203 if (F.paramHasAttr(Idx, Attribute::InReg))
6205 if (F.paramHasAttr(Idx, Attribute::StructRet))
6207 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6209 const PointerType *Ty = cast<PointerType>(I->getType());
6210 const Type *ElementTy = Ty->getElementType();
6211 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6212 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
6213 // For ByVal, alignment should be passed from FE. BE will guess if
6214 // this info is not there but there are cases it cannot get right.
6215 if (F.getParamAlignment(Idx))
6216 FrameAlign = F.getParamAlignment(Idx);
6217 Flags.setByValAlign(FrameAlign);
6218 Flags.setByValSize(FrameSize);
6220 if (F.paramHasAttr(Idx, Attribute::Nest))
6222 Flags.setOrigAlign(OriginalAlignment);
6224 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6225 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6226 for (unsigned i = 0; i != NumRegs; ++i) {
6227 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6228 if (NumRegs > 1 && i == 0)
6229 MyFlags.Flags.setSplit();
6230 // if it isn't first piece, alignment must be 1
6232 MyFlags.Flags.setOrigAlign(1);
6233 Ins.push_back(MyFlags);
6238 // Call the target to set up the argument values.
6239 SmallVector<SDValue, 8> InVals;
6240 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6244 // Verify that the target's LowerFormalArguments behaved as expected.
6245 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6246 "LowerFormalArguments didn't return a valid chain!");
6247 assert(InVals.size() == Ins.size() &&
6248 "LowerFormalArguments didn't emit the correct number of values!");
6249 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6250 assert(InVals[i].getNode() &&
6251 "LowerFormalArguments emitted a null value!");
6252 assert(Ins[i].VT == InVals[i].getValueType() &&
6253 "LowerFormalArguments emitted a value with the wrong type!");
6256 // Update the DAG with the new chain value resulting from argument lowering.
6257 DAG.setRoot(NewRoot);
6259 // Set up the argument values.
6262 if (!FLI.CanLowerReturn) {
6263 // Create a virtual register for the sret pointer, and put in a copy
6264 // from the sret argument into it.
6265 SmallVector<EVT, 1> ValueVTs;
6266 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6267 EVT VT = ValueVTs[0];
6268 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6269 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6270 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
6273 MachineFunction& MF = SDB->DAG.getMachineFunction();
6274 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6275 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6276 FLI.DemoteRegister = SRetReg;
6277 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue);
6278 DAG.setRoot(NewRoot);
6280 // i indexes lowered arguments. Bump it past the hidden sret argument.
6281 // Idx indexes LLVM arguments. Don't touch it.
6284 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6286 SmallVector<SDValue, 4> ArgValues;
6287 SmallVector<EVT, 4> ValueVTs;
6288 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6289 unsigned NumValues = ValueVTs.size();
6290 for (unsigned Value = 0; Value != NumValues; ++Value) {
6291 EVT VT = ValueVTs[Value];
6292 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6293 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6295 if (!I->use_empty()) {
6296 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6297 if (F.paramHasAttr(Idx, Attribute::SExt))
6298 AssertOp = ISD::AssertSext;
6299 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6300 AssertOp = ISD::AssertZext;
6302 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
6303 PartVT, VT, AssertOp));
6307 if (!I->use_empty()) {
6308 SDB->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
6309 SDB->getCurDebugLoc()));
6310 // If this argument is live outside of the entry block, insert a copy from
6311 // whereever we got it to the vreg that other BB's will reference it as.
6312 SDB->CopyToExportRegsIfNeeded(I);
6315 assert(i == InVals.size() && "Argument register count mismatch!");
6317 // Finally, if the target has anything special to do, allow it to do so.
6318 // FIXME: this should insert code into the DAG!
6319 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6322 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6323 /// ensure constants are generated when needed. Remember the virtual registers
6324 /// that need to be added to the Machine PHI nodes as input. We cannot just
6325 /// directly add them, because expansion might result in multiple MBB's for one
6326 /// BB. As such, the start of the BB might correspond to a different MBB than
6330 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6331 TerminatorInst *TI = LLVMBB->getTerminator();
6333 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6335 // Check successor nodes' PHI nodes that expect a constant to be available
6337 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6338 BasicBlock *SuccBB = TI->getSuccessor(succ);
6339 if (!isa<PHINode>(SuccBB->begin())) continue;
6340 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6342 // If this terminator has multiple identical successors (common for
6343 // switches), only handle each succ once.
6344 if (!SuccsHandled.insert(SuccMBB)) continue;
6346 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6349 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6350 // nodes and Machine PHI nodes, but the incoming operands have not been
6352 for (BasicBlock::iterator I = SuccBB->begin();
6353 (PN = dyn_cast<PHINode>(I)); ++I) {
6354 // Ignore dead phi's.
6355 if (PN->use_empty()) continue;
6358 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6360 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6361 unsigned &RegOut = SDB->ConstantsOut[C];
6363 RegOut = FuncInfo->CreateRegForValue(C);
6364 SDB->CopyValueToVirtualRegister(C, RegOut);
6368 Reg = FuncInfo->ValueMap[PHIOp];
6370 assert(isa<AllocaInst>(PHIOp) &&
6371 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6372 "Didn't codegen value into a register!??");
6373 Reg = FuncInfo->CreateRegForValue(PHIOp);
6374 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6378 // Remember that this register needs to added to the machine PHI node as
6379 // the input for this MBB.
6380 SmallVector<EVT, 4> ValueVTs;
6381 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6382 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6383 EVT VT = ValueVTs[vti];
6384 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6385 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6386 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6387 Reg += NumRegisters;
6391 SDB->ConstantsOut.clear();
6394 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6395 /// supports legal types, and it emits MachineInstrs directly instead of
6396 /// creating SelectionDAG nodes.
6399 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6401 TerminatorInst *TI = LLVMBB->getTerminator();
6403 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6404 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6406 // Check successor nodes' PHI nodes that expect a constant to be available
6408 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6409 BasicBlock *SuccBB = TI->getSuccessor(succ);
6410 if (!isa<PHINode>(SuccBB->begin())) continue;
6411 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6413 // If this terminator has multiple identical successors (common for
6414 // switches), only handle each succ once.
6415 if (!SuccsHandled.insert(SuccMBB)) continue;
6417 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6420 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6421 // nodes and Machine PHI nodes, but the incoming operands have not been
6423 for (BasicBlock::iterator I = SuccBB->begin();
6424 (PN = dyn_cast<PHINode>(I)); ++I) {
6425 // Ignore dead phi's.
6426 if (PN->use_empty()) continue;
6428 // Only handle legal types. Two interesting things to note here. First,
6429 // by bailing out early, we may leave behind some dead instructions,
6430 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6431 // own moves. Second, this check is necessary becuase FastISel doesn't
6432 // use CreateRegForValue to create registers, so it always creates
6433 // exactly one register for each non-void instruction.
6434 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6435 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6438 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6440 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6445 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6447 unsigned Reg = F->getRegForValue(PHIOp);
6449 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6452 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));