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 "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "FunctionLoweringInfo.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FastISel.h"
35 #include "llvm/CodeGen/GCStrategy.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineJumpTableInfo.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/PseudoSourceValue.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/Analysis/DebugInfo.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Target/TargetFrameInfo.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
62 /// LimitFloatPrecision - Generate low-precision inline sequences for
63 /// some float libcalls (6, 8 or 12 bits).
64 static unsigned LimitFloatPrecision;
66 static cl::opt<unsigned, true>
67 LimitFPPrecision("limit-float-precision",
68 cl::desc("Generate low-precision inline sequences "
69 "for some float libcalls"),
70 cl::location(LimitFloatPrecision),
73 /// getCopyFromParts - Create a value that contains the specified legal parts
74 /// combined into the value they represent. If the parts combine to a type
75 /// larger then ValueVT then AssertOp can be used to specify whether the extra
76 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
77 /// (ISD::AssertSext).
78 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
80 unsigned NumParts, EVT PartVT, EVT ValueVT,
81 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
82 assert(NumParts > 0 && "No parts to assemble!");
83 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
84 SDValue Val = Parts[0];
87 // Assemble the value from multiple parts.
88 if (!ValueVT.isVector() && ValueVT.isInteger()) {
89 unsigned PartBits = PartVT.getSizeInBits();
90 unsigned ValueBits = ValueVT.getSizeInBits();
92 // Assemble the power of 2 part.
93 unsigned RoundParts = NumParts & (NumParts - 1) ?
94 1 << Log2_32(NumParts) : NumParts;
95 unsigned RoundBits = PartBits * RoundParts;
96 EVT RoundVT = RoundBits == ValueBits ?
97 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
100 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
102 if (RoundParts > 2) {
103 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2,
105 Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2,
106 RoundParts / 2, PartVT, HalfVT);
108 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
109 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
112 if (TLI.isBigEndian())
115 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
117 if (RoundParts < NumParts) {
118 // Assemble the trailing non-power-of-2 part.
119 unsigned OddParts = NumParts - RoundParts;
120 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
121 Hi = getCopyFromParts(DAG, dl,
122 Parts + RoundParts, OddParts, PartVT, OddVT);
124 // Combine the round and odd parts.
126 if (TLI.isBigEndian())
128 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
129 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
130 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
131 DAG.getConstant(Lo.getValueType().getSizeInBits(),
132 TLI.getPointerTy()));
133 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
134 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
136 } else if (ValueVT.isVector()) {
137 // Handle a multi-element vector.
138 EVT IntermediateVT, RegisterVT;
139 unsigned NumIntermediates;
141 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
142 NumIntermediates, RegisterVT);
143 assert(NumRegs == NumParts
144 && "Part count doesn't match vector breakdown!");
145 NumParts = NumRegs; // Silence a compiler warning.
146 assert(RegisterVT == PartVT
147 && "Part type doesn't match vector breakdown!");
148 assert(RegisterVT == Parts[0].getValueType() &&
149 "Part type doesn't match part!");
151 // Assemble the parts into intermediate operands.
152 SmallVector<SDValue, 8> Ops(NumIntermediates);
153 if (NumIntermediates == NumParts) {
154 // If the register was not expanded, truncate or copy the value,
156 for (unsigned i = 0; i != NumParts; ++i)
157 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
158 PartVT, IntermediateVT);
159 } else if (NumParts > 0) {
160 // If the intermediate type was expanded, build the intermediate
161 // operands from the parts.
162 assert(NumParts % NumIntermediates == 0 &&
163 "Must expand into a divisible number of parts!");
164 unsigned Factor = NumParts / NumIntermediates;
165 for (unsigned i = 0; i != NumIntermediates; ++i)
166 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
167 PartVT, IntermediateVT);
170 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
171 // intermediate operands.
172 Val = DAG.getNode(IntermediateVT.isVector() ?
173 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
174 ValueVT, &Ops[0], NumIntermediates);
175 } else if (PartVT.isFloatingPoint()) {
176 // FP split into multiple FP parts (for ppcf128)
177 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
180 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
181 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
182 if (TLI.isBigEndian())
184 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
186 // FP split into integer parts (soft fp)
187 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
188 !PartVT.isVector() && "Unexpected split");
189 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
190 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
194 // There is now one part, held in Val. Correct it to match ValueVT.
195 PartVT = Val.getValueType();
197 if (PartVT == ValueVT)
200 if (PartVT.isVector()) {
201 assert(ValueVT.isVector() && "Unknown vector conversion!");
202 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
205 if (ValueVT.isVector()) {
206 assert(ValueVT.getVectorElementType() == PartVT &&
207 ValueVT.getVectorNumElements() == 1 &&
208 "Only trivial scalar-to-vector conversions should get here!");
209 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
212 if (PartVT.isInteger() &&
213 ValueVT.isInteger()) {
214 if (ValueVT.bitsLT(PartVT)) {
215 // For a truncate, see if we have any information to
216 // indicate whether the truncated bits will always be
217 // zero or sign-extension.
218 if (AssertOp != ISD::DELETED_NODE)
219 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
220 DAG.getValueType(ValueVT));
221 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
223 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
227 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
228 if (ValueVT.bitsLT(Val.getValueType())) {
229 // FP_ROUND's are always exact here.
230 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
231 DAG.getIntPtrConstant(1));
234 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
237 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
238 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
240 llvm_unreachable("Unknown mismatch!");
244 /// getCopyToParts - Create a series of nodes that contain the specified value
245 /// split into legal parts. If the parts contain more bits than Val, then, for
246 /// integers, ExtendKind can be used to specify how to generate the extra bits.
247 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl,
248 SDValue Val, SDValue *Parts, unsigned NumParts,
250 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
251 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
252 EVT PtrVT = TLI.getPointerTy();
253 EVT ValueVT = Val.getValueType();
254 unsigned PartBits = PartVT.getSizeInBits();
255 unsigned OrigNumParts = NumParts;
256 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
261 if (!ValueVT.isVector()) {
262 if (PartVT == ValueVT) {
263 assert(NumParts == 1 && "No-op copy with multiple parts!");
268 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
269 // If the parts cover more bits than the value has, promote the value.
270 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
271 assert(NumParts == 1 && "Do not know what to promote to!");
272 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
273 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
274 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
275 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
277 llvm_unreachable("Unknown mismatch!");
279 } else if (PartBits == ValueVT.getSizeInBits()) {
280 // Different types of the same size.
281 assert(NumParts == 1 && PartVT != ValueVT);
282 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
283 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
284 // If the parts cover less bits than value has, truncate the value.
285 if (PartVT.isInteger() && ValueVT.isInteger()) {
286 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
287 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
289 llvm_unreachable("Unknown mismatch!");
293 // The value may have changed - recompute ValueVT.
294 ValueVT = Val.getValueType();
295 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
296 "Failed to tile the value with PartVT!");
299 assert(PartVT == ValueVT && "Type conversion failed!");
304 // Expand the value into multiple parts.
305 if (NumParts & (NumParts - 1)) {
306 // The number of parts is not a power of 2. Split off and copy the tail.
307 assert(PartVT.isInteger() && ValueVT.isInteger() &&
308 "Do not know what to expand to!");
309 unsigned RoundParts = 1 << Log2_32(NumParts);
310 unsigned RoundBits = RoundParts * PartBits;
311 unsigned OddParts = NumParts - RoundParts;
312 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
313 DAG.getConstant(RoundBits,
314 TLI.getPointerTy()));
315 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts,
318 if (TLI.isBigEndian())
319 // The odd parts were reversed by getCopyToParts - unreverse them.
320 std::reverse(Parts + RoundParts, Parts + NumParts);
322 NumParts = RoundParts;
323 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
324 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
327 // The number of parts is a power of 2. Repeatedly bisect the value using
329 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
330 EVT::getIntegerVT(*DAG.getContext(),
331 ValueVT.getSizeInBits()),
334 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
335 for (unsigned i = 0; i < NumParts; i += StepSize) {
336 unsigned ThisBits = StepSize * PartBits / 2;
337 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
338 SDValue &Part0 = Parts[i];
339 SDValue &Part1 = Parts[i+StepSize/2];
341 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
343 DAG.getConstant(1, PtrVT));
344 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
346 DAG.getConstant(0, PtrVT));
348 if (ThisBits == PartBits && ThisVT != PartVT) {
349 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
351 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
357 if (TLI.isBigEndian())
358 std::reverse(Parts, Parts + OrigNumParts);
365 if (PartVT != ValueVT) {
366 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
367 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
369 assert(ValueVT.getVectorElementType() == PartVT &&
370 ValueVT.getVectorNumElements() == 1 &&
371 "Only trivial vector-to-scalar conversions should get here!");
372 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
374 DAG.getConstant(0, PtrVT));
382 // Handle a multi-element vector.
383 EVT IntermediateVT, RegisterVT;
384 unsigned NumIntermediates;
385 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
386 IntermediateVT, NumIntermediates, RegisterVT);
387 unsigned NumElements = ValueVT.getVectorNumElements();
389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390 NumParts = NumRegs; // Silence a compiler warning.
391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
393 // Split the vector into intermediate operands.
394 SmallVector<SDValue, 8> Ops(NumIntermediates);
395 for (unsigned i = 0; i != NumIntermediates; ++i) {
396 if (IntermediateVT.isVector())
397 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
399 DAG.getConstant(i * (NumElements / NumIntermediates),
402 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
404 DAG.getConstant(i, PtrVT));
407 // Split the intermediate operands into legal parts.
408 if (NumParts == NumIntermediates) {
409 // If the register was not expanded, promote or copy the value,
411 for (unsigned i = 0; i != NumParts; ++i)
412 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
413 } else if (NumParts > 0) {
414 // If the intermediate type was expanded, split each the value into
416 assert(NumParts % NumIntermediates == 0 &&
417 "Must expand into a divisible number of parts!");
418 unsigned Factor = NumParts / NumIntermediates;
419 for (unsigned i = 0; i != NumIntermediates; ++i)
420 getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT);
425 /// RegsForValue - This struct represents the registers (physical or virtual)
426 /// that a particular set of values is assigned, and the type information
427 /// about the value. The most common situation is to represent one value at a
428 /// time, but struct or array values are handled element-wise as multiple
429 /// values. The splitting of aggregates is performed recursively, so that we
430 /// never have aggregate-typed registers. The values at this point do not
431 /// necessarily have legal types, so each value may require one or more
432 /// registers of some legal type.
434 struct RegsForValue {
435 /// ValueVTs - The value types of the values, which may not be legal, and
436 /// may need be promoted or synthesized from one or more registers.
438 SmallVector<EVT, 4> ValueVTs;
440 /// RegVTs - The value types of the registers. This is the same size as
441 /// ValueVTs and it records, for each value, what the type of the assigned
442 /// register or registers are. (Individual values are never synthesized
443 /// from more than one type of register.)
445 /// With virtual registers, the contents of RegVTs is redundant with TLI's
446 /// getRegisterType member function, however when with physical registers
447 /// it is necessary to have a separate record of the types.
449 SmallVector<EVT, 4> RegVTs;
451 /// Regs - This list holds the registers assigned to the values.
452 /// Each legal or promoted value requires one register, and each
453 /// expanded value requires multiple registers.
455 SmallVector<unsigned, 4> Regs;
459 RegsForValue(const SmallVector<unsigned, 4> ®s,
460 EVT regvt, EVT valuevt)
461 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
463 RegsForValue(const SmallVector<unsigned, 4> ®s,
464 const SmallVector<EVT, 4> ®vts,
465 const SmallVector<EVT, 4> &valuevts)
466 : ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
468 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
469 unsigned Reg, const Type *Ty) {
470 ComputeValueVTs(tli, Ty, ValueVTs);
472 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
473 EVT ValueVT = ValueVTs[Value];
474 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
475 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
476 for (unsigned i = 0; i != NumRegs; ++i)
477 Regs.push_back(Reg + i);
478 RegVTs.push_back(RegisterVT);
483 /// areValueTypesLegal - Return true if types of all the values are legal.
484 bool areValueTypesLegal(const TargetLowering &TLI) {
485 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
486 EVT RegisterVT = RegVTs[Value];
487 if (!TLI.isTypeLegal(RegisterVT))
493 /// append - Add the specified values to this one.
494 void append(const RegsForValue &RHS) {
495 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
496 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
497 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
500 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
501 /// this value and returns the result as a ValueVTs value. This uses
502 /// Chain/Flag as the input and updates them for the output Chain/Flag.
503 /// If the Flag pointer is NULL, no flag is used.
504 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
506 SDValue &Chain, SDValue *Flag) const;
508 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
509 /// specified value into the registers specified by this object. This uses
510 /// Chain/Flag as the input and updates them for the output Chain/Flag.
511 /// If the Flag pointer is NULL, no flag is used.
512 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
513 SDValue &Chain, SDValue *Flag) const;
515 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
516 /// operand list. This adds the code marker, matching input operand index
517 /// (if applicable), and includes the number of values added into it.
518 void AddInlineAsmOperands(unsigned Kind,
519 bool HasMatching, unsigned MatchingIdx,
521 std::vector<SDValue> &Ops) const;
525 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
526 /// this value and returns the result as a ValueVT value. This uses
527 /// Chain/Flag as the input and updates them for the output Chain/Flag.
528 /// If the Flag pointer is NULL, no flag is used.
529 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
530 FunctionLoweringInfo &FuncInfo,
532 SDValue &Chain, SDValue *Flag) const {
533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
535 // Assemble the legal parts into the final values.
536 SmallVector<SDValue, 4> Values(ValueVTs.size());
537 SmallVector<SDValue, 8> Parts;
538 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
539 // Copy the legal parts from the registers.
540 EVT ValueVT = ValueVTs[Value];
541 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
542 EVT RegisterVT = RegVTs[Value];
544 Parts.resize(NumRegs);
545 for (unsigned i = 0; i != NumRegs; ++i) {
548 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
550 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
551 *Flag = P.getValue(2);
554 Chain = P.getValue(1);
556 // If the source register was virtual and if we know something about it,
557 // add an assert node.
558 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
559 RegisterVT.isInteger() && !RegisterVT.isVector()) {
560 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
561 if (FuncInfo.LiveOutRegInfo.size() > SlotNo) {
562 const FunctionLoweringInfo::LiveOutInfo &LOI =
563 FuncInfo.LiveOutRegInfo[SlotNo];
565 unsigned RegSize = RegisterVT.getSizeInBits();
566 unsigned NumSignBits = LOI.NumSignBits;
567 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
569 // FIXME: We capture more information than the dag can represent. For
570 // now, just use the tightest assertzext/assertsext possible.
572 EVT FromVT(MVT::Other);
573 if (NumSignBits == RegSize)
574 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
575 else if (NumZeroBits >= RegSize-1)
576 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
577 else if (NumSignBits > RegSize-8)
578 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
579 else if (NumZeroBits >= RegSize-8)
580 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
581 else if (NumSignBits > RegSize-16)
582 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
583 else if (NumZeroBits >= RegSize-16)
584 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
585 else if (NumSignBits > RegSize-32)
586 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
587 else if (NumZeroBits >= RegSize-32)
588 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
590 if (FromVT != MVT::Other)
591 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
592 RegisterVT, P, DAG.getValueType(FromVT));
599 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
600 NumRegs, RegisterVT, ValueVT);
605 return DAG.getNode(ISD::MERGE_VALUES, dl,
606 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
607 &Values[0], ValueVTs.size());
610 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
611 /// specified value into the registers specified by this object. This uses
612 /// Chain/Flag as the input and updates them for the output Chain/Flag.
613 /// If the Flag pointer is NULL, no flag is used.
614 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
615 SDValue &Chain, SDValue *Flag) const {
616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
618 // Get the list of the values's legal parts.
619 unsigned NumRegs = Regs.size();
620 SmallVector<SDValue, 8> Parts(NumRegs);
621 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
622 EVT ValueVT = ValueVTs[Value];
623 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
624 EVT RegisterVT = RegVTs[Value];
626 getCopyToParts(DAG, dl,
627 Val.getValue(Val.getResNo() + Value),
628 &Parts[Part], NumParts, RegisterVT);
632 // Copy the parts into the registers.
633 SmallVector<SDValue, 8> Chains(NumRegs);
634 for (unsigned i = 0; i != NumRegs; ++i) {
637 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
639 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
640 *Flag = Part.getValue(1);
643 Chains[i] = Part.getValue(0);
646 if (NumRegs == 1 || Flag)
647 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
648 // flagged to it. That is the CopyToReg nodes and the user are considered
649 // a single scheduling unit. If we create a TokenFactor and return it as
650 // chain, then the TokenFactor is both a predecessor (operand) of the
651 // user as well as a successor (the TF operands are flagged to the user).
652 // c1, f1 = CopyToReg
653 // c2, f2 = CopyToReg
654 // c3 = TokenFactor c1, c2
657 Chain = Chains[NumRegs-1];
659 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
662 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
663 /// operand list. This adds the code marker and includes the number of
664 /// values added into it.
665 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
666 unsigned MatchingIdx,
668 std::vector<SDValue> &Ops) const {
669 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
671 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
673 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
674 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
677 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
678 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
679 EVT RegisterVT = RegVTs[Value];
680 for (unsigned i = 0; i != NumRegs; ++i) {
681 assert(Reg < Regs.size() && "Mismatch in # registers expected");
682 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
687 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
690 TD = DAG.getTarget().getTargetData();
693 /// clear - Clear out the current SelectionDAG and the associated
694 /// state and prepare this SelectionDAGBuilder object to be used
695 /// for a new block. This doesn't clear out information about
696 /// additional blocks that are needed to complete switch lowering
697 /// or PHI node updating; that information is cleared out as it is
699 void SelectionDAGBuilder::clear() {
701 UnusedArgNodeMap.clear();
702 PendingLoads.clear();
703 PendingExports.clear();
704 CurDebugLoc = DebugLoc();
708 /// getRoot - Return the current virtual root of the Selection DAG,
709 /// flushing any PendingLoad items. This must be done before emitting
710 /// a store or any other node that may need to be ordered after any
711 /// prior load instructions.
713 SDValue SelectionDAGBuilder::getRoot() {
714 if (PendingLoads.empty())
715 return DAG.getRoot();
717 if (PendingLoads.size() == 1) {
718 SDValue Root = PendingLoads[0];
720 PendingLoads.clear();
724 // Otherwise, we have to make a token factor node.
725 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
726 &PendingLoads[0], PendingLoads.size());
727 PendingLoads.clear();
732 /// getControlRoot - Similar to getRoot, but instead of flushing all the
733 /// PendingLoad items, flush all the PendingExports items. It is necessary
734 /// to do this before emitting a terminator instruction.
736 SDValue SelectionDAGBuilder::getControlRoot() {
737 SDValue Root = DAG.getRoot();
739 if (PendingExports.empty())
742 // Turn all of the CopyToReg chains into one factored node.
743 if (Root.getOpcode() != ISD::EntryToken) {
744 unsigned i = 0, e = PendingExports.size();
745 for (; i != e; ++i) {
746 assert(PendingExports[i].getNode()->getNumOperands() > 1);
747 if (PendingExports[i].getNode()->getOperand(0) == Root)
748 break; // Don't add the root if we already indirectly depend on it.
752 PendingExports.push_back(Root);
755 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
757 PendingExports.size());
758 PendingExports.clear();
763 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
764 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
765 DAG.AssignOrdering(Node, SDNodeOrder);
767 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
768 AssignOrderingToNode(Node->getOperand(I).getNode());
771 void SelectionDAGBuilder::visit(const Instruction &I) {
772 // Set up outgoing PHI node register values before emitting the terminator.
773 if (isa<TerminatorInst>(&I))
774 HandlePHINodesInSuccessorBlocks(I.getParent());
776 CurDebugLoc = I.getDebugLoc();
778 visit(I.getOpcode(), I);
780 if (!isa<TerminatorInst>(&I) && !HasTailCall)
781 CopyToExportRegsIfNeeded(&I);
783 CurDebugLoc = DebugLoc();
786 void SelectionDAGBuilder::visitPHI(const PHINode &) {
787 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
790 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
791 // Note: this doesn't use InstVisitor, because it has to work with
792 // ConstantExpr's in addition to instructions.
794 default: llvm_unreachable("Unknown instruction type encountered!");
795 // Build the switch statement using the Instruction.def file.
796 #define HANDLE_INST(NUM, OPCODE, CLASS) \
797 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
798 #include "llvm/Instruction.def"
801 // Assign the ordering to the freshly created DAG nodes.
802 if (NodeMap.count(&I)) {
804 AssignOrderingToNode(getValue(&I).getNode());
808 SDValue SelectionDAGBuilder::getValue(const Value *V) {
809 SDValue &N = NodeMap[V];
810 if (N.getNode()) return N;
812 if (const Constant *C = dyn_cast<Constant>(V)) {
813 EVT VT = TLI.getValueType(V->getType(), true);
815 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
816 return N = DAG.getConstant(*CI, VT);
818 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
819 return N = DAG.getGlobalAddress(GV, VT);
821 if (isa<ConstantPointerNull>(C))
822 return N = DAG.getConstant(0, TLI.getPointerTy());
824 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
825 return N = DAG.getConstantFP(*CFP, VT);
827 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
828 return N = DAG.getUNDEF(VT);
830 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
831 visit(CE->getOpcode(), *CE);
832 SDValue N1 = NodeMap[V];
833 assert(N1.getNode() && "visit didn't populate the NodeMap!");
837 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
838 SmallVector<SDValue, 4> Constants;
839 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
841 SDNode *Val = getValue(*OI).getNode();
842 // If the operand is an empty aggregate, there are no values.
844 // Add each leaf value from the operand to the Constants list
845 // to form a flattened list of all the values.
846 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
847 Constants.push_back(SDValue(Val, i));
850 return DAG.getMergeValues(&Constants[0], Constants.size(),
854 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
855 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
856 "Unknown struct or array constant!");
858 SmallVector<EVT, 4> ValueVTs;
859 ComputeValueVTs(TLI, C->getType(), ValueVTs);
860 unsigned NumElts = ValueVTs.size();
862 return SDValue(); // empty struct
863 SmallVector<SDValue, 4> Constants(NumElts);
864 for (unsigned i = 0; i != NumElts; ++i) {
865 EVT EltVT = ValueVTs[i];
866 if (isa<UndefValue>(C))
867 Constants[i] = DAG.getUNDEF(EltVT);
868 else if (EltVT.isFloatingPoint())
869 Constants[i] = DAG.getConstantFP(0, EltVT);
871 Constants[i] = DAG.getConstant(0, EltVT);
874 return DAG.getMergeValues(&Constants[0], NumElts,
878 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
879 return DAG.getBlockAddress(BA, VT);
881 const VectorType *VecTy = cast<VectorType>(V->getType());
882 unsigned NumElements = VecTy->getNumElements();
884 // Now that we know the number and type of the elements, get that number of
885 // elements into the Ops array based on what kind of constant it is.
886 SmallVector<SDValue, 16> Ops;
887 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
888 for (unsigned i = 0; i != NumElements; ++i)
889 Ops.push_back(getValue(CP->getOperand(i)));
891 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
892 EVT EltVT = TLI.getValueType(VecTy->getElementType());
895 if (EltVT.isFloatingPoint())
896 Op = DAG.getConstantFP(0, EltVT);
898 Op = DAG.getConstant(0, EltVT);
899 Ops.assign(NumElements, Op);
902 // Create a BUILD_VECTOR node.
903 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
904 VT, &Ops[0], Ops.size());
907 // If this is a static alloca, generate it as the frameindex instead of
909 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
910 DenseMap<const AllocaInst*, int>::iterator SI =
911 FuncInfo.StaticAllocaMap.find(AI);
912 if (SI != FuncInfo.StaticAllocaMap.end())
913 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
916 unsigned InReg = FuncInfo.ValueMap[V];
917 assert(InReg && "Value not in map!");
919 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
920 SDValue Chain = DAG.getEntryNode();
921 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
924 /// Get the EVTs and ArgFlags collections that represent the legalized return
925 /// type of the given function. This does not require a DAG or a return value,
926 /// and is suitable for use before any DAGs for the function are constructed.
927 static void getReturnInfo(const Type* ReturnType,
928 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
929 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
930 const TargetLowering &TLI,
931 SmallVectorImpl<uint64_t> *Offsets = 0) {
932 SmallVector<EVT, 4> ValueVTs;
933 ComputeValueVTs(TLI, ReturnType, ValueVTs);
934 unsigned NumValues = ValueVTs.size();
935 if (NumValues == 0) return;
938 for (unsigned j = 0, f = NumValues; j != f; ++j) {
939 EVT VT = ValueVTs[j];
940 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
942 if (attr & Attribute::SExt)
943 ExtendKind = ISD::SIGN_EXTEND;
944 else if (attr & Attribute::ZExt)
945 ExtendKind = ISD::ZERO_EXTEND;
947 // FIXME: C calling convention requires the return type to be promoted to
948 // at least 32-bit. But this is not necessary for non-C calling
949 // conventions. The frontend should mark functions whose return values
950 // require promoting with signext or zeroext attributes.
951 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
952 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
953 if (VT.bitsLT(MinVT))
957 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
958 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
959 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
960 PartVT.getTypeForEVT(ReturnType->getContext()));
962 // 'inreg' on function refers to return value
963 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
964 if (attr & Attribute::InReg)
967 // Propagate extension type if any
968 if (attr & Attribute::SExt)
970 else if (attr & Attribute::ZExt)
973 for (unsigned i = 0; i < NumParts; ++i) {
974 OutVTs.push_back(PartVT);
975 OutFlags.push_back(Flags);
978 Offsets->push_back(Offset);
985 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
986 SDValue Chain = getControlRoot();
987 SmallVector<ISD::OutputArg, 8> Outs;
989 if (!FuncInfo.CanLowerReturn) {
990 unsigned DemoteReg = FuncInfo.DemoteRegister;
991 const Function *F = I.getParent()->getParent();
993 // Emit a store of the return value through the virtual register.
994 // Leave Outs empty so that LowerReturn won't try to load return
995 // registers the usual way.
996 SmallVector<EVT, 1> PtrValueVTs;
997 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1000 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1001 SDValue RetOp = getValue(I.getOperand(0));
1003 SmallVector<EVT, 4> ValueVTs;
1004 SmallVector<uint64_t, 4> Offsets;
1005 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1006 unsigned NumValues = ValueVTs.size();
1008 SmallVector<SDValue, 4> Chains(NumValues);
1009 EVT PtrVT = PtrValueVTs[0];
1010 for (unsigned i = 0; i != NumValues; ++i) {
1011 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
1012 DAG.getConstant(Offsets[i], PtrVT));
1014 DAG.getStore(Chain, getCurDebugLoc(),
1015 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1016 Add, NULL, Offsets[i], false, false, 0);
1019 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1020 MVT::Other, &Chains[0], NumValues);
1021 } else if (I.getNumOperands() != 0) {
1022 SmallVector<EVT, 4> ValueVTs;
1023 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1024 unsigned NumValues = ValueVTs.size();
1026 SDValue RetOp = getValue(I.getOperand(0));
1027 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1028 EVT VT = ValueVTs[j];
1030 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1032 const Function *F = I.getParent()->getParent();
1033 if (F->paramHasAttr(0, Attribute::SExt))
1034 ExtendKind = ISD::SIGN_EXTEND;
1035 else if (F->paramHasAttr(0, Attribute::ZExt))
1036 ExtendKind = ISD::ZERO_EXTEND;
1038 // FIXME: C calling convention requires the return type to be promoted
1039 // to at least 32-bit. But this is not necessary for non-C calling
1040 // conventions. The frontend should mark functions whose return values
1041 // require promoting with signext or zeroext attributes.
1042 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1043 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
1044 if (VT.bitsLT(MinVT))
1048 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1049 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1050 SmallVector<SDValue, 4> Parts(NumParts);
1051 getCopyToParts(DAG, getCurDebugLoc(),
1052 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1053 &Parts[0], NumParts, PartVT, ExtendKind);
1055 // 'inreg' on function refers to return value
1056 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1057 if (F->paramHasAttr(0, Attribute::InReg))
1060 // Propagate extension type if any
1061 if (F->paramHasAttr(0, Attribute::SExt))
1063 else if (F->paramHasAttr(0, Attribute::ZExt))
1066 for (unsigned i = 0; i < NumParts; ++i)
1067 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
1072 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1073 CallingConv::ID CallConv =
1074 DAG.getMachineFunction().getFunction()->getCallingConv();
1075 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1076 Outs, getCurDebugLoc(), DAG);
1078 // Verify that the target's LowerReturn behaved as expected.
1079 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1080 "LowerReturn didn't return a valid chain!");
1082 // Update the DAG with the new chain value resulting from return lowering.
1086 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1087 /// created for it, emit nodes to copy the value into the virtual
1089 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1090 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1091 if (VMI != FuncInfo.ValueMap.end()) {
1092 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1093 CopyValueToVirtualRegister(V, VMI->second);
1097 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1098 /// the current basic block, add it to ValueMap now so that we'll get a
1100 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1101 // No need to export constants.
1102 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1104 // Already exported?
1105 if (FuncInfo.isExportedInst(V)) return;
1107 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1108 CopyValueToVirtualRegister(V, Reg);
1111 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1112 const BasicBlock *FromBB) {
1113 // The operands of the setcc have to be in this block. We don't know
1114 // how to export them from some other block.
1115 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1116 // Can export from current BB.
1117 if (VI->getParent() == FromBB)
1120 // Is already exported, noop.
1121 return FuncInfo.isExportedInst(V);
1124 // If this is an argument, we can export it if the BB is the entry block or
1125 // if it is already exported.
1126 if (isa<Argument>(V)) {
1127 if (FromBB == &FromBB->getParent()->getEntryBlock())
1130 // Otherwise, can only export this if it is already exported.
1131 return FuncInfo.isExportedInst(V);
1134 // Otherwise, constants can always be exported.
1138 static bool InBlock(const Value *V, const BasicBlock *BB) {
1139 if (const Instruction *I = dyn_cast<Instruction>(V))
1140 return I->getParent() == BB;
1144 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1145 /// This function emits a branch and is used at the leaves of an OR or an
1146 /// AND operator tree.
1149 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1150 MachineBasicBlock *TBB,
1151 MachineBasicBlock *FBB,
1152 MachineBasicBlock *CurBB,
1153 MachineBasicBlock *SwitchBB) {
1154 const BasicBlock *BB = CurBB->getBasicBlock();
1156 // If the leaf of the tree is a comparison, merge the condition into
1158 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1159 // The operands of the cmp have to be in this block. We don't know
1160 // how to export them from some other block. If this is the first block
1161 // of the sequence, no exporting is needed.
1162 if (CurBB == SwitchBB ||
1163 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1164 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1165 ISD::CondCode Condition;
1166 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1167 Condition = getICmpCondCode(IC->getPredicate());
1168 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1169 Condition = getFCmpCondCode(FC->getPredicate());
1171 Condition = ISD::SETEQ; // silence warning.
1172 llvm_unreachable("Unknown compare instruction");
1175 CaseBlock CB(Condition, BOp->getOperand(0),
1176 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1177 SwitchCases.push_back(CB);
1182 // Create a CaseBlock record representing this branch.
1183 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1184 NULL, TBB, FBB, CurBB);
1185 SwitchCases.push_back(CB);
1188 /// FindMergedConditions - If Cond is an expression like
1189 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1190 MachineBasicBlock *TBB,
1191 MachineBasicBlock *FBB,
1192 MachineBasicBlock *CurBB,
1193 MachineBasicBlock *SwitchBB,
1195 // If this node is not part of the or/and tree, emit it as a branch.
1196 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1197 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1198 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1199 BOp->getParent() != CurBB->getBasicBlock() ||
1200 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1201 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1202 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1206 // Create TmpBB after CurBB.
1207 MachineFunction::iterator BBI = CurBB;
1208 MachineFunction &MF = DAG.getMachineFunction();
1209 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1210 CurBB->getParent()->insert(++BBI, TmpBB);
1212 if (Opc == Instruction::Or) {
1213 // Codegen X | Y as:
1221 // Emit the LHS condition.
1222 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1224 // Emit the RHS condition into TmpBB.
1225 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1227 assert(Opc == Instruction::And && "Unknown merge op!");
1228 // Codegen X & Y as:
1235 // This requires creation of TmpBB after CurBB.
1237 // Emit the LHS condition.
1238 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1240 // Emit the RHS condition into TmpBB.
1241 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1245 /// If the set of cases should be emitted as a series of branches, return true.
1246 /// If we should emit this as a bunch of and/or'd together conditions, return
1249 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1250 if (Cases.size() != 2) return true;
1252 // If this is two comparisons of the same values or'd or and'd together, they
1253 // will get folded into a single comparison, so don't emit two blocks.
1254 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1255 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1256 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1257 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1261 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1262 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1263 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1264 Cases[0].CC == Cases[1].CC &&
1265 isa<Constant>(Cases[0].CmpRHS) &&
1266 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1267 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1269 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1276 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1277 MachineBasicBlock *BrMBB = FuncInfo.MBBMap[I.getParent()];
1279 // Update machine-CFG edges.
1280 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1282 // Figure out which block is immediately after the current one.
1283 MachineBasicBlock *NextBlock = 0;
1284 MachineFunction::iterator BBI = BrMBB;
1285 if (++BBI != FuncInfo.MF->end())
1288 if (I.isUnconditional()) {
1289 // Update machine-CFG edges.
1290 BrMBB->addSuccessor(Succ0MBB);
1292 // If this is not a fall-through branch, emit the branch.
1293 if (Succ0MBB != NextBlock)
1294 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1295 MVT::Other, getControlRoot(),
1296 DAG.getBasicBlock(Succ0MBB)));
1301 // If this condition is one of the special cases we handle, do special stuff
1303 const Value *CondVal = I.getCondition();
1304 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1306 // If this is a series of conditions that are or'd or and'd together, emit
1307 // this as a sequence of branches instead of setcc's with and/or operations.
1308 // For example, instead of something like:
1321 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1322 if (BOp->hasOneUse() &&
1323 (BOp->getOpcode() == Instruction::And ||
1324 BOp->getOpcode() == Instruction::Or)) {
1325 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1327 // If the compares in later blocks need to use values not currently
1328 // exported from this block, export them now. This block should always
1329 // be the first entry.
1330 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1332 // Allow some cases to be rejected.
1333 if (ShouldEmitAsBranches(SwitchCases)) {
1334 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1335 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1336 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1339 // Emit the branch for this block.
1340 visitSwitchCase(SwitchCases[0], BrMBB);
1341 SwitchCases.erase(SwitchCases.begin());
1345 // Okay, we decided not to do this, remove any inserted MBB's and clear
1347 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1348 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1350 SwitchCases.clear();
1354 // Create a CaseBlock record representing this branch.
1355 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1356 NULL, Succ0MBB, Succ1MBB, BrMBB);
1358 // Use visitSwitchCase to actually insert the fast branch sequence for this
1360 visitSwitchCase(CB, BrMBB);
1363 /// visitSwitchCase - Emits the necessary code to represent a single node in
1364 /// the binary search tree resulting from lowering a switch instruction.
1365 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1366 MachineBasicBlock *SwitchBB) {
1368 SDValue CondLHS = getValue(CB.CmpLHS);
1369 DebugLoc dl = getCurDebugLoc();
1371 // Build the setcc now.
1372 if (CB.CmpMHS == NULL) {
1373 // Fold "(X == true)" to X and "(X == false)" to !X to
1374 // handle common cases produced by branch lowering.
1375 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1376 CB.CC == ISD::SETEQ)
1378 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1379 CB.CC == ISD::SETEQ) {
1380 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1381 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1383 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1385 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1387 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1388 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1390 SDValue CmpOp = getValue(CB.CmpMHS);
1391 EVT VT = CmpOp.getValueType();
1393 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1394 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1397 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1398 VT, CmpOp, DAG.getConstant(Low, VT));
1399 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1400 DAG.getConstant(High-Low, VT), ISD::SETULE);
1404 // Update successor info
1405 SwitchBB->addSuccessor(CB.TrueBB);
1406 SwitchBB->addSuccessor(CB.FalseBB);
1408 // Set NextBlock to be the MBB immediately after the current one, if any.
1409 // This is used to avoid emitting unnecessary branches to the next block.
1410 MachineBasicBlock *NextBlock = 0;
1411 MachineFunction::iterator BBI = SwitchBB;
1412 if (++BBI != FuncInfo.MF->end())
1415 // If the lhs block is the next block, invert the condition so that we can
1416 // fall through to the lhs instead of the rhs block.
1417 if (CB.TrueBB == NextBlock) {
1418 std::swap(CB.TrueBB, CB.FalseBB);
1419 SDValue True = DAG.getConstant(1, Cond.getValueType());
1420 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1423 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1424 MVT::Other, getControlRoot(), Cond,
1425 DAG.getBasicBlock(CB.TrueBB));
1427 // Insert the false branch.
1428 if (CB.FalseBB != NextBlock)
1429 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1430 DAG.getBasicBlock(CB.FalseBB));
1432 DAG.setRoot(BrCond);
1435 /// visitJumpTable - Emit JumpTable node in the current MBB
1436 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1437 // Emit the code for the jump table
1438 assert(JT.Reg != -1U && "Should lower JT Header first!");
1439 EVT PTy = TLI.getPointerTy();
1440 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1442 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1443 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1444 MVT::Other, Index.getValue(1),
1446 DAG.setRoot(BrJumpTable);
1449 /// visitJumpTableHeader - This function emits necessary code to produce index
1450 /// in the JumpTable from switch case.
1451 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1452 JumpTableHeader &JTH,
1453 MachineBasicBlock *SwitchBB) {
1454 // Subtract the lowest switch case value from the value being switched on and
1455 // conditional branch to default mbb if the result is greater than the
1456 // difference between smallest and largest cases.
1457 SDValue SwitchOp = getValue(JTH.SValue);
1458 EVT VT = SwitchOp.getValueType();
1459 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1460 DAG.getConstant(JTH.First, VT));
1462 // The SDNode we just created, which holds the value being switched on minus
1463 // the smallest case value, needs to be copied to a virtual register so it
1464 // can be used as an index into the jump table in a subsequent basic block.
1465 // This value may be smaller or larger than the target's pointer type, and
1466 // therefore require extension or truncating.
1467 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1469 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1470 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1471 JumpTableReg, SwitchOp);
1472 JT.Reg = JumpTableReg;
1474 // Emit the range check for the jump table, and branch to the default block
1475 // for the switch statement if the value being switched on exceeds the largest
1476 // case in the switch.
1477 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1478 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1479 DAG.getConstant(JTH.Last-JTH.First,VT),
1482 // Set NextBlock to be the MBB immediately after the current one, if any.
1483 // This is used to avoid emitting unnecessary branches to the next block.
1484 MachineBasicBlock *NextBlock = 0;
1485 MachineFunction::iterator BBI = SwitchBB;
1487 if (++BBI != FuncInfo.MF->end())
1490 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1491 MVT::Other, CopyTo, CMP,
1492 DAG.getBasicBlock(JT.Default));
1494 if (JT.MBB != NextBlock)
1495 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1496 DAG.getBasicBlock(JT.MBB));
1498 DAG.setRoot(BrCond);
1501 /// visitBitTestHeader - This function emits necessary code to produce value
1502 /// suitable for "bit tests"
1503 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1504 MachineBasicBlock *SwitchBB) {
1505 // Subtract the minimum value
1506 SDValue SwitchOp = getValue(B.SValue);
1507 EVT VT = SwitchOp.getValueType();
1508 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1509 DAG.getConstant(B.First, VT));
1512 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1513 TLI.getSetCCResultType(Sub.getValueType()),
1514 Sub, DAG.getConstant(B.Range, VT),
1517 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1518 TLI.getPointerTy());
1520 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1521 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1524 // Set NextBlock to be the MBB immediately after the current one, if any.
1525 // This is used to avoid emitting unnecessary branches to the next block.
1526 MachineBasicBlock *NextBlock = 0;
1527 MachineFunction::iterator BBI = SwitchBB;
1528 if (++BBI != FuncInfo.MF->end())
1531 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1533 SwitchBB->addSuccessor(B.Default);
1534 SwitchBB->addSuccessor(MBB);
1536 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1537 MVT::Other, CopyTo, RangeCmp,
1538 DAG.getBasicBlock(B.Default));
1540 if (MBB != NextBlock)
1541 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1542 DAG.getBasicBlock(MBB));
1544 DAG.setRoot(BrRange);
1547 /// visitBitTestCase - this function produces one "bit test"
1548 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1551 MachineBasicBlock *SwitchBB) {
1552 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1553 TLI.getPointerTy());
1555 if (CountPopulation_64(B.Mask) == 1) {
1556 // Testing for a single bit; just compare the shift count with what it
1557 // would need to be to shift a 1 bit in that position.
1558 Cmp = DAG.getSetCC(getCurDebugLoc(),
1559 TLI.getSetCCResultType(ShiftOp.getValueType()),
1561 DAG.getConstant(CountTrailingZeros_64(B.Mask),
1562 TLI.getPointerTy()),
1565 // Make desired shift
1566 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1568 DAG.getConstant(1, TLI.getPointerTy()),
1571 // Emit bit tests and jumps
1572 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1573 TLI.getPointerTy(), SwitchVal,
1574 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1575 Cmp = DAG.getSetCC(getCurDebugLoc(),
1576 TLI.getSetCCResultType(AndOp.getValueType()),
1577 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1581 SwitchBB->addSuccessor(B.TargetBB);
1582 SwitchBB->addSuccessor(NextMBB);
1584 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1585 MVT::Other, getControlRoot(),
1586 Cmp, DAG.getBasicBlock(B.TargetBB));
1588 // Set NextBlock to be the MBB immediately after the current one, if any.
1589 // This is used to avoid emitting unnecessary branches to the next block.
1590 MachineBasicBlock *NextBlock = 0;
1591 MachineFunction::iterator BBI = SwitchBB;
1592 if (++BBI != FuncInfo.MF->end())
1595 if (NextMBB != NextBlock)
1596 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1597 DAG.getBasicBlock(NextMBB));
1602 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1603 MachineBasicBlock *InvokeMBB = FuncInfo.MBBMap[I.getParent()];
1605 // Retrieve successors.
1606 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1607 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1609 const Value *Callee(I.getCalledValue());
1610 if (isa<InlineAsm>(Callee))
1613 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1615 // If the value of the invoke is used outside of its defining block, make it
1616 // available as a virtual register.
1617 CopyToExportRegsIfNeeded(&I);
1619 // Update successor info
1620 InvokeMBB->addSuccessor(Return);
1621 InvokeMBB->addSuccessor(LandingPad);
1623 // Drop into normal successor.
1624 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1625 MVT::Other, getControlRoot(),
1626 DAG.getBasicBlock(Return)));
1629 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1632 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1633 /// small case ranges).
1634 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1635 CaseRecVector& WorkList,
1637 MachineBasicBlock *Default,
1638 MachineBasicBlock *SwitchBB) {
1639 Case& BackCase = *(CR.Range.second-1);
1641 // Size is the number of Cases represented by this range.
1642 size_t Size = CR.Range.second - CR.Range.first;
1646 // Get the MachineFunction which holds the current MBB. This is used when
1647 // inserting any additional MBBs necessary to represent the switch.
1648 MachineFunction *CurMF = FuncInfo.MF;
1650 // Figure out which block is immediately after the current one.
1651 MachineBasicBlock *NextBlock = 0;
1652 MachineFunction::iterator BBI = CR.CaseBB;
1654 if (++BBI != FuncInfo.MF->end())
1657 // TODO: If any two of the cases has the same destination, and if one value
1658 // is the same as the other, but has one bit unset that the other has set,
1659 // use bit manipulation to do two compares at once. For example:
1660 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1662 // Rearrange the case blocks so that the last one falls through if possible.
1663 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1664 // The last case block won't fall through into 'NextBlock' if we emit the
1665 // branches in this order. See if rearranging a case value would help.
1666 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1667 if (I->BB == NextBlock) {
1668 std::swap(*I, BackCase);
1674 // Create a CaseBlock record representing a conditional branch to
1675 // the Case's target mbb if the value being switched on SV is equal
1677 MachineBasicBlock *CurBlock = CR.CaseBB;
1678 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1679 MachineBasicBlock *FallThrough;
1681 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1682 CurMF->insert(BBI, FallThrough);
1684 // Put SV in a virtual register to make it available from the new blocks.
1685 ExportFromCurrentBlock(SV);
1687 // If the last case doesn't match, go to the default block.
1688 FallThrough = Default;
1691 const Value *RHS, *LHS, *MHS;
1693 if (I->High == I->Low) {
1694 // This is just small small case range :) containing exactly 1 case
1696 LHS = SV; RHS = I->High; MHS = NULL;
1699 LHS = I->Low; MHS = SV; RHS = I->High;
1701 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1703 // If emitting the first comparison, just call visitSwitchCase to emit the
1704 // code into the current block. Otherwise, push the CaseBlock onto the
1705 // vector to be later processed by SDISel, and insert the node's MBB
1706 // before the next MBB.
1707 if (CurBlock == SwitchBB)
1708 visitSwitchCase(CB, SwitchBB);
1710 SwitchCases.push_back(CB);
1712 CurBlock = FallThrough;
1718 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1719 return !DisableJumpTables &&
1720 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1721 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1724 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1725 APInt LastExt(Last), FirstExt(First);
1726 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1727 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1728 return (LastExt - FirstExt + 1ULL);
1731 /// handleJTSwitchCase - Emit jumptable for current switch case range
1732 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1733 CaseRecVector& WorkList,
1735 MachineBasicBlock* Default,
1736 MachineBasicBlock *SwitchBB) {
1737 Case& FrontCase = *CR.Range.first;
1738 Case& BackCase = *(CR.Range.second-1);
1740 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1741 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1743 APInt TSize(First.getBitWidth(), 0);
1744 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1748 if (!areJTsAllowed(TLI) || TSize.ult(4))
1751 APInt Range = ComputeRange(First, Last);
1752 double Density = TSize.roundToDouble() / Range.roundToDouble();
1756 DEBUG(dbgs() << "Lowering jump table\n"
1757 << "First entry: " << First << ". Last entry: " << Last << '\n'
1758 << "Range: " << Range
1759 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1761 // Get the MachineFunction which holds the current MBB. This is used when
1762 // inserting any additional MBBs necessary to represent the switch.
1763 MachineFunction *CurMF = FuncInfo.MF;
1765 // Figure out which block is immediately after the current one.
1766 MachineFunction::iterator BBI = CR.CaseBB;
1769 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1771 // Create a new basic block to hold the code for loading the address
1772 // of the jump table, and jumping to it. Update successor information;
1773 // we will either branch to the default case for the switch, or the jump
1775 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1776 CurMF->insert(BBI, JumpTableBB);
1777 CR.CaseBB->addSuccessor(Default);
1778 CR.CaseBB->addSuccessor(JumpTableBB);
1780 // Build a vector of destination BBs, corresponding to each target
1781 // of the jump table. If the value of the jump table slot corresponds to
1782 // a case statement, push the case's BB onto the vector, otherwise, push
1784 std::vector<MachineBasicBlock*> DestBBs;
1786 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1787 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1788 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1790 if (Low.sle(TEI) && TEI.sle(High)) {
1791 DestBBs.push_back(I->BB);
1795 DestBBs.push_back(Default);
1799 // Update successor info. Add one edge to each unique successor.
1800 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1801 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1802 E = DestBBs.end(); I != E; ++I) {
1803 if (!SuccsHandled[(*I)->getNumber()]) {
1804 SuccsHandled[(*I)->getNumber()] = true;
1805 JumpTableBB->addSuccessor(*I);
1809 // Create a jump table index for this jump table.
1810 unsigned JTEncoding = TLI.getJumpTableEncoding();
1811 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1812 ->createJumpTableIndex(DestBBs);
1814 // Set the jump table information so that we can codegen it as a second
1815 // MachineBasicBlock
1816 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1817 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
1818 if (CR.CaseBB == SwitchBB)
1819 visitJumpTableHeader(JT, JTH, SwitchBB);
1821 JTCases.push_back(JumpTableBlock(JTH, JT));
1826 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1828 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1829 CaseRecVector& WorkList,
1831 MachineBasicBlock *Default,
1832 MachineBasicBlock *SwitchBB) {
1833 // Get the MachineFunction which holds the current MBB. This is used when
1834 // inserting any additional MBBs necessary to represent the switch.
1835 MachineFunction *CurMF = FuncInfo.MF;
1837 // Figure out which block is immediately after the current one.
1838 MachineFunction::iterator BBI = CR.CaseBB;
1841 Case& FrontCase = *CR.Range.first;
1842 Case& BackCase = *(CR.Range.second-1);
1843 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1845 // Size is the number of Cases represented by this range.
1846 unsigned Size = CR.Range.second - CR.Range.first;
1848 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1849 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1851 CaseItr Pivot = CR.Range.first + Size/2;
1853 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1854 // (heuristically) allow us to emit JumpTable's later.
1855 APInt TSize(First.getBitWidth(), 0);
1856 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1860 APInt LSize = FrontCase.size();
1861 APInt RSize = TSize-LSize;
1862 DEBUG(dbgs() << "Selecting best pivot: \n"
1863 << "First: " << First << ", Last: " << Last <<'\n'
1864 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1865 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1867 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1868 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1869 APInt Range = ComputeRange(LEnd, RBegin);
1870 assert((Range - 2ULL).isNonNegative() &&
1871 "Invalid case distance");
1872 double LDensity = (double)LSize.roundToDouble() /
1873 (LEnd - First + 1ULL).roundToDouble();
1874 double RDensity = (double)RSize.roundToDouble() /
1875 (Last - RBegin + 1ULL).roundToDouble();
1876 double Metric = Range.logBase2()*(LDensity+RDensity);
1877 // Should always split in some non-trivial place
1878 DEBUG(dbgs() <<"=>Step\n"
1879 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1880 << "LDensity: " << LDensity
1881 << ", RDensity: " << RDensity << '\n'
1882 << "Metric: " << Metric << '\n');
1883 if (FMetric < Metric) {
1886 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1892 if (areJTsAllowed(TLI)) {
1893 // If our case is dense we *really* should handle it earlier!
1894 assert((FMetric > 0) && "Should handle dense range earlier!");
1896 Pivot = CR.Range.first + Size/2;
1899 CaseRange LHSR(CR.Range.first, Pivot);
1900 CaseRange RHSR(Pivot, CR.Range.second);
1901 Constant *C = Pivot->Low;
1902 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1904 // We know that we branch to the LHS if the Value being switched on is
1905 // less than the Pivot value, C. We use this to optimize our binary
1906 // tree a bit, by recognizing that if SV is greater than or equal to the
1907 // LHS's Case Value, and that Case Value is exactly one less than the
1908 // Pivot's Value, then we can branch directly to the LHS's Target,
1909 // rather than creating a leaf node for it.
1910 if ((LHSR.second - LHSR.first) == 1 &&
1911 LHSR.first->High == CR.GE &&
1912 cast<ConstantInt>(C)->getValue() ==
1913 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1914 TrueBB = LHSR.first->BB;
1916 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1917 CurMF->insert(BBI, TrueBB);
1918 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1920 // Put SV in a virtual register to make it available from the new blocks.
1921 ExportFromCurrentBlock(SV);
1924 // Similar to the optimization above, if the Value being switched on is
1925 // known to be less than the Constant CR.LT, and the current Case Value
1926 // is CR.LT - 1, then we can branch directly to the target block for
1927 // the current Case Value, rather than emitting a RHS leaf node for it.
1928 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1929 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1930 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1931 FalseBB = RHSR.first->BB;
1933 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1934 CurMF->insert(BBI, FalseBB);
1935 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1937 // Put SV in a virtual register to make it available from the new blocks.
1938 ExportFromCurrentBlock(SV);
1941 // Create a CaseBlock record representing a conditional branch to
1942 // the LHS node if the value being switched on SV is less than C.
1943 // Otherwise, branch to LHS.
1944 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1946 if (CR.CaseBB == SwitchBB)
1947 visitSwitchCase(CB, SwitchBB);
1949 SwitchCases.push_back(CB);
1954 /// handleBitTestsSwitchCase - if current case range has few destination and
1955 /// range span less, than machine word bitwidth, encode case range into series
1956 /// of masks and emit bit tests with these masks.
1957 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1958 CaseRecVector& WorkList,
1960 MachineBasicBlock* Default,
1961 MachineBasicBlock *SwitchBB){
1962 EVT PTy = TLI.getPointerTy();
1963 unsigned IntPtrBits = PTy.getSizeInBits();
1965 Case& FrontCase = *CR.Range.first;
1966 Case& BackCase = *(CR.Range.second-1);
1968 // Get the MachineFunction which holds the current MBB. This is used when
1969 // inserting any additional MBBs necessary to represent the switch.
1970 MachineFunction *CurMF = FuncInfo.MF;
1972 // If target does not have legal shift left, do not emit bit tests at all.
1973 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1977 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1979 // Single case counts one, case range - two.
1980 numCmps += (I->Low == I->High ? 1 : 2);
1983 // Count unique destinations
1984 SmallSet<MachineBasicBlock*, 4> Dests;
1985 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1986 Dests.insert(I->BB);
1987 if (Dests.size() > 3)
1988 // Don't bother the code below, if there are too much unique destinations
1991 DEBUG(dbgs() << "Total number of unique destinations: "
1992 << Dests.size() << '\n'
1993 << "Total number of comparisons: " << numCmps << '\n');
1995 // Compute span of values.
1996 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1997 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1998 APInt cmpRange = maxValue - minValue;
2000 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2001 << "Low bound: " << minValue << '\n'
2002 << "High bound: " << maxValue << '\n');
2004 if (cmpRange.uge(IntPtrBits) ||
2005 (!(Dests.size() == 1 && numCmps >= 3) &&
2006 !(Dests.size() == 2 && numCmps >= 5) &&
2007 !(Dests.size() >= 3 && numCmps >= 6)))
2010 DEBUG(dbgs() << "Emitting bit tests\n");
2011 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2013 // Optimize the case where all the case values fit in a
2014 // word without having to subtract minValue. In this case,
2015 // we can optimize away the subtraction.
2016 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2017 cmpRange = maxValue;
2019 lowBound = minValue;
2022 CaseBitsVector CasesBits;
2023 unsigned i, count = 0;
2025 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2026 MachineBasicBlock* Dest = I->BB;
2027 for (i = 0; i < count; ++i)
2028 if (Dest == CasesBits[i].BB)
2032 assert((count < 3) && "Too much destinations to test!");
2033 CasesBits.push_back(CaseBits(0, Dest, 0));
2037 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2038 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2040 uint64_t lo = (lowValue - lowBound).getZExtValue();
2041 uint64_t hi = (highValue - lowBound).getZExtValue();
2043 for (uint64_t j = lo; j <= hi; j++) {
2044 CasesBits[i].Mask |= 1ULL << j;
2045 CasesBits[i].Bits++;
2049 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2053 // Figure out which block is immediately after the current one.
2054 MachineFunction::iterator BBI = CR.CaseBB;
2057 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2059 DEBUG(dbgs() << "Cases:\n");
2060 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2061 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2062 << ", Bits: " << CasesBits[i].Bits
2063 << ", BB: " << CasesBits[i].BB << '\n');
2065 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2066 CurMF->insert(BBI, CaseBB);
2067 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2071 // Put SV in a virtual register to make it available from the new blocks.
2072 ExportFromCurrentBlock(SV);
2075 BitTestBlock BTB(lowBound, cmpRange, SV,
2076 -1U, (CR.CaseBB == SwitchBB),
2077 CR.CaseBB, Default, BTC);
2079 if (CR.CaseBB == SwitchBB)
2080 visitBitTestHeader(BTB, SwitchBB);
2082 BitTestCases.push_back(BTB);
2087 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2088 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2089 const SwitchInst& SI) {
2092 // Start with "simple" cases
2093 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2094 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2095 Cases.push_back(Case(SI.getSuccessorValue(i),
2096 SI.getSuccessorValue(i),
2099 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2101 // Merge case into clusters
2102 if (Cases.size() >= 2)
2103 // Must recompute end() each iteration because it may be
2104 // invalidated by erase if we hold on to it
2105 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2106 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2107 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2108 MachineBasicBlock* nextBB = J->BB;
2109 MachineBasicBlock* currentBB = I->BB;
2111 // If the two neighboring cases go to the same destination, merge them
2112 // into a single case.
2113 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2121 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2122 if (I->Low != I->High)
2123 // A range counts double, since it requires two compares.
2130 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2131 MachineBasicBlock *SwitchMBB = FuncInfo.MBBMap[SI.getParent()];
2133 // Figure out which block is immediately after the current one.
2134 MachineBasicBlock *NextBlock = 0;
2135 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2137 // If there is only the default destination, branch to it if it is not the
2138 // next basic block. Otherwise, just fall through.
2139 if (SI.getNumOperands() == 2) {
2140 // Update machine-CFG edges.
2142 // If this is not a fall-through branch, emit the branch.
2143 SwitchMBB->addSuccessor(Default);
2144 if (Default != NextBlock)
2145 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2146 MVT::Other, getControlRoot(),
2147 DAG.getBasicBlock(Default)));
2152 // If there are any non-default case statements, create a vector of Cases
2153 // representing each one, and sort the vector so that we can efficiently
2154 // create a binary search tree from them.
2156 size_t numCmps = Clusterify(Cases, SI);
2157 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2158 << ". Total compares: " << numCmps << '\n');
2161 // Get the Value to be switched on and default basic blocks, which will be
2162 // inserted into CaseBlock records, representing basic blocks in the binary
2164 const Value *SV = SI.getOperand(0);
2166 // Push the initial CaseRec onto the worklist
2167 CaseRecVector WorkList;
2168 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2169 CaseRange(Cases.begin(),Cases.end())));
2171 while (!WorkList.empty()) {
2172 // Grab a record representing a case range to process off the worklist
2173 CaseRec CR = WorkList.back();
2174 WorkList.pop_back();
2176 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2179 // If the range has few cases (two or less) emit a series of specific
2181 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2184 // If the switch has more than 5 blocks, and at least 40% dense, and the
2185 // target supports indirect branches, then emit a jump table rather than
2186 // lowering the switch to a binary tree of conditional branches.
2187 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2190 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2191 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2192 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2196 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2197 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBBMap[I.getParent()];
2199 // Update machine-CFG edges with unique successors.
2200 SmallVector<BasicBlock*, 32> succs;
2201 succs.reserve(I.getNumSuccessors());
2202 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2203 succs.push_back(I.getSuccessor(i));
2204 array_pod_sort(succs.begin(), succs.end());
2205 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2206 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2207 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2209 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2210 MVT::Other, getControlRoot(),
2211 getValue(I.getAddress())));
2214 void SelectionDAGBuilder::visitFSub(const User &I) {
2215 // -0.0 - X --> fneg
2216 const Type *Ty = I.getType();
2217 if (Ty->isVectorTy()) {
2218 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2219 const VectorType *DestTy = cast<VectorType>(I.getType());
2220 const Type *ElTy = DestTy->getElementType();
2221 unsigned VL = DestTy->getNumElements();
2222 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2223 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2225 SDValue Op2 = getValue(I.getOperand(1));
2226 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2227 Op2.getValueType(), Op2));
2233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2234 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2235 SDValue Op2 = getValue(I.getOperand(1));
2236 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2237 Op2.getValueType(), Op2));
2241 visitBinary(I, ISD::FSUB);
2244 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2245 SDValue Op1 = getValue(I.getOperand(0));
2246 SDValue Op2 = getValue(I.getOperand(1));
2247 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2248 Op1.getValueType(), Op1, Op2));
2251 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2252 SDValue Op1 = getValue(I.getOperand(0));
2253 SDValue Op2 = getValue(I.getOperand(1));
2254 if (!I.getType()->isVectorTy() &&
2255 Op2.getValueType() != TLI.getShiftAmountTy()) {
2256 // If the operand is smaller than the shift count type, promote it.
2257 EVT PTy = TLI.getPointerTy();
2258 EVT STy = TLI.getShiftAmountTy();
2259 if (STy.bitsGT(Op2.getValueType()))
2260 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2261 TLI.getShiftAmountTy(), Op2);
2262 // If the operand is larger than the shift count type but the shift
2263 // count type has enough bits to represent any shift value, truncate
2264 // it now. This is a common case and it exposes the truncate to
2265 // optimization early.
2266 else if (STy.getSizeInBits() >=
2267 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2268 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2269 TLI.getShiftAmountTy(), Op2);
2270 // Otherwise we'll need to temporarily settle for some other
2271 // convenient type; type legalization will make adjustments as
2273 else if (PTy.bitsLT(Op2.getValueType()))
2274 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2275 TLI.getPointerTy(), Op2);
2276 else if (PTy.bitsGT(Op2.getValueType()))
2277 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2278 TLI.getPointerTy(), Op2);
2281 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2282 Op1.getValueType(), Op1, Op2));
2285 void SelectionDAGBuilder::visitICmp(const User &I) {
2286 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2287 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2288 predicate = IC->getPredicate();
2289 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2290 predicate = ICmpInst::Predicate(IC->getPredicate());
2291 SDValue Op1 = getValue(I.getOperand(0));
2292 SDValue Op2 = getValue(I.getOperand(1));
2293 ISD::CondCode Opcode = getICmpCondCode(predicate);
2295 EVT DestVT = TLI.getValueType(I.getType());
2296 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2299 void SelectionDAGBuilder::visitFCmp(const User &I) {
2300 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2301 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2302 predicate = FC->getPredicate();
2303 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2304 predicate = FCmpInst::Predicate(FC->getPredicate());
2305 SDValue Op1 = getValue(I.getOperand(0));
2306 SDValue Op2 = getValue(I.getOperand(1));
2307 ISD::CondCode Condition = getFCmpCondCode(predicate);
2308 EVT DestVT = TLI.getValueType(I.getType());
2309 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2312 void SelectionDAGBuilder::visitSelect(const User &I) {
2313 SmallVector<EVT, 4> ValueVTs;
2314 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2315 unsigned NumValues = ValueVTs.size();
2316 if (NumValues == 0) return;
2318 SmallVector<SDValue, 4> Values(NumValues);
2319 SDValue Cond = getValue(I.getOperand(0));
2320 SDValue TrueVal = getValue(I.getOperand(1));
2321 SDValue FalseVal = getValue(I.getOperand(2));
2323 for (unsigned i = 0; i != NumValues; ++i)
2324 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2325 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2327 SDValue(TrueVal.getNode(),
2328 TrueVal.getResNo() + i),
2329 SDValue(FalseVal.getNode(),
2330 FalseVal.getResNo() + i));
2332 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2333 DAG.getVTList(&ValueVTs[0], NumValues),
2334 &Values[0], NumValues));
2337 void SelectionDAGBuilder::visitTrunc(const User &I) {
2338 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2339 SDValue N = getValue(I.getOperand(0));
2340 EVT DestVT = TLI.getValueType(I.getType());
2341 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2344 void SelectionDAGBuilder::visitZExt(const User &I) {
2345 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2346 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2347 SDValue N = getValue(I.getOperand(0));
2348 EVT DestVT = TLI.getValueType(I.getType());
2349 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2352 void SelectionDAGBuilder::visitSExt(const User &I) {
2353 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2354 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2355 SDValue N = getValue(I.getOperand(0));
2356 EVT DestVT = TLI.getValueType(I.getType());
2357 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2360 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2361 // FPTrunc is never a no-op cast, no need to check
2362 SDValue N = getValue(I.getOperand(0));
2363 EVT DestVT = TLI.getValueType(I.getType());
2364 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2365 DestVT, N, DAG.getIntPtrConstant(0)));
2368 void SelectionDAGBuilder::visitFPExt(const User &I){
2369 // FPTrunc is never a no-op cast, no need to check
2370 SDValue N = getValue(I.getOperand(0));
2371 EVT DestVT = TLI.getValueType(I.getType());
2372 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2375 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2376 // FPToUI is never a no-op cast, no need to check
2377 SDValue N = getValue(I.getOperand(0));
2378 EVT DestVT = TLI.getValueType(I.getType());
2379 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2382 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2383 // FPToSI is never a no-op cast, no need to check
2384 SDValue N = getValue(I.getOperand(0));
2385 EVT DestVT = TLI.getValueType(I.getType());
2386 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2389 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2390 // UIToFP is never a no-op cast, no need to check
2391 SDValue N = getValue(I.getOperand(0));
2392 EVT DestVT = TLI.getValueType(I.getType());
2393 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2396 void SelectionDAGBuilder::visitSIToFP(const User &I){
2397 // SIToFP is never a no-op cast, no need to check
2398 SDValue N = getValue(I.getOperand(0));
2399 EVT DestVT = TLI.getValueType(I.getType());
2400 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2403 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2404 // What to do depends on the size of the integer and the size of the pointer.
2405 // We can either truncate, zero extend, or no-op, accordingly.
2406 SDValue N = getValue(I.getOperand(0));
2407 EVT DestVT = TLI.getValueType(I.getType());
2408 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2411 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2412 // What to do depends on the size of the integer and the size of the pointer.
2413 // We can either truncate, zero extend, or no-op, accordingly.
2414 SDValue N = getValue(I.getOperand(0));
2415 EVT DestVT = TLI.getValueType(I.getType());
2416 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2419 void SelectionDAGBuilder::visitBitCast(const User &I) {
2420 SDValue N = getValue(I.getOperand(0));
2421 EVT DestVT = TLI.getValueType(I.getType());
2423 // BitCast assures us that source and destination are the same size so this is
2424 // either a BIT_CONVERT or a no-op.
2425 if (DestVT != N.getValueType())
2426 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2427 DestVT, N)); // convert types.
2429 setValue(&I, N); // noop cast.
2432 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2433 SDValue InVec = getValue(I.getOperand(0));
2434 SDValue InVal = getValue(I.getOperand(1));
2435 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2437 getValue(I.getOperand(2)));
2438 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2439 TLI.getValueType(I.getType()),
2440 InVec, InVal, InIdx));
2443 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2444 SDValue InVec = getValue(I.getOperand(0));
2445 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2447 getValue(I.getOperand(1)));
2448 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2449 TLI.getValueType(I.getType()), InVec, InIdx));
2452 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2453 // from SIndx and increasing to the element length (undefs are allowed).
2454 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2455 unsigned MaskNumElts = Mask.size();
2456 for (unsigned i = 0; i != MaskNumElts; ++i)
2457 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2462 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2463 SmallVector<int, 8> Mask;
2464 SDValue Src1 = getValue(I.getOperand(0));
2465 SDValue Src2 = getValue(I.getOperand(1));
2467 // Convert the ConstantVector mask operand into an array of ints, with -1
2468 // representing undef values.
2469 SmallVector<Constant*, 8> MaskElts;
2470 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2471 unsigned MaskNumElts = MaskElts.size();
2472 for (unsigned i = 0; i != MaskNumElts; ++i) {
2473 if (isa<UndefValue>(MaskElts[i]))
2476 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2479 EVT VT = TLI.getValueType(I.getType());
2480 EVT SrcVT = Src1.getValueType();
2481 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2483 if (SrcNumElts == MaskNumElts) {
2484 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2489 // Normalize the shuffle vector since mask and vector length don't match.
2490 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2491 // Mask is longer than the source vectors and is a multiple of the source
2492 // vectors. We can use concatenate vector to make the mask and vectors
2494 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2495 // The shuffle is concatenating two vectors together.
2496 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2501 // Pad both vectors with undefs to make them the same length as the mask.
2502 unsigned NumConcat = MaskNumElts / SrcNumElts;
2503 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2504 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2505 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2507 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2508 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2512 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2513 getCurDebugLoc(), VT,
2514 &MOps1[0], NumConcat);
2515 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2516 getCurDebugLoc(), VT,
2517 &MOps2[0], NumConcat);
2519 // Readjust mask for new input vector length.
2520 SmallVector<int, 8> MappedOps;
2521 for (unsigned i = 0; i != MaskNumElts; ++i) {
2523 if (Idx < (int)SrcNumElts)
2524 MappedOps.push_back(Idx);
2526 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2529 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2534 if (SrcNumElts > MaskNumElts) {
2535 // Analyze the access pattern of the vector to see if we can extract
2536 // two subvectors and do the shuffle. The analysis is done by calculating
2537 // the range of elements the mask access on both vectors.
2538 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2539 int MaxRange[2] = {-1, -1};
2541 for (unsigned i = 0; i != MaskNumElts; ++i) {
2547 if (Idx >= (int)SrcNumElts) {
2551 if (Idx > MaxRange[Input])
2552 MaxRange[Input] = Idx;
2553 if (Idx < MinRange[Input])
2554 MinRange[Input] = Idx;
2557 // Check if the access is smaller than the vector size and can we find
2558 // a reasonable extract index.
2559 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2561 int StartIdx[2]; // StartIdx to extract from
2562 for (int Input=0; Input < 2; ++Input) {
2563 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2564 RangeUse[Input] = 0; // Unused
2565 StartIdx[Input] = 0;
2566 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2567 // Fits within range but we should see if we can find a good
2568 // start index that is a multiple of the mask length.
2569 if (MaxRange[Input] < (int)MaskNumElts) {
2570 RangeUse[Input] = 1; // Extract from beginning of the vector
2571 StartIdx[Input] = 0;
2573 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2574 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2575 StartIdx[Input] + MaskNumElts < SrcNumElts)
2576 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2581 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2582 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2585 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2586 // Extract appropriate subvector and generate a vector shuffle
2587 for (int Input=0; Input < 2; ++Input) {
2588 SDValue &Src = Input == 0 ? Src1 : Src2;
2589 if (RangeUse[Input] == 0)
2590 Src = DAG.getUNDEF(VT);
2592 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2593 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2596 // Calculate new mask.
2597 SmallVector<int, 8> MappedOps;
2598 for (unsigned i = 0; i != MaskNumElts; ++i) {
2601 MappedOps.push_back(Idx);
2602 else if (Idx < (int)SrcNumElts)
2603 MappedOps.push_back(Idx - StartIdx[0]);
2605 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2608 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2614 // We can't use either concat vectors or extract subvectors so fall back to
2615 // replacing the shuffle with extract and build vector.
2616 // to insert and build vector.
2617 EVT EltVT = VT.getVectorElementType();
2618 EVT PtrVT = TLI.getPointerTy();
2619 SmallVector<SDValue,8> Ops;
2620 for (unsigned i = 0; i != MaskNumElts; ++i) {
2622 Ops.push_back(DAG.getUNDEF(EltVT));
2627 if (Idx < (int)SrcNumElts)
2628 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2629 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2631 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2633 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2639 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2640 VT, &Ops[0], Ops.size()));
2643 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2644 const Value *Op0 = I.getOperand(0);
2645 const Value *Op1 = I.getOperand(1);
2646 const Type *AggTy = I.getType();
2647 const Type *ValTy = Op1->getType();
2648 bool IntoUndef = isa<UndefValue>(Op0);
2649 bool FromUndef = isa<UndefValue>(Op1);
2651 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2652 I.idx_begin(), I.idx_end());
2654 SmallVector<EVT, 4> AggValueVTs;
2655 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2656 SmallVector<EVT, 4> ValValueVTs;
2657 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2659 unsigned NumAggValues = AggValueVTs.size();
2660 unsigned NumValValues = ValValueVTs.size();
2661 SmallVector<SDValue, 4> Values(NumAggValues);
2663 SDValue Agg = getValue(Op0);
2664 SDValue Val = getValue(Op1);
2666 // Copy the beginning value(s) from the original aggregate.
2667 for (; i != LinearIndex; ++i)
2668 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2669 SDValue(Agg.getNode(), Agg.getResNo() + i);
2670 // Copy values from the inserted value(s).
2671 for (; i != LinearIndex + NumValValues; ++i)
2672 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2673 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2674 // Copy remaining value(s) from the original aggregate.
2675 for (; i != NumAggValues; ++i)
2676 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2677 SDValue(Agg.getNode(), Agg.getResNo() + i);
2679 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2680 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2681 &Values[0], NumAggValues));
2684 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2685 const Value *Op0 = I.getOperand(0);
2686 const Type *AggTy = Op0->getType();
2687 const Type *ValTy = I.getType();
2688 bool OutOfUndef = isa<UndefValue>(Op0);
2690 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2691 I.idx_begin(), I.idx_end());
2693 SmallVector<EVT, 4> ValValueVTs;
2694 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2696 unsigned NumValValues = ValValueVTs.size();
2697 SmallVector<SDValue, 4> Values(NumValValues);
2699 SDValue Agg = getValue(Op0);
2700 // Copy out the selected value(s).
2701 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2702 Values[i - LinearIndex] =
2704 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2705 SDValue(Agg.getNode(), Agg.getResNo() + i);
2707 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2708 DAG.getVTList(&ValValueVTs[0], NumValValues),
2709 &Values[0], NumValValues));
2712 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2713 SDValue N = getValue(I.getOperand(0));
2714 const Type *Ty = I.getOperand(0)->getType();
2716 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2718 const Value *Idx = *OI;
2719 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2720 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2723 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2724 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2725 DAG.getIntPtrConstant(Offset));
2728 Ty = StTy->getElementType(Field);
2729 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2730 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2732 // Offset canonically 0 for unions, but type changes
2733 Ty = UnTy->getElementType(Field);
2735 Ty = cast<SequentialType>(Ty)->getElementType();
2737 // If this is a constant subscript, handle it quickly.
2738 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2739 if (CI->isZero()) continue;
2741 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2743 EVT PTy = TLI.getPointerTy();
2744 unsigned PtrBits = PTy.getSizeInBits();
2746 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2748 DAG.getConstant(Offs, MVT::i64));
2750 OffsVal = DAG.getIntPtrConstant(Offs);
2752 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2757 // N = N + Idx * ElementSize;
2758 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2759 TD->getTypeAllocSize(Ty));
2760 SDValue IdxN = getValue(Idx);
2762 // If the index is smaller or larger than intptr_t, truncate or extend
2764 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2766 // If this is a multiply by a power of two, turn it into a shl
2767 // immediately. This is a very common case.
2768 if (ElementSize != 1) {
2769 if (ElementSize.isPowerOf2()) {
2770 unsigned Amt = ElementSize.logBase2();
2771 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2772 N.getValueType(), IdxN,
2773 DAG.getConstant(Amt, TLI.getPointerTy()));
2775 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2776 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2777 N.getValueType(), IdxN, Scale);
2781 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2782 N.getValueType(), N, IdxN);
2789 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2790 // If this is a fixed sized alloca in the entry block of the function,
2791 // allocate it statically on the stack.
2792 if (FuncInfo.StaticAllocaMap.count(&I))
2793 return; // getValue will auto-populate this.
2795 const Type *Ty = I.getAllocatedType();
2796 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2798 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2801 SDValue AllocSize = getValue(I.getArraySize());
2803 EVT IntPtr = TLI.getPointerTy();
2804 if (AllocSize.getValueType() != IntPtr)
2805 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2807 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
2809 DAG.getConstant(TySize, IntPtr));
2811 // Handle alignment. If the requested alignment is less than or equal to
2812 // the stack alignment, ignore it. If the size is greater than or equal to
2813 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2814 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment();
2815 if (Align <= StackAlign)
2818 // Round the size of the allocation up to the stack alignment size
2819 // by add SA-1 to the size.
2820 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2821 AllocSize.getValueType(), AllocSize,
2822 DAG.getIntPtrConstant(StackAlign-1));
2824 // Mask out the low bits for alignment purposes.
2825 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2826 AllocSize.getValueType(), AllocSize,
2827 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2829 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2830 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2831 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2834 DAG.setRoot(DSA.getValue(1));
2836 // Inform the Frame Information that we have just allocated a variable-sized
2838 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2841 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2842 const Value *SV = I.getOperand(0);
2843 SDValue Ptr = getValue(SV);
2845 const Type *Ty = I.getType();
2847 bool isVolatile = I.isVolatile();
2848 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2849 unsigned Alignment = I.getAlignment();
2851 SmallVector<EVT, 4> ValueVTs;
2852 SmallVector<uint64_t, 4> Offsets;
2853 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2854 unsigned NumValues = ValueVTs.size();
2859 bool ConstantMemory = false;
2861 // Serialize volatile loads with other side effects.
2863 else if (AA->pointsToConstantMemory(SV)) {
2864 // Do not serialize (non-volatile) loads of constant memory with anything.
2865 Root = DAG.getEntryNode();
2866 ConstantMemory = true;
2868 // Do not serialize non-volatile loads against each other.
2869 Root = DAG.getRoot();
2872 SmallVector<SDValue, 4> Values(NumValues);
2873 SmallVector<SDValue, 4> Chains(NumValues);
2874 EVT PtrVT = Ptr.getValueType();
2875 for (unsigned i = 0; i != NumValues; ++i) {
2876 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2878 DAG.getConstant(Offsets[i], PtrVT));
2879 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2880 A, SV, Offsets[i], isVolatile,
2881 isNonTemporal, Alignment);
2884 Chains[i] = L.getValue(1);
2887 if (!ConstantMemory) {
2888 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2889 MVT::Other, &Chains[0], NumValues);
2893 PendingLoads.push_back(Chain);
2896 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2897 DAG.getVTList(&ValueVTs[0], NumValues),
2898 &Values[0], NumValues));
2901 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2902 const Value *SrcV = I.getOperand(0);
2903 const Value *PtrV = I.getOperand(1);
2905 SmallVector<EVT, 4> ValueVTs;
2906 SmallVector<uint64_t, 4> Offsets;
2907 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2908 unsigned NumValues = ValueVTs.size();
2912 // Get the lowered operands. Note that we do this after
2913 // checking if NumResults is zero, because with zero results
2914 // the operands won't have values in the map.
2915 SDValue Src = getValue(SrcV);
2916 SDValue Ptr = getValue(PtrV);
2918 SDValue Root = getRoot();
2919 SmallVector<SDValue, 4> Chains(NumValues);
2920 EVT PtrVT = Ptr.getValueType();
2921 bool isVolatile = I.isVolatile();
2922 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2923 unsigned Alignment = I.getAlignment();
2925 for (unsigned i = 0; i != NumValues; ++i) {
2926 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2927 DAG.getConstant(Offsets[i], PtrVT));
2928 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2929 SDValue(Src.getNode(), Src.getResNo() + i),
2930 Add, PtrV, Offsets[i], isVolatile,
2931 isNonTemporal, Alignment);
2934 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2935 MVT::Other, &Chains[0], NumValues));
2938 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2940 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
2941 unsigned Intrinsic) {
2942 bool HasChain = !I.doesNotAccessMemory();
2943 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2945 // Build the operand list.
2946 SmallVector<SDValue, 8> Ops;
2947 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2949 // We don't need to serialize loads against other loads.
2950 Ops.push_back(DAG.getRoot());
2952 Ops.push_back(getRoot());
2956 // Info is set by getTgtMemInstrinsic
2957 TargetLowering::IntrinsicInfo Info;
2958 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2960 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2961 if (!IsTgtIntrinsic)
2962 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2964 // Add all operands of the call to the operand list.
2965 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
2966 SDValue Op = getValue(I.getArgOperand(i));
2967 assert(TLI.isTypeLegal(Op.getValueType()) &&
2968 "Intrinsic uses a non-legal type?");
2972 SmallVector<EVT, 4> ValueVTs;
2973 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2975 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2976 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2977 "Intrinsic uses a non-legal type?");
2982 ValueVTs.push_back(MVT::Other);
2984 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2988 if (IsTgtIntrinsic) {
2989 // This is target intrinsic that touches memory
2990 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2991 VTs, &Ops[0], Ops.size(),
2992 Info.memVT, Info.ptrVal, Info.offset,
2993 Info.align, Info.vol,
2994 Info.readMem, Info.writeMem);
2995 } else if (!HasChain) {
2996 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2997 VTs, &Ops[0], Ops.size());
2998 } else if (!I.getType()->isVoidTy()) {
2999 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3000 VTs, &Ops[0], Ops.size());
3002 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3003 VTs, &Ops[0], Ops.size());
3007 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3009 PendingLoads.push_back(Chain);
3014 if (!I.getType()->isVoidTy()) {
3015 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3016 EVT VT = TLI.getValueType(PTy);
3017 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3020 setValue(&I, Result);
3024 /// GetSignificand - Get the significand and build it into a floating-point
3025 /// number with exponent of 1:
3027 /// Op = (Op & 0x007fffff) | 0x3f800000;
3029 /// where Op is the hexidecimal representation of floating point value.
3031 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3032 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3033 DAG.getConstant(0x007fffff, MVT::i32));
3034 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3035 DAG.getConstant(0x3f800000, MVT::i32));
3036 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3039 /// GetExponent - Get the exponent:
3041 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3043 /// where Op is the hexidecimal representation of floating point value.
3045 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3047 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3048 DAG.getConstant(0x7f800000, MVT::i32));
3049 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3050 DAG.getConstant(23, TLI.getPointerTy()));
3051 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3052 DAG.getConstant(127, MVT::i32));
3053 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3056 /// getF32Constant - Get 32-bit floating point constant.
3058 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3059 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3062 /// Inlined utility function to implement binary input atomic intrinsics for
3063 /// visitIntrinsicCall: I is a call instruction
3064 /// Op is the associated NodeType for I
3066 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3068 SDValue Root = getRoot();
3070 DAG.getAtomic(Op, getCurDebugLoc(),
3071 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3073 getValue(I.getArgOperand(0)),
3074 getValue(I.getArgOperand(1)),
3075 I.getArgOperand(0));
3077 DAG.setRoot(L.getValue(1));
3081 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3083 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3084 SDValue Op1 = getValue(I.getArgOperand(0));
3085 SDValue Op2 = getValue(I.getArgOperand(1));
3087 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3088 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3092 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3093 /// limited-precision mode.
3095 SelectionDAGBuilder::visitExp(const CallInst &I) {
3097 DebugLoc dl = getCurDebugLoc();
3099 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3100 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3101 SDValue Op = getValue(I.getArgOperand(0));
3103 // Put the exponent in the right bit position for later addition to the
3106 // #define LOG2OFe 1.4426950f
3107 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3108 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3109 getF32Constant(DAG, 0x3fb8aa3b));
3110 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3112 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3113 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3114 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3116 // IntegerPartOfX <<= 23;
3117 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3118 DAG.getConstant(23, TLI.getPointerTy()));
3120 if (LimitFloatPrecision <= 6) {
3121 // For floating-point precision of 6:
3123 // TwoToFractionalPartOfX =
3125 // (0.735607626f + 0.252464424f * x) * x;
3127 // error 0.0144103317, which is 6 bits
3128 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3129 getF32Constant(DAG, 0x3e814304));
3130 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3131 getF32Constant(DAG, 0x3f3c50c8));
3132 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3133 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3134 getF32Constant(DAG, 0x3f7f5e7e));
3135 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3137 // Add the exponent into the result in integer domain.
3138 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3139 TwoToFracPartOfX, IntegerPartOfX);
3141 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3142 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3143 // For floating-point precision of 12:
3145 // TwoToFractionalPartOfX =
3148 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3150 // 0.000107046256 error, which is 13 to 14 bits
3151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3152 getF32Constant(DAG, 0x3da235e3));
3153 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3154 getF32Constant(DAG, 0x3e65b8f3));
3155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3156 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3157 getF32Constant(DAG, 0x3f324b07));
3158 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3159 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3160 getF32Constant(DAG, 0x3f7ff8fd));
3161 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3163 // Add the exponent into the result in integer domain.
3164 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3165 TwoToFracPartOfX, IntegerPartOfX);
3167 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3168 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3169 // For floating-point precision of 18:
3171 // TwoToFractionalPartOfX =
3175 // (0.554906021e-1f +
3176 // (0.961591928e-2f +
3177 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3179 // error 2.47208000*10^(-7), which is better than 18 bits
3180 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3181 getF32Constant(DAG, 0x3924b03e));
3182 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3183 getF32Constant(DAG, 0x3ab24b87));
3184 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3185 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3186 getF32Constant(DAG, 0x3c1d8c17));
3187 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3188 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3189 getF32Constant(DAG, 0x3d634a1d));
3190 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3191 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3192 getF32Constant(DAG, 0x3e75fe14));
3193 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3194 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3195 getF32Constant(DAG, 0x3f317234));
3196 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3197 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3198 getF32Constant(DAG, 0x3f800000));
3199 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3202 // Add the exponent into the result in integer domain.
3203 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3204 TwoToFracPartOfX, IntegerPartOfX);
3206 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3209 // No special expansion.
3210 result = DAG.getNode(ISD::FEXP, dl,
3211 getValue(I.getArgOperand(0)).getValueType(),
3212 getValue(I.getArgOperand(0)));
3215 setValue(&I, result);
3218 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3219 /// limited-precision mode.
3221 SelectionDAGBuilder::visitLog(const CallInst &I) {
3223 DebugLoc dl = getCurDebugLoc();
3225 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3226 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3227 SDValue Op = getValue(I.getArgOperand(0));
3228 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3230 // Scale the exponent by log(2) [0.69314718f].
3231 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3232 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3233 getF32Constant(DAG, 0x3f317218));
3235 // Get the significand and build it into a floating-point number with
3237 SDValue X = GetSignificand(DAG, Op1, dl);
3239 if (LimitFloatPrecision <= 6) {
3240 // For floating-point precision of 6:
3244 // (1.4034025f - 0.23903021f * x) * x;
3246 // error 0.0034276066, which is better than 8 bits
3247 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3248 getF32Constant(DAG, 0xbe74c456));
3249 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3250 getF32Constant(DAG, 0x3fb3a2b1));
3251 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3252 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3253 getF32Constant(DAG, 0x3f949a29));
3255 result = DAG.getNode(ISD::FADD, dl,
3256 MVT::f32, LogOfExponent, LogOfMantissa);
3257 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3258 // For floating-point precision of 12:
3264 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3266 // error 0.000061011436, which is 14 bits
3267 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3268 getF32Constant(DAG, 0xbd67b6d6));
3269 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3270 getF32Constant(DAG, 0x3ee4f4b8));
3271 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3272 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3273 getF32Constant(DAG, 0x3fbc278b));
3274 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3275 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3276 getF32Constant(DAG, 0x40348e95));
3277 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3278 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3279 getF32Constant(DAG, 0x3fdef31a));
3281 result = DAG.getNode(ISD::FADD, dl,
3282 MVT::f32, LogOfExponent, LogOfMantissa);
3283 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3284 // For floating-point precision of 18:
3292 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3294 // error 0.0000023660568, which is better than 18 bits
3295 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3296 getF32Constant(DAG, 0xbc91e5ac));
3297 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3298 getF32Constant(DAG, 0x3e4350aa));
3299 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3300 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3301 getF32Constant(DAG, 0x3f60d3e3));
3302 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3303 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3304 getF32Constant(DAG, 0x4011cdf0));
3305 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3306 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3307 getF32Constant(DAG, 0x406cfd1c));
3308 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3309 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3310 getF32Constant(DAG, 0x408797cb));
3311 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3312 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3313 getF32Constant(DAG, 0x4006dcab));
3315 result = DAG.getNode(ISD::FADD, dl,
3316 MVT::f32, LogOfExponent, LogOfMantissa);
3319 // No special expansion.
3320 result = DAG.getNode(ISD::FLOG, dl,
3321 getValue(I.getArgOperand(0)).getValueType(),
3322 getValue(I.getArgOperand(0)));
3325 setValue(&I, result);
3328 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3329 /// limited-precision mode.
3331 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3333 DebugLoc dl = getCurDebugLoc();
3335 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3336 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3337 SDValue Op = getValue(I.getArgOperand(0));
3338 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3340 // Get the exponent.
3341 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3343 // Get the significand and build it into a floating-point number with
3345 SDValue X = GetSignificand(DAG, Op1, dl);
3347 // Different possible minimax approximations of significand in
3348 // floating-point for various degrees of accuracy over [1,2].
3349 if (LimitFloatPrecision <= 6) {
3350 // For floating-point precision of 6:
3352 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3354 // error 0.0049451742, which is more than 7 bits
3355 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3356 getF32Constant(DAG, 0xbeb08fe0));
3357 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3358 getF32Constant(DAG, 0x40019463));
3359 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3360 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3361 getF32Constant(DAG, 0x3fd6633d));
3363 result = DAG.getNode(ISD::FADD, dl,
3364 MVT::f32, LogOfExponent, Log2ofMantissa);
3365 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3366 // For floating-point precision of 12:
3372 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3374 // error 0.0000876136000, which is better than 13 bits
3375 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3376 getF32Constant(DAG, 0xbda7262e));
3377 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3378 getF32Constant(DAG, 0x3f25280b));
3379 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3380 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3381 getF32Constant(DAG, 0x4007b923));
3382 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3383 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3384 getF32Constant(DAG, 0x40823e2f));
3385 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3386 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3387 getF32Constant(DAG, 0x4020d29c));
3389 result = DAG.getNode(ISD::FADD, dl,
3390 MVT::f32, LogOfExponent, Log2ofMantissa);
3391 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3392 // For floating-point precision of 18:
3401 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3403 // error 0.0000018516, which is better than 18 bits
3404 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3405 getF32Constant(DAG, 0xbcd2769e));
3406 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3407 getF32Constant(DAG, 0x3e8ce0b9));
3408 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3409 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3410 getF32Constant(DAG, 0x3fa22ae7));
3411 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3412 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3413 getF32Constant(DAG, 0x40525723));
3414 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3415 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3416 getF32Constant(DAG, 0x40aaf200));
3417 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3418 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3419 getF32Constant(DAG, 0x40c39dad));
3420 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3421 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3422 getF32Constant(DAG, 0x4042902c));
3424 result = DAG.getNode(ISD::FADD, dl,
3425 MVT::f32, LogOfExponent, Log2ofMantissa);
3428 // No special expansion.
3429 result = DAG.getNode(ISD::FLOG2, dl,
3430 getValue(I.getArgOperand(0)).getValueType(),
3431 getValue(I.getArgOperand(0)));
3434 setValue(&I, result);
3437 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3438 /// limited-precision mode.
3440 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3442 DebugLoc dl = getCurDebugLoc();
3444 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3445 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3446 SDValue Op = getValue(I.getArgOperand(0));
3447 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3449 // Scale the exponent by log10(2) [0.30102999f].
3450 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3451 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3452 getF32Constant(DAG, 0x3e9a209a));
3454 // Get the significand and build it into a floating-point number with
3456 SDValue X = GetSignificand(DAG, Op1, dl);
3458 if (LimitFloatPrecision <= 6) {
3459 // For floating-point precision of 6:
3461 // Log10ofMantissa =
3463 // (0.60948995f - 0.10380950f * x) * x;
3465 // error 0.0014886165, which is 6 bits
3466 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3467 getF32Constant(DAG, 0xbdd49a13));
3468 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3469 getF32Constant(DAG, 0x3f1c0789));
3470 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3471 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3472 getF32Constant(DAG, 0x3f011300));
3474 result = DAG.getNode(ISD::FADD, dl,
3475 MVT::f32, LogOfExponent, Log10ofMantissa);
3476 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3477 // For floating-point precision of 12:
3479 // Log10ofMantissa =
3482 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3484 // error 0.00019228036, which is better than 12 bits
3485 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3486 getF32Constant(DAG, 0x3d431f31));
3487 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3488 getF32Constant(DAG, 0x3ea21fb2));
3489 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3490 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3491 getF32Constant(DAG, 0x3f6ae232));
3492 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3493 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3494 getF32Constant(DAG, 0x3f25f7c3));
3496 result = DAG.getNode(ISD::FADD, dl,
3497 MVT::f32, LogOfExponent, Log10ofMantissa);
3498 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3499 // For floating-point precision of 18:
3501 // Log10ofMantissa =
3506 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3508 // error 0.0000037995730, which is better than 18 bits
3509 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3510 getF32Constant(DAG, 0x3c5d51ce));
3511 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3512 getF32Constant(DAG, 0x3e00685a));
3513 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3514 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3515 getF32Constant(DAG, 0x3efb6798));
3516 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3517 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3518 getF32Constant(DAG, 0x3f88d192));
3519 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3520 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3521 getF32Constant(DAG, 0x3fc4316c));
3522 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3523 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3524 getF32Constant(DAG, 0x3f57ce70));
3526 result = DAG.getNode(ISD::FADD, dl,
3527 MVT::f32, LogOfExponent, Log10ofMantissa);
3530 // No special expansion.
3531 result = DAG.getNode(ISD::FLOG10, dl,
3532 getValue(I.getArgOperand(0)).getValueType(),
3533 getValue(I.getArgOperand(0)));
3536 setValue(&I, result);
3539 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3540 /// limited-precision mode.
3542 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3544 DebugLoc dl = getCurDebugLoc();
3546 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3547 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3548 SDValue Op = getValue(I.getArgOperand(0));
3550 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3552 // FractionalPartOfX = x - (float)IntegerPartOfX;
3553 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3554 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3556 // IntegerPartOfX <<= 23;
3557 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3558 DAG.getConstant(23, TLI.getPointerTy()));
3560 if (LimitFloatPrecision <= 6) {
3561 // For floating-point precision of 6:
3563 // TwoToFractionalPartOfX =
3565 // (0.735607626f + 0.252464424f * x) * x;
3567 // error 0.0144103317, which is 6 bits
3568 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3569 getF32Constant(DAG, 0x3e814304));
3570 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3571 getF32Constant(DAG, 0x3f3c50c8));
3572 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3573 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3574 getF32Constant(DAG, 0x3f7f5e7e));
3575 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3576 SDValue TwoToFractionalPartOfX =
3577 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3579 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3580 MVT::f32, TwoToFractionalPartOfX);
3581 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3582 // For floating-point precision of 12:
3584 // TwoToFractionalPartOfX =
3587 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3589 // error 0.000107046256, which is 13 to 14 bits
3590 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3591 getF32Constant(DAG, 0x3da235e3));
3592 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3593 getF32Constant(DAG, 0x3e65b8f3));
3594 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3595 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3596 getF32Constant(DAG, 0x3f324b07));
3597 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3598 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3599 getF32Constant(DAG, 0x3f7ff8fd));
3600 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3601 SDValue TwoToFractionalPartOfX =
3602 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3604 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3605 MVT::f32, TwoToFractionalPartOfX);
3606 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3607 // For floating-point precision of 18:
3609 // TwoToFractionalPartOfX =
3613 // (0.554906021e-1f +
3614 // (0.961591928e-2f +
3615 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3616 // error 2.47208000*10^(-7), which is better than 18 bits
3617 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3618 getF32Constant(DAG, 0x3924b03e));
3619 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3620 getF32Constant(DAG, 0x3ab24b87));
3621 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3622 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3623 getF32Constant(DAG, 0x3c1d8c17));
3624 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3625 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3626 getF32Constant(DAG, 0x3d634a1d));
3627 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3628 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3629 getF32Constant(DAG, 0x3e75fe14));
3630 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3631 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3632 getF32Constant(DAG, 0x3f317234));
3633 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3634 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3635 getF32Constant(DAG, 0x3f800000));
3636 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3637 SDValue TwoToFractionalPartOfX =
3638 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3640 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3641 MVT::f32, TwoToFractionalPartOfX);
3644 // No special expansion.
3645 result = DAG.getNode(ISD::FEXP2, dl,
3646 getValue(I.getArgOperand(0)).getValueType(),
3647 getValue(I.getArgOperand(0)));
3650 setValue(&I, result);
3653 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3654 /// limited-precision mode with x == 10.0f.
3656 SelectionDAGBuilder::visitPow(const CallInst &I) {
3658 const Value *Val = I.getArgOperand(0);
3659 DebugLoc dl = getCurDebugLoc();
3660 bool IsExp10 = false;
3662 if (getValue(Val).getValueType() == MVT::f32 &&
3663 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3664 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3665 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3666 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3668 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3673 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3674 SDValue Op = getValue(I.getArgOperand(1));
3676 // Put the exponent in the right bit position for later addition to the
3679 // #define LOG2OF10 3.3219281f
3680 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3681 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3682 getF32Constant(DAG, 0x40549a78));
3683 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3685 // FractionalPartOfX = x - (float)IntegerPartOfX;
3686 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3687 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3689 // IntegerPartOfX <<= 23;
3690 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3691 DAG.getConstant(23, TLI.getPointerTy()));
3693 if (LimitFloatPrecision <= 6) {
3694 // For floating-point precision of 6:
3696 // twoToFractionalPartOfX =
3698 // (0.735607626f + 0.252464424f * x) * x;
3700 // error 0.0144103317, which is 6 bits
3701 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3702 getF32Constant(DAG, 0x3e814304));
3703 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3704 getF32Constant(DAG, 0x3f3c50c8));
3705 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3706 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3707 getF32Constant(DAG, 0x3f7f5e7e));
3708 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3709 SDValue TwoToFractionalPartOfX =
3710 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3712 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3713 MVT::f32, TwoToFractionalPartOfX);
3714 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3715 // For floating-point precision of 12:
3717 // TwoToFractionalPartOfX =
3720 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3722 // error 0.000107046256, which is 13 to 14 bits
3723 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3724 getF32Constant(DAG, 0x3da235e3));
3725 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3726 getF32Constant(DAG, 0x3e65b8f3));
3727 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3728 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3729 getF32Constant(DAG, 0x3f324b07));
3730 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3731 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3732 getF32Constant(DAG, 0x3f7ff8fd));
3733 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3734 SDValue TwoToFractionalPartOfX =
3735 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3737 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3738 MVT::f32, TwoToFractionalPartOfX);
3739 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3740 // For floating-point precision of 18:
3742 // TwoToFractionalPartOfX =
3746 // (0.554906021e-1f +
3747 // (0.961591928e-2f +
3748 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3749 // error 2.47208000*10^(-7), which is better than 18 bits
3750 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3751 getF32Constant(DAG, 0x3924b03e));
3752 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3753 getF32Constant(DAG, 0x3ab24b87));
3754 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3755 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3756 getF32Constant(DAG, 0x3c1d8c17));
3757 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3758 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3759 getF32Constant(DAG, 0x3d634a1d));
3760 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3761 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3762 getF32Constant(DAG, 0x3e75fe14));
3763 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3764 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3765 getF32Constant(DAG, 0x3f317234));
3766 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3767 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3768 getF32Constant(DAG, 0x3f800000));
3769 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3770 SDValue TwoToFractionalPartOfX =
3771 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3773 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3774 MVT::f32, TwoToFractionalPartOfX);
3777 // No special expansion.
3778 result = DAG.getNode(ISD::FPOW, dl,
3779 getValue(I.getArgOperand(0)).getValueType(),
3780 getValue(I.getArgOperand(0)),
3781 getValue(I.getArgOperand(1)));
3784 setValue(&I, result);
3788 /// ExpandPowI - Expand a llvm.powi intrinsic.
3789 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3790 SelectionDAG &DAG) {
3791 // If RHS is a constant, we can expand this out to a multiplication tree,
3792 // otherwise we end up lowering to a call to __powidf2 (for example). When
3793 // optimizing for size, we only want to do this if the expansion would produce
3794 // a small number of multiplies, otherwise we do the full expansion.
3795 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3796 // Get the exponent as a positive value.
3797 unsigned Val = RHSC->getSExtValue();
3798 if ((int)Val < 0) Val = -Val;
3800 // powi(x, 0) -> 1.0
3802 return DAG.getConstantFP(1.0, LHS.getValueType());
3804 const Function *F = DAG.getMachineFunction().getFunction();
3805 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3806 // If optimizing for size, don't insert too many multiplies. This
3807 // inserts up to 5 multiplies.
3808 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3809 // We use the simple binary decomposition method to generate the multiply
3810 // sequence. There are more optimal ways to do this (for example,
3811 // powi(x,15) generates one more multiply than it should), but this has
3812 // the benefit of being both really simple and much better than a libcall.
3813 SDValue Res; // Logically starts equal to 1.0
3814 SDValue CurSquare = LHS;
3818 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3820 Res = CurSquare; // 1.0*CurSquare.
3823 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3824 CurSquare, CurSquare);
3828 // If the original was negative, invert the result, producing 1/(x*x*x).
3829 if (RHSC->getSExtValue() < 0)
3830 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3831 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3836 // Otherwise, expand to a libcall.
3837 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3840 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
3841 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
3842 /// At the end of instruction selection, they will be inserted to the entry BB.
3844 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const DbgValueInst &DI,
3845 const Value *V, MDNode *Variable,
3848 if (!isa<Argument>(V))
3851 MachineFunction &MF = DAG.getMachineFunction();
3852 // Ignore inlined function arguments here.
3853 DIVariable DV(Variable);
3854 if (DV.isInlinedFnArgument(MF.getFunction()))
3857 MachineBasicBlock *MBB = FuncInfo.MBBMap[DI.getParent()];
3858 if (MBB != &MF.front())
3862 if (N.getOpcode() == ISD::CopyFromReg) {
3863 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
3864 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
3865 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3866 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
3873 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
3874 if (VMI == FuncInfo.ValueMap.end())
3879 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
3880 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
3881 TII->get(TargetOpcode::DBG_VALUE))
3882 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
3883 FuncInfo.ArgDbgValues.push_back(&*MIB);
3887 // VisualStudio defines setjmp as _setjmp
3888 #if defined(_MSC_VER) && defined(setjmp)
3889 #define setjmp_undefined_for_visual_studio
3893 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3894 /// we want to emit this as a call to a named external function, return the name
3895 /// otherwise lower it and return null.
3897 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
3898 DebugLoc dl = getCurDebugLoc();
3901 switch (Intrinsic) {
3903 // By default, turn this into a target intrinsic node.
3904 visitTargetIntrinsic(I, Intrinsic);
3906 case Intrinsic::vastart: visitVAStart(I); return 0;
3907 case Intrinsic::vaend: visitVAEnd(I); return 0;
3908 case Intrinsic::vacopy: visitVACopy(I); return 0;
3909 case Intrinsic::returnaddress:
3910 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3911 getValue(I.getArgOperand(0))));
3913 case Intrinsic::frameaddress:
3914 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3915 getValue(I.getArgOperand(0))));
3917 case Intrinsic::setjmp:
3918 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3919 case Intrinsic::longjmp:
3920 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3921 case Intrinsic::memcpy: {
3922 // Assert for address < 256 since we support only user defined address
3924 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
3926 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
3928 "Unknown address space");
3929 SDValue Op1 = getValue(I.getArgOperand(0));
3930 SDValue Op2 = getValue(I.getArgOperand(1));
3931 SDValue Op3 = getValue(I.getArgOperand(2));
3932 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
3933 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
3934 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
3935 I.getArgOperand(0), 0, I.getArgOperand(1), 0));
3938 case Intrinsic::memset: {
3939 // Assert for address < 256 since we support only user defined address
3941 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
3943 "Unknown address space");
3944 SDValue Op1 = getValue(I.getArgOperand(0));
3945 SDValue Op2 = getValue(I.getArgOperand(1));
3946 SDValue Op3 = getValue(I.getArgOperand(2));
3947 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
3948 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
3949 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3950 I.getArgOperand(0), 0));
3953 case Intrinsic::memmove: {
3954 // Assert for address < 256 since we support only user defined address
3956 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
3958 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
3960 "Unknown address space");
3961 SDValue Op1 = getValue(I.getArgOperand(0));
3962 SDValue Op2 = getValue(I.getArgOperand(1));
3963 SDValue Op3 = getValue(I.getArgOperand(2));
3964 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
3965 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
3967 // If the source and destination are known to not be aliases, we can
3968 // lower memmove as memcpy.
3969 uint64_t Size = -1ULL;
3970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3971 Size = C->getZExtValue();
3972 if (AA->alias(I.getArgOperand(0), Size, I.getArgOperand(1), Size) ==
3973 AliasAnalysis::NoAlias) {
3974 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3975 false, I.getArgOperand(0), 0, I.getArgOperand(1), 0));
3979 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3980 I.getArgOperand(0), 0, I.getArgOperand(1), 0));
3983 case Intrinsic::dbg_declare: {
3984 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3985 if (!DIVariable(DI.getVariable()).Verify())
3988 MDNode *Variable = DI.getVariable();
3989 // Parameters are handled specially.
3991 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
3992 const Value *Address = DI.getAddress();
3995 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3996 Address = BCI->getOperand(0);
3997 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3999 // Don't handle byval arguments or VLAs, for example.
4000 // Non-byval arguments are handled here (they refer to the stack temporary
4001 // alloca at this point).
4002 DenseMap<const AllocaInst*, int>::iterator SI =
4003 FuncInfo.StaticAllocaMap.find(AI);
4004 if (SI == FuncInfo.StaticAllocaMap.end())
4006 int FI = SI->second;
4008 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4009 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4010 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4013 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4014 // but do not always have a corresponding SDNode built. The SDNodeOrder
4015 // absolute, but not relative, values are different depending on whether
4016 // debug info exists.
4018 SDValue &N = NodeMap[Address];
4021 if (isParameter && !AI) {
4022 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4024 // Byval parameter. We have a frame index at this point.
4025 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4026 0, dl, SDNodeOrder);
4028 // Can't do anything with other non-AI cases yet. This might be a
4029 // parameter of a callee function that got inlined, for example.
4032 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4033 0, dl, SDNodeOrder);
4035 // Can't do anything with other non-AI cases yet.
4037 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4039 // This isn't useful, but it shows what we're missing.
4040 SDV = DAG.getDbgValue(Variable, UndefValue::get(Address->getType()),
4041 0, dl, SDNodeOrder);
4042 DAG.AddDbgValue(SDV, 0, isParameter);
4046 case Intrinsic::dbg_value: {
4047 const DbgValueInst &DI = cast<DbgValueInst>(I);
4048 if (!DIVariable(DI.getVariable()).Verify())
4051 MDNode *Variable = DI.getVariable();
4052 uint64_t Offset = DI.getOffset();
4053 const Value *V = DI.getValue();
4057 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4058 // but do not always have a corresponding SDNode built. The SDNodeOrder
4059 // absolute, but not relative, values are different depending on whether
4060 // debug info exists.
4063 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4064 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4065 DAG.AddDbgValue(SDV, 0, false);
4067 bool createUndef = false;
4068 // FIXME : Why not use getValue() directly ?
4069 SDValue N = NodeMap[V];
4070 if (!N.getNode() && isa<Argument>(V))
4071 // Check unused arguments map.
4072 N = UnusedArgNodeMap[V];
4074 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) {
4075 SDV = DAG.getDbgValue(Variable, N.getNode(),
4076 N.getResNo(), Offset, dl, SDNodeOrder);
4077 DAG.AddDbgValue(SDV, N.getNode(), false);
4079 } else if (isa<PHINode>(V) && !V->use_empty()) {
4080 SDValue N = getValue(V);
4082 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) {
4083 SDV = DAG.getDbgValue(Variable, N.getNode(),
4084 N.getResNo(), Offset, dl, SDNodeOrder);
4085 DAG.AddDbgValue(SDV, N.getNode(), false);
4092 // We may expand this to cover more cases. One case where we have no
4093 // data available is an unreferenced parameter; we need this fallback.
4094 SDV = DAG.getDbgValue(Variable, UndefValue::get(V->getType()),
4095 Offset, dl, SDNodeOrder);
4096 DAG.AddDbgValue(SDV, 0, false);
4100 // Build a debug info table entry.
4101 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4102 V = BCI->getOperand(0);
4103 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4104 // Don't handle byval struct arguments or VLAs, for example.
4107 DenseMap<const AllocaInst*, int>::iterator SI =
4108 FuncInfo.StaticAllocaMap.find(AI);
4109 if (SI == FuncInfo.StaticAllocaMap.end())
4111 int FI = SI->second;
4113 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4114 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4115 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4118 case Intrinsic::eh_exception: {
4119 // Insert the EXCEPTIONADDR instruction.
4120 assert(FuncInfo.MBBMap[I.getParent()]->isLandingPad() &&
4121 "Call to eh.exception not in landing pad!");
4122 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4124 Ops[0] = DAG.getRoot();
4125 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4127 DAG.setRoot(Op.getValue(1));
4131 case Intrinsic::eh_selector: {
4132 MachineBasicBlock *CallMBB = FuncInfo.MBBMap[I.getParent()];
4133 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4134 if (CallMBB->isLandingPad())
4135 AddCatchInfo(I, &MMI, CallMBB);
4138 FuncInfo.CatchInfoLost.insert(&I);
4140 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4141 unsigned Reg = TLI.getExceptionSelectorRegister();
4142 if (Reg) FuncInfo.MBBMap[I.getParent()]->addLiveIn(Reg);
4145 // Insert the EHSELECTION instruction.
4146 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4148 Ops[0] = getValue(I.getArgOperand(0));
4150 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4151 DAG.setRoot(Op.getValue(1));
4152 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4156 case Intrinsic::eh_typeid_for: {
4157 // Find the type id for the given typeinfo.
4158 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4159 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4160 Res = DAG.getConstant(TypeID, MVT::i32);
4165 case Intrinsic::eh_return_i32:
4166 case Intrinsic::eh_return_i64:
4167 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4168 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4171 getValue(I.getArgOperand(0)),
4172 getValue(I.getArgOperand(1))));
4174 case Intrinsic::eh_unwind_init:
4175 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4177 case Intrinsic::eh_dwarf_cfa: {
4178 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4179 TLI.getPointerTy());
4180 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4182 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4183 TLI.getPointerTy()),
4185 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4187 DAG.getConstant(0, TLI.getPointerTy()));
4188 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4192 case Intrinsic::eh_sjlj_callsite: {
4193 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4194 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4195 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4196 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4198 MMI.setCurrentCallSite(CI->getZExtValue());
4201 case Intrinsic::eh_sjlj_setjmp: {
4202 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4203 getValue(I.getArgOperand(0))));
4206 case Intrinsic::eh_sjlj_longjmp: {
4207 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4209 getValue(I.getArgOperand(0))));
4213 case Intrinsic::convertff:
4214 case Intrinsic::convertfsi:
4215 case Intrinsic::convertfui:
4216 case Intrinsic::convertsif:
4217 case Intrinsic::convertuif:
4218 case Intrinsic::convertss:
4219 case Intrinsic::convertsu:
4220 case Intrinsic::convertus:
4221 case Intrinsic::convertuu: {
4222 ISD::CvtCode Code = ISD::CVT_INVALID;
4223 switch (Intrinsic) {
4224 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4225 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4226 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4227 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4228 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4229 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4230 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4231 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4232 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4234 EVT DestVT = TLI.getValueType(I.getType());
4235 const Value *Op1 = I.getArgOperand(0);
4236 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4237 DAG.getValueType(DestVT),
4238 DAG.getValueType(getValue(Op1).getValueType()),
4239 getValue(I.getArgOperand(1)),
4240 getValue(I.getArgOperand(2)),
4245 case Intrinsic::sqrt:
4246 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4247 getValue(I.getArgOperand(0)).getValueType(),
4248 getValue(I.getArgOperand(0))));
4250 case Intrinsic::powi:
4251 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4252 getValue(I.getArgOperand(1)), DAG));
4254 case Intrinsic::sin:
4255 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4256 getValue(I.getArgOperand(0)).getValueType(),
4257 getValue(I.getArgOperand(0))));
4259 case Intrinsic::cos:
4260 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4261 getValue(I.getArgOperand(0)).getValueType(),
4262 getValue(I.getArgOperand(0))));
4264 case Intrinsic::log:
4267 case Intrinsic::log2:
4270 case Intrinsic::log10:
4273 case Intrinsic::exp:
4276 case Intrinsic::exp2:
4279 case Intrinsic::pow:
4282 case Intrinsic::convert_to_fp16:
4283 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4284 MVT::i16, getValue(I.getArgOperand(0))));
4286 case Intrinsic::convert_from_fp16:
4287 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4288 MVT::f32, getValue(I.getArgOperand(0))));
4290 case Intrinsic::pcmarker: {
4291 SDValue Tmp = getValue(I.getArgOperand(0));
4292 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4295 case Intrinsic::readcyclecounter: {
4296 SDValue Op = getRoot();
4297 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4298 DAG.getVTList(MVT::i64, MVT::Other),
4301 DAG.setRoot(Res.getValue(1));
4304 case Intrinsic::bswap:
4305 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4306 getValue(I.getArgOperand(0)).getValueType(),
4307 getValue(I.getArgOperand(0))));
4309 case Intrinsic::cttz: {
4310 SDValue Arg = getValue(I.getArgOperand(0));
4311 EVT Ty = Arg.getValueType();
4312 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4315 case Intrinsic::ctlz: {
4316 SDValue Arg = getValue(I.getArgOperand(0));
4317 EVT Ty = Arg.getValueType();
4318 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4321 case Intrinsic::ctpop: {
4322 SDValue Arg = getValue(I.getArgOperand(0));
4323 EVT Ty = Arg.getValueType();
4324 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4327 case Intrinsic::stacksave: {
4328 SDValue Op = getRoot();
4329 Res = DAG.getNode(ISD::STACKSAVE, dl,
4330 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4332 DAG.setRoot(Res.getValue(1));
4335 case Intrinsic::stackrestore: {
4336 Res = getValue(I.getArgOperand(0));
4337 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4340 case Intrinsic::stackprotector: {
4341 // Emit code into the DAG to store the stack guard onto the stack.
4342 MachineFunction &MF = DAG.getMachineFunction();
4343 MachineFrameInfo *MFI = MF.getFrameInfo();
4344 EVT PtrTy = TLI.getPointerTy();
4346 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4347 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4349 int FI = FuncInfo.StaticAllocaMap[Slot];
4350 MFI->setStackProtectorIndex(FI);
4352 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4354 // Store the stack protector onto the stack.
4355 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4356 PseudoSourceValue::getFixedStack(FI),
4362 case Intrinsic::objectsize: {
4363 // If we don't know by now, we're never going to know.
4364 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4366 assert(CI && "Non-constant type in __builtin_object_size?");
4368 SDValue Arg = getValue(I.getCalledValue());
4369 EVT Ty = Arg.getValueType();
4372 Res = DAG.getConstant(-1ULL, Ty);
4374 Res = DAG.getConstant(0, Ty);
4379 case Intrinsic::var_annotation:
4380 // Discard annotate attributes
4383 case Intrinsic::init_trampoline: {
4384 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4388 Ops[1] = getValue(I.getArgOperand(0));
4389 Ops[2] = getValue(I.getArgOperand(1));
4390 Ops[3] = getValue(I.getArgOperand(2));
4391 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4392 Ops[5] = DAG.getSrcValue(F);
4394 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4395 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4399 DAG.setRoot(Res.getValue(1));
4402 case Intrinsic::gcroot:
4404 const Value *Alloca = I.getArgOperand(0);
4405 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4407 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4408 GFI->addStackRoot(FI->getIndex(), TypeMap);
4411 case Intrinsic::gcread:
4412 case Intrinsic::gcwrite:
4413 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4415 case Intrinsic::flt_rounds:
4416 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4418 case Intrinsic::trap:
4419 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4421 case Intrinsic::uadd_with_overflow:
4422 return implVisitAluOverflow(I, ISD::UADDO);
4423 case Intrinsic::sadd_with_overflow:
4424 return implVisitAluOverflow(I, ISD::SADDO);
4425 case Intrinsic::usub_with_overflow:
4426 return implVisitAluOverflow(I, ISD::USUBO);
4427 case Intrinsic::ssub_with_overflow:
4428 return implVisitAluOverflow(I, ISD::SSUBO);
4429 case Intrinsic::umul_with_overflow:
4430 return implVisitAluOverflow(I, ISD::UMULO);
4431 case Intrinsic::smul_with_overflow:
4432 return implVisitAluOverflow(I, ISD::SMULO);
4434 case Intrinsic::prefetch: {
4437 Ops[1] = getValue(I.getArgOperand(0));
4438 Ops[2] = getValue(I.getArgOperand(1));
4439 Ops[3] = getValue(I.getArgOperand(2));
4440 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4444 case Intrinsic::memory_barrier: {
4447 for (int x = 1; x < 6; ++x)
4448 Ops[x] = getValue(I.getArgOperand(x - 1));
4450 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4453 case Intrinsic::atomic_cmp_swap: {
4454 SDValue Root = getRoot();
4456 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4457 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4459 getValue(I.getArgOperand(0)),
4460 getValue(I.getArgOperand(1)),
4461 getValue(I.getArgOperand(2)),
4462 I.getArgOperand(0));
4464 DAG.setRoot(L.getValue(1));
4467 case Intrinsic::atomic_load_add:
4468 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4469 case Intrinsic::atomic_load_sub:
4470 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4471 case Intrinsic::atomic_load_or:
4472 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4473 case Intrinsic::atomic_load_xor:
4474 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4475 case Intrinsic::atomic_load_and:
4476 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4477 case Intrinsic::atomic_load_nand:
4478 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4479 case Intrinsic::atomic_load_max:
4480 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4481 case Intrinsic::atomic_load_min:
4482 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4483 case Intrinsic::atomic_load_umin:
4484 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4485 case Intrinsic::atomic_load_umax:
4486 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4487 case Intrinsic::atomic_swap:
4488 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4490 case Intrinsic::invariant_start:
4491 case Intrinsic::lifetime_start:
4492 // Discard region information.
4493 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4495 case Intrinsic::invariant_end:
4496 case Intrinsic::lifetime_end:
4497 // Discard region information.
4502 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4504 MachineBasicBlock *LandingPad) {
4505 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4506 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4507 const Type *RetTy = FTy->getReturnType();
4508 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4509 MCSymbol *BeginLabel = 0;
4511 TargetLowering::ArgListTy Args;
4512 TargetLowering::ArgListEntry Entry;
4513 Args.reserve(CS.arg_size());
4515 // Check whether the function can return without sret-demotion.
4516 SmallVector<EVT, 4> OutVTs;
4517 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4518 SmallVector<uint64_t, 4> Offsets;
4519 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4520 OutVTs, OutsFlags, TLI, &Offsets);
4522 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4523 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4525 SDValue DemoteStackSlot;
4527 if (!CanLowerReturn) {
4528 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4529 FTy->getReturnType());
4530 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4531 FTy->getReturnType());
4532 MachineFunction &MF = DAG.getMachineFunction();
4533 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4534 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4536 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4537 Entry.Node = DemoteStackSlot;
4538 Entry.Ty = StackSlotPtrType;
4539 Entry.isSExt = false;
4540 Entry.isZExt = false;
4541 Entry.isInReg = false;
4542 Entry.isSRet = true;
4543 Entry.isNest = false;
4544 Entry.isByVal = false;
4545 Entry.Alignment = Align;
4546 Args.push_back(Entry);
4547 RetTy = Type::getVoidTy(FTy->getContext());
4550 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4552 SDValue ArgNode = getValue(*i);
4553 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4555 unsigned attrInd = i - CS.arg_begin() + 1;
4556 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4557 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4558 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4559 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4560 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4561 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4562 Entry.Alignment = CS.getParamAlignment(attrInd);
4563 Args.push_back(Entry);
4567 // Insert a label before the invoke call to mark the try range. This can be
4568 // used to detect deletion of the invoke via the MachineModuleInfo.
4569 BeginLabel = MMI.getContext().CreateTempSymbol();
4571 // For SjLj, keep track of which landing pads go with which invokes
4572 // so as to maintain the ordering of pads in the LSDA.
4573 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4574 if (CallSiteIndex) {
4575 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4576 // Now that the call site is handled, stop tracking it.
4577 MMI.setCurrentCallSite(0);
4580 // Both PendingLoads and PendingExports must be flushed here;
4581 // this call might not return.
4583 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4586 // Check if target-independent constraints permit a tail call here.
4587 // Target-dependent constraints are checked within TLI.LowerCallTo.
4589 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4592 std::pair<SDValue,SDValue> Result =
4593 TLI.LowerCallTo(getRoot(), RetTy,
4594 CS.paramHasAttr(0, Attribute::SExt),
4595 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4596 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4597 CS.getCallingConv(),
4599 !CS.getInstruction()->use_empty(),
4600 Callee, Args, DAG, getCurDebugLoc());
4601 assert((isTailCall || Result.second.getNode()) &&
4602 "Non-null chain expected with non-tail call!");
4603 assert((Result.second.getNode() || !Result.first.getNode()) &&
4604 "Null value expected with tail call!");
4605 if (Result.first.getNode()) {
4606 setValue(CS.getInstruction(), Result.first);
4607 } else if (!CanLowerReturn && Result.second.getNode()) {
4608 // The instruction result is the result of loading from the
4609 // hidden sret parameter.
4610 SmallVector<EVT, 1> PVTs;
4611 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4613 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4614 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4615 EVT PtrVT = PVTs[0];
4616 unsigned NumValues = OutVTs.size();
4617 SmallVector<SDValue, 4> Values(NumValues);
4618 SmallVector<SDValue, 4> Chains(NumValues);
4620 for (unsigned i = 0; i < NumValues; ++i) {
4621 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4623 DAG.getConstant(Offsets[i], PtrVT));
4624 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4625 Add, NULL, Offsets[i], false, false, 1);
4627 Chains[i] = L.getValue(1);
4630 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4631 MVT::Other, &Chains[0], NumValues);
4632 PendingLoads.push_back(Chain);
4634 // Collect the legal value parts into potentially illegal values
4635 // that correspond to the original function's return values.
4636 SmallVector<EVT, 4> RetTys;
4637 RetTy = FTy->getReturnType();
4638 ComputeValueVTs(TLI, RetTy, RetTys);
4639 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4640 SmallVector<SDValue, 4> ReturnValues;
4641 unsigned CurReg = 0;
4642 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4644 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4645 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4647 SDValue ReturnValue =
4648 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4649 RegisterVT, VT, AssertOp);
4650 ReturnValues.push_back(ReturnValue);
4654 setValue(CS.getInstruction(),
4655 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4656 DAG.getVTList(&RetTys[0], RetTys.size()),
4657 &ReturnValues[0], ReturnValues.size()));
4661 // As a special case, a null chain means that a tail call has been emitted and
4662 // the DAG root is already updated.
4663 if (Result.second.getNode())
4664 DAG.setRoot(Result.second);
4669 // Insert a label at the end of the invoke call to mark the try range. This
4670 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4671 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
4672 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4674 // Inform MachineModuleInfo of range.
4675 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
4679 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4680 /// value is equal or not-equal to zero.
4681 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
4682 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
4684 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4685 if (IC->isEquality())
4686 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4687 if (C->isNullValue())
4689 // Unknown instruction.
4695 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
4697 SelectionDAGBuilder &Builder) {
4699 // Check to see if this load can be trivially constant folded, e.g. if the
4700 // input is from a string literal.
4701 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4702 // Cast pointer to the type we really want to load.
4703 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
4704 PointerType::getUnqual(LoadTy));
4706 if (const Constant *LoadCst =
4707 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
4709 return Builder.getValue(LoadCst);
4712 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4713 // still constant memory, the input chain can be the entry node.
4715 bool ConstantMemory = false;
4717 // Do not serialize (non-volatile) loads of constant memory with anything.
4718 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4719 Root = Builder.DAG.getEntryNode();
4720 ConstantMemory = true;
4722 // Do not serialize non-volatile loads against each other.
4723 Root = Builder.DAG.getRoot();
4726 SDValue Ptr = Builder.getValue(PtrVal);
4727 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4728 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4730 false /*nontemporal*/, 1 /* align=1 */);
4732 if (!ConstantMemory)
4733 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4738 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4739 /// If so, return true and lower it, otherwise return false and it will be
4740 /// lowered like a normal call.
4741 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
4742 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4743 if (I.getNumArgOperands() != 3)
4746 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
4747 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4748 !I.getArgOperand(2)->getType()->isIntegerTy() ||
4749 !I.getType()->isIntegerTy())
4752 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
4754 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4755 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4756 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4757 bool ActuallyDoIt = true;
4760 switch (Size->getZExtValue()) {
4762 LoadVT = MVT::Other;
4764 ActuallyDoIt = false;
4768 LoadTy = Type::getInt16Ty(Size->getContext());
4772 LoadTy = Type::getInt32Ty(Size->getContext());
4776 LoadTy = Type::getInt64Ty(Size->getContext());
4780 LoadVT = MVT::v4i32;
4781 LoadTy = Type::getInt32Ty(Size->getContext());
4782 LoadTy = VectorType::get(LoadTy, 4);
4787 // This turns into unaligned loads. We only do this if the target natively
4788 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4789 // we'll only produce a small number of byte loads.
4791 // Require that we can find a legal MVT, and only do this if the target
4792 // supports unaligned loads of that type. Expanding into byte loads would
4794 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4795 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4796 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4797 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4798 ActuallyDoIt = false;
4802 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4803 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4805 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4807 EVT CallVT = TLI.getValueType(I.getType(), true);
4808 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4818 void SelectionDAGBuilder::visitCall(const CallInst &I) {
4819 const char *RenameFn = 0;
4820 if (Function *F = I.getCalledFunction()) {
4821 if (F->isDeclaration()) {
4822 const TargetIntrinsicInfo *II = TM.getIntrinsicInfo();
4824 if (unsigned IID = II->getIntrinsicID(F)) {
4825 RenameFn = visitIntrinsicCall(I, IID);
4830 if (unsigned IID = F->getIntrinsicID()) {
4831 RenameFn = visitIntrinsicCall(I, IID);
4837 // Check for well-known libc/libm calls. If the function is internal, it
4838 // can't be a library call.
4839 if (!F->hasLocalLinkage() && F->hasName()) {
4840 StringRef Name = F->getName();
4841 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
4842 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
4843 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4844 I.getType() == I.getArgOperand(0)->getType() &&
4845 I.getType() == I.getArgOperand(1)->getType()) {
4846 SDValue LHS = getValue(I.getArgOperand(0));
4847 SDValue RHS = getValue(I.getArgOperand(1));
4848 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4849 LHS.getValueType(), LHS, RHS));
4852 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4853 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4854 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4855 I.getType() == I.getArgOperand(0)->getType()) {
4856 SDValue Tmp = getValue(I.getArgOperand(0));
4857 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4858 Tmp.getValueType(), Tmp));
4861 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4862 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4863 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4864 I.getType() == I.getArgOperand(0)->getType() &&
4865 I.onlyReadsMemory()) {
4866 SDValue Tmp = getValue(I.getArgOperand(0));
4867 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4868 Tmp.getValueType(), Tmp));
4871 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4872 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4873 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4874 I.getType() == I.getArgOperand(0)->getType() &&
4875 I.onlyReadsMemory()) {
4876 SDValue Tmp = getValue(I.getArgOperand(0));
4877 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4878 Tmp.getValueType(), Tmp));
4881 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4882 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4883 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4884 I.getType() == I.getArgOperand(0)->getType() &&
4885 I.onlyReadsMemory()) {
4886 SDValue Tmp = getValue(I.getArgOperand(0));
4887 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4888 Tmp.getValueType(), Tmp));
4891 } else if (Name == "memcmp") {
4892 if (visitMemCmpCall(I))
4896 } else if (isa<InlineAsm>(I.getCalledValue())) {
4903 Callee = getValue(I.getCalledValue());
4905 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4907 // Check if we can potentially perform a tail call. More detailed checking is
4908 // be done within LowerCallTo, after more information about the call is known.
4909 LowerCallTo(&I, Callee, I.isTailCall());
4914 /// AsmOperandInfo - This contains information for each constraint that we are
4916 class LLVM_LIBRARY_VISIBILITY SDISelAsmOperandInfo :
4917 public TargetLowering::AsmOperandInfo {
4919 /// CallOperand - If this is the result output operand or a clobber
4920 /// this is null, otherwise it is the incoming operand to the CallInst.
4921 /// This gets modified as the asm is processed.
4922 SDValue CallOperand;
4924 /// AssignedRegs - If this is a register or register class operand, this
4925 /// contains the set of register corresponding to the operand.
4926 RegsForValue AssignedRegs;
4928 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4929 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4932 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4933 /// busy in OutputRegs/InputRegs.
4934 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4935 std::set<unsigned> &OutputRegs,
4936 std::set<unsigned> &InputRegs,
4937 const TargetRegisterInfo &TRI) const {
4939 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4940 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4943 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4944 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4948 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4949 /// corresponds to. If there is no Value* for this operand, it returns
4951 EVT getCallOperandValEVT(LLVMContext &Context,
4952 const TargetLowering &TLI,
4953 const TargetData *TD) const {
4954 if (CallOperandVal == 0) return MVT::Other;
4956 if (isa<BasicBlock>(CallOperandVal))
4957 return TLI.getPointerTy();
4959 const llvm::Type *OpTy = CallOperandVal->getType();
4961 // If this is an indirect operand, the operand is a pointer to the
4964 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4966 report_fatal_error("Indirect operand for inline asm not a pointer!");
4967 OpTy = PtrTy->getElementType();
4970 // If OpTy is not a single value, it may be a struct/union that we
4971 // can tile with integers.
4972 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4973 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4982 OpTy = IntegerType::get(Context, BitSize);
4987 return TLI.getValueType(OpTy, true);
4991 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4993 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4994 const TargetRegisterInfo &TRI) {
4995 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4997 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4998 for (; *Aliases; ++Aliases)
4999 Regs.insert(*Aliases);
5003 } // end llvm namespace.
5005 /// isAllocatableRegister - If the specified register is safe to allocate,
5006 /// i.e. it isn't a stack pointer or some other special register, return the
5007 /// register class for the register. Otherwise, return null.
5008 static const TargetRegisterClass *
5009 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5010 const TargetLowering &TLI,
5011 const TargetRegisterInfo *TRI) {
5012 EVT FoundVT = MVT::Other;
5013 const TargetRegisterClass *FoundRC = 0;
5014 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5015 E = TRI->regclass_end(); RCI != E; ++RCI) {
5016 EVT ThisVT = MVT::Other;
5018 const TargetRegisterClass *RC = *RCI;
5019 // If none of the value types for this register class are valid, we
5020 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5021 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5023 if (TLI.isTypeLegal(*I)) {
5024 // If we have already found this register in a different register class,
5025 // choose the one with the largest VT specified. For example, on
5026 // PowerPC, we favor f64 register classes over f32.
5027 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5034 if (ThisVT == MVT::Other) continue;
5036 // NOTE: This isn't ideal. In particular, this might allocate the
5037 // frame pointer in functions that need it (due to them not being taken
5038 // out of allocation, because a variable sized allocation hasn't been seen
5039 // yet). This is a slight code pessimization, but should still work.
5040 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5041 E = RC->allocation_order_end(MF); I != E; ++I)
5043 // We found a matching register class. Keep looking at others in case
5044 // we find one with larger registers that this physreg is also in.
5053 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5054 /// specified operand. We prefer to assign virtual registers, to allow the
5055 /// register allocator to handle the assignment process. However, if the asm
5056 /// uses features that we can't model on machineinstrs, we have SDISel do the
5057 /// allocation. This produces generally horrible, but correct, code.
5059 /// OpInfo describes the operand.
5060 /// Input and OutputRegs are the set of already allocated physical registers.
5062 void SelectionDAGBuilder::
5063 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5064 std::set<unsigned> &OutputRegs,
5065 std::set<unsigned> &InputRegs) {
5066 LLVMContext &Context = FuncInfo.Fn->getContext();
5068 // Compute whether this value requires an input register, an output register,
5070 bool isOutReg = false;
5071 bool isInReg = false;
5072 switch (OpInfo.Type) {
5073 case InlineAsm::isOutput:
5076 // If there is an input constraint that matches this, we need to reserve
5077 // the input register so no other inputs allocate to it.
5078 isInReg = OpInfo.hasMatchingInput();
5080 case InlineAsm::isInput:
5084 case InlineAsm::isClobber:
5091 MachineFunction &MF = DAG.getMachineFunction();
5092 SmallVector<unsigned, 4> Regs;
5094 // If this is a constraint for a single physreg, or a constraint for a
5095 // register class, find it.
5096 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5097 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5098 OpInfo.ConstraintVT);
5100 unsigned NumRegs = 1;
5101 if (OpInfo.ConstraintVT != MVT::Other) {
5102 // If this is a FP input in an integer register (or visa versa) insert a bit
5103 // cast of the input value. More generally, handle any case where the input
5104 // value disagrees with the register class we plan to stick this in.
5105 if (OpInfo.Type == InlineAsm::isInput &&
5106 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5107 // Try to convert to the first EVT that the reg class contains. If the
5108 // types are identical size, use a bitcast to convert (e.g. two differing
5110 EVT RegVT = *PhysReg.second->vt_begin();
5111 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5112 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5113 RegVT, OpInfo.CallOperand);
5114 OpInfo.ConstraintVT = RegVT;
5115 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5116 // If the input is a FP value and we want it in FP registers, do a
5117 // bitcast to the corresponding integer type. This turns an f64 value
5118 // into i64, which can be passed with two i32 values on a 32-bit
5120 RegVT = EVT::getIntegerVT(Context,
5121 OpInfo.ConstraintVT.getSizeInBits());
5122 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5123 RegVT, OpInfo.CallOperand);
5124 OpInfo.ConstraintVT = RegVT;
5128 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5132 EVT ValueVT = OpInfo.ConstraintVT;
5134 // If this is a constraint for a specific physical register, like {r17},
5136 if (unsigned AssignedReg = PhysReg.first) {
5137 const TargetRegisterClass *RC = PhysReg.second;
5138 if (OpInfo.ConstraintVT == MVT::Other)
5139 ValueVT = *RC->vt_begin();
5141 // Get the actual register value type. This is important, because the user
5142 // may have asked for (e.g.) the AX register in i32 type. We need to
5143 // remember that AX is actually i16 to get the right extension.
5144 RegVT = *RC->vt_begin();
5146 // This is a explicit reference to a physical register.
5147 Regs.push_back(AssignedReg);
5149 // If this is an expanded reference, add the rest of the regs to Regs.
5151 TargetRegisterClass::iterator I = RC->begin();
5152 for (; *I != AssignedReg; ++I)
5153 assert(I != RC->end() && "Didn't find reg!");
5155 // Already added the first reg.
5157 for (; NumRegs; --NumRegs, ++I) {
5158 assert(I != RC->end() && "Ran out of registers to allocate!");
5163 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5164 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5165 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5169 // Otherwise, if this was a reference to an LLVM register class, create vregs
5170 // for this reference.
5171 if (const TargetRegisterClass *RC = PhysReg.second) {
5172 RegVT = *RC->vt_begin();
5173 if (OpInfo.ConstraintVT == MVT::Other)
5176 // Create the appropriate number of virtual registers.
5177 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5178 for (; NumRegs; --NumRegs)
5179 Regs.push_back(RegInfo.createVirtualRegister(RC));
5181 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5185 // This is a reference to a register class that doesn't directly correspond
5186 // to an LLVM register class. Allocate NumRegs consecutive, available,
5187 // registers from the class.
5188 std::vector<unsigned> RegClassRegs
5189 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5190 OpInfo.ConstraintVT);
5192 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5193 unsigned NumAllocated = 0;
5194 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5195 unsigned Reg = RegClassRegs[i];
5196 // See if this register is available.
5197 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5198 (isInReg && InputRegs.count(Reg))) { // Already used.
5199 // Make sure we find consecutive registers.
5204 // Check to see if this register is allocatable (i.e. don't give out the
5206 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5207 if (!RC) { // Couldn't allocate this register.
5208 // Reset NumAllocated to make sure we return consecutive registers.
5213 // Okay, this register is good, we can use it.
5216 // If we allocated enough consecutive registers, succeed.
5217 if (NumAllocated == NumRegs) {
5218 unsigned RegStart = (i-NumAllocated)+1;
5219 unsigned RegEnd = i+1;
5220 // Mark all of the allocated registers used.
5221 for (unsigned i = RegStart; i != RegEnd; ++i)
5222 Regs.push_back(RegClassRegs[i]);
5224 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
5225 OpInfo.ConstraintVT);
5226 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5231 // Otherwise, we couldn't allocate enough registers for this.
5234 /// visitInlineAsm - Handle a call to an InlineAsm object.
5236 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5237 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5239 /// ConstraintOperands - Information about all of the constraints.
5240 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5242 std::set<unsigned> OutputRegs, InputRegs;
5244 // Do a prepass over the constraints, canonicalizing them, and building up the
5245 // ConstraintOperands list.
5246 std::vector<InlineAsm::ConstraintInfo>
5247 ConstraintInfos = IA->ParseConstraints();
5249 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5251 SDValue Chain, Flag;
5253 // We won't need to flush pending loads if this asm doesn't touch
5254 // memory and is nonvolatile.
5255 if (hasMemory || IA->hasSideEffects())
5258 Chain = DAG.getRoot();
5260 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5261 unsigned ResNo = 0; // ResNo - The result number of the next output.
5262 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5263 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5264 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5266 EVT OpVT = MVT::Other;
5268 // Compute the value type for each operand.
5269 switch (OpInfo.Type) {
5270 case InlineAsm::isOutput:
5271 // Indirect outputs just consume an argument.
5272 if (OpInfo.isIndirect) {
5273 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5277 // The return value of the call is this value. As such, there is no
5278 // corresponding argument.
5279 assert(!CS.getType()->isVoidTy() &&
5281 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5282 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5284 assert(ResNo == 0 && "Asm only has one result!");
5285 OpVT = TLI.getValueType(CS.getType());
5289 case InlineAsm::isInput:
5290 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5292 case InlineAsm::isClobber:
5297 // If this is an input or an indirect output, process the call argument.
5298 // BasicBlocks are labels, currently appearing only in asm's.
5299 if (OpInfo.CallOperandVal) {
5300 // Strip bitcasts, if any. This mostly comes up for functions.
5301 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5303 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5304 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5306 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5309 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5312 OpInfo.ConstraintVT = OpVT;
5315 // Second pass over the constraints: compute which constraint option to use
5316 // and assign registers to constraints that want a specific physreg.
5317 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5318 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5320 // If this is an output operand with a matching input operand, look up the
5321 // matching input. If their types mismatch, e.g. one is an integer, the
5322 // other is floating point, or their sizes are different, flag it as an
5324 if (OpInfo.hasMatchingInput()) {
5325 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5327 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5328 if ((OpInfo.ConstraintVT.isInteger() !=
5329 Input.ConstraintVT.isInteger()) ||
5330 (OpInfo.ConstraintVT.getSizeInBits() !=
5331 Input.ConstraintVT.getSizeInBits())) {
5332 report_fatal_error("Unsupported asm: input constraint"
5333 " with a matching output constraint of"
5334 " incompatible type!");
5336 Input.ConstraintVT = OpInfo.ConstraintVT;
5340 // Compute the constraint code and ConstraintType to use.
5341 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5343 // If this is a memory input, and if the operand is not indirect, do what we
5344 // need to to provide an address for the memory input.
5345 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5346 !OpInfo.isIndirect) {
5347 assert(OpInfo.Type == InlineAsm::isInput &&
5348 "Can only indirectify direct input operands!");
5350 // Memory operands really want the address of the value. If we don't have
5351 // an indirect input, put it in the constpool if we can, otherwise spill
5352 // it to a stack slot.
5354 // If the operand is a float, integer, or vector constant, spill to a
5355 // constant pool entry to get its address.
5356 const Value *OpVal = OpInfo.CallOperandVal;
5357 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5358 isa<ConstantVector>(OpVal)) {
5359 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5360 TLI.getPointerTy());
5362 // Otherwise, create a stack slot and emit a store to it before the
5364 const Type *Ty = OpVal->getType();
5365 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5366 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5367 MachineFunction &MF = DAG.getMachineFunction();
5368 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5369 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5370 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5371 OpInfo.CallOperand, StackSlot, NULL, 0,
5373 OpInfo.CallOperand = StackSlot;
5376 // There is no longer a Value* corresponding to this operand.
5377 OpInfo.CallOperandVal = 0;
5379 // It is now an indirect operand.
5380 OpInfo.isIndirect = true;
5383 // If this constraint is for a specific register, allocate it before
5385 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5386 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5389 ConstraintInfos.clear();
5391 // Second pass - Loop over all of the operands, assigning virtual or physregs
5392 // to register class operands.
5393 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5394 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5396 // C_Register operands have already been allocated, Other/Memory don't need
5398 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5399 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5402 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5403 std::vector<SDValue> AsmNodeOperands;
5404 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5405 AsmNodeOperands.push_back(
5406 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5407 TLI.getPointerTy()));
5409 // If we have a !srcloc metadata node associated with it, we want to attach
5410 // this to the ultimately generated inline asm machineinstr. To do this, we
5411 // pass in the third operand as this (potentially null) inline asm MDNode.
5412 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5413 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5415 // Loop over all of the inputs, copying the operand values into the
5416 // appropriate registers and processing the output regs.
5417 RegsForValue RetValRegs;
5419 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5420 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5422 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5423 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5425 switch (OpInfo.Type) {
5426 case InlineAsm::isOutput: {
5427 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5428 OpInfo.ConstraintType != TargetLowering::C_Register) {
5429 // Memory output, or 'other' output (e.g. 'X' constraint).
5430 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5432 // Add information to the INLINEASM node to know about this output.
5433 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5434 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5435 TLI.getPointerTy()));
5436 AsmNodeOperands.push_back(OpInfo.CallOperand);
5440 // Otherwise, this is a register or register class output.
5442 // Copy the output from the appropriate register. Find a register that
5444 if (OpInfo.AssignedRegs.Regs.empty())
5445 report_fatal_error("Couldn't allocate output reg for constraint '" +
5446 Twine(OpInfo.ConstraintCode) + "'!");
5448 // If this is an indirect operand, store through the pointer after the
5450 if (OpInfo.isIndirect) {
5451 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5452 OpInfo.CallOperandVal));
5454 // This is the result value of the call.
5455 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5456 // Concatenate this output onto the outputs list.
5457 RetValRegs.append(OpInfo.AssignedRegs);
5460 // Add information to the INLINEASM node to know that this register is
5462 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5463 InlineAsm::Kind_RegDefEarlyClobber :
5464 InlineAsm::Kind_RegDef,
5471 case InlineAsm::isInput: {
5472 SDValue InOperandVal = OpInfo.CallOperand;
5474 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5475 // If this is required to match an output register we have already set,
5476 // just use its register.
5477 unsigned OperandNo = OpInfo.getMatchedOperand();
5479 // Scan until we find the definition we already emitted of this operand.
5480 // When we find it, create a RegsForValue operand.
5481 unsigned CurOp = InlineAsm::Op_FirstOperand;
5482 for (; OperandNo; --OperandNo) {
5483 // Advance to the next operand.
5485 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5486 assert((InlineAsm::isRegDefKind(OpFlag) ||
5487 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5488 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5489 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5493 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5494 if (InlineAsm::isRegDefKind(OpFlag) ||
5495 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5496 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5497 if (OpInfo.isIndirect) {
5498 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5499 LLVMContext &Ctx = *DAG.getContext();
5500 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5501 " don't know how to handle tied "
5502 "indirect register inputs");
5505 RegsForValue MatchedRegs;
5506 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5507 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5508 MatchedRegs.RegVTs.push_back(RegVT);
5509 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5510 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5512 MatchedRegs.Regs.push_back
5513 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5515 // Use the produced MatchedRegs object to
5516 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5518 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5519 true, OpInfo.getMatchedOperand(),
5520 DAG, AsmNodeOperands);
5524 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5525 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5526 "Unexpected number of operands");
5527 // Add information to the INLINEASM node to know about this input.
5528 // See InlineAsm.h isUseOperandTiedToDef.
5529 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5530 OpInfo.getMatchedOperand());
5531 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5532 TLI.getPointerTy()));
5533 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5537 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5538 assert(!OpInfo.isIndirect &&
5539 "Don't know how to handle indirect other inputs yet!");
5541 std::vector<SDValue> Ops;
5542 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5545 report_fatal_error("Invalid operand for inline asm constraint '" +
5546 Twine(OpInfo.ConstraintCode) + "'!");
5548 // Add information to the INLINEASM node to know about this input.
5549 unsigned ResOpType =
5550 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5551 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5552 TLI.getPointerTy()));
5553 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5557 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5558 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5559 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5560 "Memory operands expect pointer values");
5562 // Add information to the INLINEASM node to know about this input.
5563 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5564 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5565 TLI.getPointerTy()));
5566 AsmNodeOperands.push_back(InOperandVal);
5570 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5571 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5572 "Unknown constraint type!");
5573 assert(!OpInfo.isIndirect &&
5574 "Don't know how to handle indirect register inputs yet!");
5576 // Copy the input into the appropriate registers.
5577 if (OpInfo.AssignedRegs.Regs.empty() ||
5578 !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
5579 report_fatal_error("Couldn't allocate input reg for constraint '" +
5580 Twine(OpInfo.ConstraintCode) + "'!");
5582 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5585 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5586 DAG, AsmNodeOperands);
5589 case InlineAsm::isClobber: {
5590 // Add the clobbered value to the operand list, so that the register
5591 // allocator is aware that the physreg got clobbered.
5592 if (!OpInfo.AssignedRegs.Regs.empty())
5593 OpInfo.AssignedRegs.AddInlineAsmOperands(
5594 InlineAsm::Kind_RegDefEarlyClobber,
5602 // Finish up input operands. Set the input chain and add the flag last.
5603 AsmNodeOperands[0] = Chain;
5604 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5606 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5607 DAG.getVTList(MVT::Other, MVT::Flag),
5608 &AsmNodeOperands[0], AsmNodeOperands.size());
5609 Flag = Chain.getValue(1);
5611 // If this asm returns a register value, copy the result from that register
5612 // and set it as the value of the call.
5613 if (!RetValRegs.Regs.empty()) {
5614 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5617 // FIXME: Why don't we do this for inline asms with MRVs?
5618 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5619 EVT ResultType = TLI.getValueType(CS.getType());
5621 // If any of the results of the inline asm is a vector, it may have the
5622 // wrong width/num elts. This can happen for register classes that can
5623 // contain multiple different value types. The preg or vreg allocated may
5624 // not have the same VT as was expected. Convert it to the right type
5625 // with bit_convert.
5626 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5627 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5630 } else if (ResultType != Val.getValueType() &&
5631 ResultType.isInteger() && Val.getValueType().isInteger()) {
5632 // If a result value was tied to an input value, the computed result may
5633 // have a wider width than the expected result. Extract the relevant
5635 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5638 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5641 setValue(CS.getInstruction(), Val);
5642 // Don't need to use this as a chain in this case.
5643 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5647 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
5649 // Process indirect outputs, first output all of the flagged copies out of
5651 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5652 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5653 const Value *Ptr = IndirectStoresToEmit[i].second;
5654 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5656 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5659 // Emit the non-flagged stores from the physregs.
5660 SmallVector<SDValue, 8> OutChains;
5661 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5662 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5663 StoresToEmit[i].first,
5664 getValue(StoresToEmit[i].second),
5665 StoresToEmit[i].second, 0,
5667 OutChains.push_back(Val);
5670 if (!OutChains.empty())
5671 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5672 &OutChains[0], OutChains.size());
5677 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
5678 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5679 MVT::Other, getRoot(),
5680 getValue(I.getArgOperand(0)),
5681 DAG.getSrcValue(I.getArgOperand(0))));
5684 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
5685 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5686 getRoot(), getValue(I.getOperand(0)),
5687 DAG.getSrcValue(I.getOperand(0)));
5689 DAG.setRoot(V.getValue(1));
5692 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
5693 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5694 MVT::Other, getRoot(),
5695 getValue(I.getArgOperand(0)),
5696 DAG.getSrcValue(I.getArgOperand(0))));
5699 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
5700 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5701 MVT::Other, getRoot(),
5702 getValue(I.getArgOperand(0)),
5703 getValue(I.getArgOperand(1)),
5704 DAG.getSrcValue(I.getArgOperand(0)),
5705 DAG.getSrcValue(I.getArgOperand(1))));
5708 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5709 /// implementation, which just calls LowerCall.
5710 /// FIXME: When all targets are
5711 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5712 std::pair<SDValue, SDValue>
5713 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5714 bool RetSExt, bool RetZExt, bool isVarArg,
5715 bool isInreg, unsigned NumFixedArgs,
5716 CallingConv::ID CallConv, bool isTailCall,
5717 bool isReturnValueUsed,
5719 ArgListTy &Args, SelectionDAG &DAG,
5720 DebugLoc dl) const {
5721 // Handle all of the outgoing arguments.
5722 SmallVector<ISD::OutputArg, 32> Outs;
5723 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5724 SmallVector<EVT, 4> ValueVTs;
5725 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5726 for (unsigned Value = 0, NumValues = ValueVTs.size();
5727 Value != NumValues; ++Value) {
5728 EVT VT = ValueVTs[Value];
5729 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5730 SDValue Op = SDValue(Args[i].Node.getNode(),
5731 Args[i].Node.getResNo() + Value);
5732 ISD::ArgFlagsTy Flags;
5733 unsigned OriginalAlignment =
5734 getTargetData()->getABITypeAlignment(ArgTy);
5740 if (Args[i].isInReg)
5744 if (Args[i].isByVal) {
5746 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5747 const Type *ElementTy = Ty->getElementType();
5748 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5749 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5750 // For ByVal, alignment should come from FE. BE will guess if this
5751 // info is not there but there are cases it cannot get right.
5752 if (Args[i].Alignment)
5753 FrameAlign = Args[i].Alignment;
5754 Flags.setByValAlign(FrameAlign);
5755 Flags.setByValSize(FrameSize);
5759 Flags.setOrigAlign(OriginalAlignment);
5761 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5762 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5763 SmallVector<SDValue, 4> Parts(NumParts);
5764 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5767 ExtendKind = ISD::SIGN_EXTEND;
5768 else if (Args[i].isZExt)
5769 ExtendKind = ISD::ZERO_EXTEND;
5771 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
5772 PartVT, ExtendKind);
5774 for (unsigned j = 0; j != NumParts; ++j) {
5775 // if it isn't first piece, alignment must be 1
5776 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5777 if (NumParts > 1 && j == 0)
5778 MyFlags.Flags.setSplit();
5780 MyFlags.Flags.setOrigAlign(1);
5782 Outs.push_back(MyFlags);
5787 // Handle the incoming return values from the call.
5788 SmallVector<ISD::InputArg, 32> Ins;
5789 SmallVector<EVT, 4> RetTys;
5790 ComputeValueVTs(*this, RetTy, RetTys);
5791 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5793 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5794 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5795 for (unsigned i = 0; i != NumRegs; ++i) {
5796 ISD::InputArg MyFlags;
5797 MyFlags.VT = RegisterVT;
5798 MyFlags.Used = isReturnValueUsed;
5800 MyFlags.Flags.setSExt();
5802 MyFlags.Flags.setZExt();
5804 MyFlags.Flags.setInReg();
5805 Ins.push_back(MyFlags);
5809 SmallVector<SDValue, 4> InVals;
5810 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5811 Outs, Ins, dl, DAG, InVals);
5813 // Verify that the target's LowerCall behaved as expected.
5814 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5815 "LowerCall didn't return a valid chain!");
5816 assert((!isTailCall || InVals.empty()) &&
5817 "LowerCall emitted a return value for a tail call!");
5818 assert((isTailCall || InVals.size() == Ins.size()) &&
5819 "LowerCall didn't emit the correct number of values!");
5821 // For a tail call, the return value is merely live-out and there aren't
5822 // any nodes in the DAG representing it. Return a special value to
5823 // indicate that a tail call has been emitted and no more Instructions
5824 // should be processed in the current block.
5827 return std::make_pair(SDValue(), SDValue());
5830 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5831 assert(InVals[i].getNode() &&
5832 "LowerCall emitted a null value!");
5833 assert(Ins[i].VT == InVals[i].getValueType() &&
5834 "LowerCall emitted a value with the wrong type!");
5837 // Collect the legal value parts into potentially illegal values
5838 // that correspond to the original function's return values.
5839 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5841 AssertOp = ISD::AssertSext;
5843 AssertOp = ISD::AssertZext;
5844 SmallVector<SDValue, 4> ReturnValues;
5845 unsigned CurReg = 0;
5846 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5848 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5849 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5851 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
5852 NumRegs, RegisterVT, VT,
5857 // For a function returning void, there is no return value. We can't create
5858 // such a node, so we just return a null return value in that case. In
5859 // that case, nothing will actualy look at the value.
5860 if (ReturnValues.empty())
5861 return std::make_pair(SDValue(), Chain);
5863 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5864 DAG.getVTList(&RetTys[0], RetTys.size()),
5865 &ReturnValues[0], ReturnValues.size());
5866 return std::make_pair(Res, Chain);
5869 void TargetLowering::LowerOperationWrapper(SDNode *N,
5870 SmallVectorImpl<SDValue> &Results,
5871 SelectionDAG &DAG) const {
5872 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5874 Results.push_back(Res);
5877 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5878 llvm_unreachable("LowerOperation not implemented for this target!");
5883 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
5884 SDValue Op = getValue(V);
5885 assert((Op.getOpcode() != ISD::CopyFromReg ||
5886 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5887 "Copy from a reg to the same reg!");
5888 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5890 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5891 SDValue Chain = DAG.getEntryNode();
5892 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5893 PendingExports.push_back(Chain);
5896 #include "llvm/CodeGen/SelectionDAGISel.h"
5898 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
5899 // If this is the entry block, emit arguments.
5900 const Function &F = *LLVMBB->getParent();
5901 SelectionDAG &DAG = SDB->DAG;
5902 DebugLoc dl = SDB->getCurDebugLoc();
5903 const TargetData *TD = TLI.getTargetData();
5904 SmallVector<ISD::InputArg, 16> Ins;
5906 // Check whether the function can return without sret-demotion.
5907 SmallVector<EVT, 4> OutVTs;
5908 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5909 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5910 OutVTs, OutsFlags, TLI);
5912 FuncInfo->CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(),
5914 OutVTs, OutsFlags, DAG);
5915 if (!FuncInfo->CanLowerReturn) {
5916 // Put in an sret pointer parameter before all the other parameters.
5917 SmallVector<EVT, 1> ValueVTs;
5918 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5920 // NOTE: Assuming that a pointer will never break down to more than one VT
5922 ISD::ArgFlagsTy Flags;
5924 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
5925 ISD::InputArg RetArg(Flags, RegisterVT, true);
5926 Ins.push_back(RetArg);
5929 // Set up the incoming argument description vector.
5931 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
5932 I != E; ++I, ++Idx) {
5933 SmallVector<EVT, 4> ValueVTs;
5934 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5935 bool isArgValueUsed = !I->use_empty();
5936 for (unsigned Value = 0, NumValues = ValueVTs.size();
5937 Value != NumValues; ++Value) {
5938 EVT VT = ValueVTs[Value];
5939 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5940 ISD::ArgFlagsTy Flags;
5941 unsigned OriginalAlignment =
5942 TD->getABITypeAlignment(ArgTy);
5944 if (F.paramHasAttr(Idx, Attribute::ZExt))
5946 if (F.paramHasAttr(Idx, Attribute::SExt))
5948 if (F.paramHasAttr(Idx, Attribute::InReg))
5950 if (F.paramHasAttr(Idx, Attribute::StructRet))
5952 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5954 const PointerType *Ty = cast<PointerType>(I->getType());
5955 const Type *ElementTy = Ty->getElementType();
5956 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5957 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5958 // For ByVal, alignment should be passed from FE. BE will guess if
5959 // this info is not there but there are cases it cannot get right.
5960 if (F.getParamAlignment(Idx))
5961 FrameAlign = F.getParamAlignment(Idx);
5962 Flags.setByValAlign(FrameAlign);
5963 Flags.setByValSize(FrameSize);
5965 if (F.paramHasAttr(Idx, Attribute::Nest))
5967 Flags.setOrigAlign(OriginalAlignment);
5969 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5970 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5971 for (unsigned i = 0; i != NumRegs; ++i) {
5972 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5973 if (NumRegs > 1 && i == 0)
5974 MyFlags.Flags.setSplit();
5975 // if it isn't first piece, alignment must be 1
5977 MyFlags.Flags.setOrigAlign(1);
5978 Ins.push_back(MyFlags);
5983 // Call the target to set up the argument values.
5984 SmallVector<SDValue, 8> InVals;
5985 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5989 // Verify that the target's LowerFormalArguments behaved as expected.
5990 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5991 "LowerFormalArguments didn't return a valid chain!");
5992 assert(InVals.size() == Ins.size() &&
5993 "LowerFormalArguments didn't emit the correct number of values!");
5995 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5996 assert(InVals[i].getNode() &&
5997 "LowerFormalArguments emitted a null value!");
5998 assert(Ins[i].VT == InVals[i].getValueType() &&
5999 "LowerFormalArguments emitted a value with the wrong type!");
6003 // Update the DAG with the new chain value resulting from argument lowering.
6004 DAG.setRoot(NewRoot);
6006 // Set up the argument values.
6009 if (!FuncInfo->CanLowerReturn) {
6010 // Create a virtual register for the sret pointer, and put in a copy
6011 // from the sret argument into it.
6012 SmallVector<EVT, 1> ValueVTs;
6013 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6014 EVT VT = ValueVTs[0];
6015 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6016 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6017 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6018 RegVT, VT, AssertOp);
6020 MachineFunction& MF = SDB->DAG.getMachineFunction();
6021 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6022 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6023 FuncInfo->DemoteRegister = SRetReg;
6024 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6026 DAG.setRoot(NewRoot);
6028 // i indexes lowered arguments. Bump it past the hidden sret argument.
6029 // Idx indexes LLVM arguments. Don't touch it.
6033 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6035 SmallVector<SDValue, 4> ArgValues;
6036 SmallVector<EVT, 4> ValueVTs;
6037 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6038 unsigned NumValues = ValueVTs.size();
6040 // If this argument is unused then remember its value. It is used to generate
6041 // debugging information.
6042 if (I->use_empty() && NumValues)
6043 SDB->setUnusedArgValue(I, InVals[i]);
6045 for (unsigned Value = 0; Value != NumValues; ++Value) {
6046 EVT VT = ValueVTs[Value];
6047 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6048 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6050 if (!I->use_empty()) {
6051 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6052 if (F.paramHasAttr(Idx, Attribute::SExt))
6053 AssertOp = ISD::AssertSext;
6054 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6055 AssertOp = ISD::AssertZext;
6057 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6058 NumParts, PartVT, VT,
6065 if (!I->use_empty()) {
6067 if (!ArgValues.empty())
6068 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6069 SDB->getCurDebugLoc());
6070 SDB->setValue(I, Res);
6072 // If this argument is live outside of the entry block, insert a copy from
6073 // whereever we got it to the vreg that other BB's will reference it as.
6074 SDB->CopyToExportRegsIfNeeded(I);
6078 assert(i == InVals.size() && "Argument register count mismatch!");
6080 // Finally, if the target has anything special to do, allow it to do so.
6081 // FIXME: this should insert code into the DAG!
6082 EmitFunctionEntryCode();
6085 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6086 /// ensure constants are generated when needed. Remember the virtual registers
6087 /// that need to be added to the Machine PHI nodes as input. We cannot just
6088 /// directly add them, because expansion might result in multiple MBB's for one
6089 /// BB. As such, the start of the BB might correspond to a different MBB than
6093 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6094 const TerminatorInst *TI = LLVMBB->getTerminator();
6096 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6098 // Check successor nodes' PHI nodes that expect a constant to be available
6100 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6101 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6102 if (!isa<PHINode>(SuccBB->begin())) continue;
6103 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6105 // If this terminator has multiple identical successors (common for
6106 // switches), only handle each succ once.
6107 if (!SuccsHandled.insert(SuccMBB)) continue;
6109 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6111 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6112 // nodes and Machine PHI nodes, but the incoming operands have not been
6114 for (BasicBlock::const_iterator I = SuccBB->begin();
6115 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6116 // Ignore dead phi's.
6117 if (PN->use_empty()) continue;
6120 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6122 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6123 unsigned &RegOut = ConstantsOut[C];
6125 RegOut = FuncInfo.CreateRegForValue(C);
6126 CopyValueToVirtualRegister(C, RegOut);
6130 Reg = FuncInfo.ValueMap[PHIOp];
6132 assert(isa<AllocaInst>(PHIOp) &&
6133 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6134 "Didn't codegen value into a register!??");
6135 Reg = FuncInfo.CreateRegForValue(PHIOp);
6136 CopyValueToVirtualRegister(PHIOp, Reg);
6140 // Remember that this register needs to added to the machine PHI node as
6141 // the input for this MBB.
6142 SmallVector<EVT, 4> ValueVTs;
6143 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6144 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6145 EVT VT = ValueVTs[vti];
6146 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6147 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6148 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6149 Reg += NumRegisters;
6153 ConstantsOut.clear();