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 // getValue - Return an SDValue for the given Value.
809 SDValue SelectionDAGBuilder::getValue(const Value *V) {
810 // If we already have an SDValue for this value, use it. It's important
811 // to do this first, so that we don't create a CopyFromReg if we already
812 // have a regular SDValue.
813 SDValue &N = NodeMap[V];
814 if (N.getNode()) return N;
816 // If there's a virtual register allocated and initialized for this
818 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
819 if (It != FuncInfo.ValueMap.end()) {
820 unsigned InReg = It->second;
821 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
822 SDValue Chain = DAG.getEntryNode();
823 return N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
826 // Otherwise create a new SDValue and remember it.
827 SDValue Val = getValueImpl(V);
832 /// getNonRegisterValue - Return an SDValue for the given Value, but
833 /// don't look in FuncInfo.ValueMap for a virtual register.
834 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
835 // If we already have an SDValue for this value, use it.
836 SDValue &N = NodeMap[V];
837 if (N.getNode()) return N;
839 // Otherwise create a new SDValue and remember it.
840 SDValue Val = getValueImpl(V);
845 /// getValueImpl - Helper function for getValue and getMaterializedValue.
846 /// Create an SDValue for the given value.
847 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
848 if (const Constant *C = dyn_cast<Constant>(V)) {
849 EVT VT = TLI.getValueType(V->getType(), true);
851 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
852 return DAG.getConstant(*CI, VT);
854 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
855 return DAG.getGlobalAddress(GV, VT);
857 if (isa<ConstantPointerNull>(C))
858 return DAG.getConstant(0, TLI.getPointerTy());
860 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
861 return DAG.getConstantFP(*CFP, VT);
863 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
864 return DAG.getUNDEF(VT);
866 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
867 visit(CE->getOpcode(), *CE);
868 SDValue N1 = NodeMap[V];
869 assert(N1.getNode() && "visit didn't populate the NodeMap!");
873 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
874 SmallVector<SDValue, 4> Constants;
875 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
877 SDNode *Val = getValue(*OI).getNode();
878 // If the operand is an empty aggregate, there are no values.
880 // Add each leaf value from the operand to the Constants list
881 // to form a flattened list of all the values.
882 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
883 Constants.push_back(SDValue(Val, i));
886 return DAG.getMergeValues(&Constants[0], Constants.size(),
890 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
891 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
892 "Unknown struct or array constant!");
894 SmallVector<EVT, 4> ValueVTs;
895 ComputeValueVTs(TLI, C->getType(), ValueVTs);
896 unsigned NumElts = ValueVTs.size();
898 return SDValue(); // empty struct
899 SmallVector<SDValue, 4> Constants(NumElts);
900 for (unsigned i = 0; i != NumElts; ++i) {
901 EVT EltVT = ValueVTs[i];
902 if (isa<UndefValue>(C))
903 Constants[i] = DAG.getUNDEF(EltVT);
904 else if (EltVT.isFloatingPoint())
905 Constants[i] = DAG.getConstantFP(0, EltVT);
907 Constants[i] = DAG.getConstant(0, EltVT);
910 return DAG.getMergeValues(&Constants[0], NumElts,
914 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
915 return DAG.getBlockAddress(BA, VT);
917 const VectorType *VecTy = cast<VectorType>(V->getType());
918 unsigned NumElements = VecTy->getNumElements();
920 // Now that we know the number and type of the elements, get that number of
921 // elements into the Ops array based on what kind of constant it is.
922 SmallVector<SDValue, 16> Ops;
923 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
924 for (unsigned i = 0; i != NumElements; ++i)
925 Ops.push_back(getValue(CP->getOperand(i)));
927 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
928 EVT EltVT = TLI.getValueType(VecTy->getElementType());
931 if (EltVT.isFloatingPoint())
932 Op = DAG.getConstantFP(0, EltVT);
934 Op = DAG.getConstant(0, EltVT);
935 Ops.assign(NumElements, Op);
938 // Create a BUILD_VECTOR node.
939 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
940 VT, &Ops[0], Ops.size());
943 // If this is a static alloca, generate it as the frameindex instead of
945 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
946 DenseMap<const AllocaInst*, int>::iterator SI =
947 FuncInfo.StaticAllocaMap.find(AI);
948 if (SI != FuncInfo.StaticAllocaMap.end())
949 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
952 // If this is an instruction which fast-isel has deferred, select it now.
953 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
954 assert(Inst->isSafeToSpeculativelyExecute() &&
955 "Instruction with side effects deferred!");
957 DenseMap<const Value *, SDValue>::iterator NIt = NodeMap.find(Inst);
958 if (NIt != NodeMap.end() && NIt->second.getNode())
962 llvm_unreachable("Can't get register for value!");
966 /// Get the EVTs and ArgFlags collections that represent the legalized return
967 /// type of the given function. This does not require a DAG or a return value,
968 /// and is suitable for use before any DAGs for the function are constructed.
969 static void getReturnInfo(const Type* ReturnType,
970 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
971 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
972 const TargetLowering &TLI,
973 SmallVectorImpl<uint64_t> *Offsets = 0) {
974 SmallVector<EVT, 4> ValueVTs;
975 ComputeValueVTs(TLI, ReturnType, ValueVTs);
976 unsigned NumValues = ValueVTs.size();
977 if (NumValues == 0) return;
980 for (unsigned j = 0, f = NumValues; j != f; ++j) {
981 EVT VT = ValueVTs[j];
982 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
984 if (attr & Attribute::SExt)
985 ExtendKind = ISD::SIGN_EXTEND;
986 else if (attr & Attribute::ZExt)
987 ExtendKind = ISD::ZERO_EXTEND;
989 // FIXME: C calling convention requires the return type to be promoted to
990 // at least 32-bit. But this is not necessary for non-C calling
991 // conventions. The frontend should mark functions whose return values
992 // require promoting with signext or zeroext attributes.
993 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
994 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
995 if (VT.bitsLT(MinVT))
999 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
1000 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
1001 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
1002 PartVT.getTypeForEVT(ReturnType->getContext()));
1004 // 'inreg' on function refers to return value
1005 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1006 if (attr & Attribute::InReg)
1009 // Propagate extension type if any
1010 if (attr & Attribute::SExt)
1012 else if (attr & Attribute::ZExt)
1015 for (unsigned i = 0; i < NumParts; ++i) {
1016 OutVTs.push_back(PartVT);
1017 OutFlags.push_back(Flags);
1020 Offsets->push_back(Offset);
1027 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1028 SDValue Chain = getControlRoot();
1029 SmallVector<ISD::OutputArg, 8> Outs;
1031 if (!FuncInfo.CanLowerReturn) {
1032 unsigned DemoteReg = FuncInfo.DemoteRegister;
1033 const Function *F = I.getParent()->getParent();
1035 // Emit a store of the return value through the virtual register.
1036 // Leave Outs empty so that LowerReturn won't try to load return
1037 // registers the usual way.
1038 SmallVector<EVT, 1> PtrValueVTs;
1039 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1042 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1043 SDValue RetOp = getValue(I.getOperand(0));
1045 SmallVector<EVT, 4> ValueVTs;
1046 SmallVector<uint64_t, 4> Offsets;
1047 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1048 unsigned NumValues = ValueVTs.size();
1050 SmallVector<SDValue, 4> Chains(NumValues);
1051 EVT PtrVT = PtrValueVTs[0];
1052 for (unsigned i = 0; i != NumValues; ++i) {
1053 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
1054 DAG.getConstant(Offsets[i], PtrVT));
1056 DAG.getStore(Chain, getCurDebugLoc(),
1057 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1058 Add, NULL, Offsets[i], false, false, 0);
1061 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1062 MVT::Other, &Chains[0], NumValues);
1063 } else if (I.getNumOperands() != 0) {
1064 SmallVector<EVT, 4> ValueVTs;
1065 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1066 unsigned NumValues = ValueVTs.size();
1068 SDValue RetOp = getValue(I.getOperand(0));
1069 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1070 EVT VT = ValueVTs[j];
1072 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1074 const Function *F = I.getParent()->getParent();
1075 if (F->paramHasAttr(0, Attribute::SExt))
1076 ExtendKind = ISD::SIGN_EXTEND;
1077 else if (F->paramHasAttr(0, Attribute::ZExt))
1078 ExtendKind = ISD::ZERO_EXTEND;
1080 // FIXME: C calling convention requires the return type to be promoted
1081 // to at least 32-bit. But this is not necessary for non-C calling
1082 // conventions. The frontend should mark functions whose return values
1083 // require promoting with signext or zeroext attributes.
1084 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1085 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
1086 if (VT.bitsLT(MinVT))
1090 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1091 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1092 SmallVector<SDValue, 4> Parts(NumParts);
1093 getCopyToParts(DAG, getCurDebugLoc(),
1094 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1095 &Parts[0], NumParts, PartVT, ExtendKind);
1097 // 'inreg' on function refers to return value
1098 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1099 if (F->paramHasAttr(0, Attribute::InReg))
1102 // Propagate extension type if any
1103 if (F->paramHasAttr(0, Attribute::SExt))
1105 else if (F->paramHasAttr(0, Attribute::ZExt))
1108 for (unsigned i = 0; i < NumParts; ++i)
1109 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
1114 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1115 CallingConv::ID CallConv =
1116 DAG.getMachineFunction().getFunction()->getCallingConv();
1117 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1118 Outs, getCurDebugLoc(), DAG);
1120 // Verify that the target's LowerReturn behaved as expected.
1121 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1122 "LowerReturn didn't return a valid chain!");
1124 // Update the DAG with the new chain value resulting from return lowering.
1128 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1129 /// created for it, emit nodes to copy the value into the virtual
1131 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1132 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1133 if (VMI != FuncInfo.ValueMap.end()) {
1134 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1135 CopyValueToVirtualRegister(V, VMI->second);
1139 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1140 /// the current basic block, add it to ValueMap now so that we'll get a
1142 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1143 // No need to export constants.
1144 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1146 // Already exported?
1147 if (FuncInfo.isExportedInst(V)) return;
1149 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1150 CopyValueToVirtualRegister(V, Reg);
1153 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1154 const BasicBlock *FromBB) {
1155 // The operands of the setcc have to be in this block. We don't know
1156 // how to export them from some other block.
1157 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1158 // Can export from current BB.
1159 if (VI->getParent() == FromBB)
1162 // Is already exported, noop.
1163 return FuncInfo.isExportedInst(V);
1166 // If this is an argument, we can export it if the BB is the entry block or
1167 // if it is already exported.
1168 if (isa<Argument>(V)) {
1169 if (FromBB == &FromBB->getParent()->getEntryBlock())
1172 // Otherwise, can only export this if it is already exported.
1173 return FuncInfo.isExportedInst(V);
1176 // Otherwise, constants can always be exported.
1180 static bool InBlock(const Value *V, const BasicBlock *BB) {
1181 if (const Instruction *I = dyn_cast<Instruction>(V))
1182 return I->getParent() == BB;
1186 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1187 /// This function emits a branch and is used at the leaves of an OR or an
1188 /// AND operator tree.
1191 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1192 MachineBasicBlock *TBB,
1193 MachineBasicBlock *FBB,
1194 MachineBasicBlock *CurBB,
1195 MachineBasicBlock *SwitchBB) {
1196 const BasicBlock *BB = CurBB->getBasicBlock();
1198 // If the leaf of the tree is a comparison, merge the condition into
1200 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1201 // The operands of the cmp have to be in this block. We don't know
1202 // how to export them from some other block. If this is the first block
1203 // of the sequence, no exporting is needed.
1204 if (CurBB == SwitchBB ||
1205 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1206 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1207 ISD::CondCode Condition;
1208 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1209 Condition = getICmpCondCode(IC->getPredicate());
1210 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1211 Condition = getFCmpCondCode(FC->getPredicate());
1213 Condition = ISD::SETEQ; // silence warning.
1214 llvm_unreachable("Unknown compare instruction");
1217 CaseBlock CB(Condition, BOp->getOperand(0),
1218 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1219 SwitchCases.push_back(CB);
1224 // Create a CaseBlock record representing this branch.
1225 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1226 NULL, TBB, FBB, CurBB);
1227 SwitchCases.push_back(CB);
1230 /// FindMergedConditions - If Cond is an expression like
1231 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1232 MachineBasicBlock *TBB,
1233 MachineBasicBlock *FBB,
1234 MachineBasicBlock *CurBB,
1235 MachineBasicBlock *SwitchBB,
1237 // If this node is not part of the or/and tree, emit it as a branch.
1238 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1239 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1240 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1241 BOp->getParent() != CurBB->getBasicBlock() ||
1242 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1243 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1244 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1248 // Create TmpBB after CurBB.
1249 MachineFunction::iterator BBI = CurBB;
1250 MachineFunction &MF = DAG.getMachineFunction();
1251 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1252 CurBB->getParent()->insert(++BBI, TmpBB);
1254 if (Opc == Instruction::Or) {
1255 // Codegen X | Y as:
1263 // Emit the LHS condition.
1264 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1266 // Emit the RHS condition into TmpBB.
1267 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1269 assert(Opc == Instruction::And && "Unknown merge op!");
1270 // Codegen X & Y as:
1277 // This requires creation of TmpBB after CurBB.
1279 // Emit the LHS condition.
1280 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1282 // Emit the RHS condition into TmpBB.
1283 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1287 /// If the set of cases should be emitted as a series of branches, return true.
1288 /// If we should emit this as a bunch of and/or'd together conditions, return
1291 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1292 if (Cases.size() != 2) return true;
1294 // If this is two comparisons of the same values or'd or and'd together, they
1295 // will get folded into a single comparison, so don't emit two blocks.
1296 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1297 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1298 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1299 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1303 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1304 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1305 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1306 Cases[0].CC == Cases[1].CC &&
1307 isa<Constant>(Cases[0].CmpRHS) &&
1308 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1309 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1311 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1318 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1319 MachineBasicBlock *BrMBB = FuncInfo.MBBMap[I.getParent()];
1321 // Update machine-CFG edges.
1322 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1324 // Figure out which block is immediately after the current one.
1325 MachineBasicBlock *NextBlock = 0;
1326 MachineFunction::iterator BBI = BrMBB;
1327 if (++BBI != FuncInfo.MF->end())
1330 if (I.isUnconditional()) {
1331 // Update machine-CFG edges.
1332 BrMBB->addSuccessor(Succ0MBB);
1334 // If this is not a fall-through branch, emit the branch.
1335 if (Succ0MBB != NextBlock)
1336 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1337 MVT::Other, getControlRoot(),
1338 DAG.getBasicBlock(Succ0MBB)));
1343 // If this condition is one of the special cases we handle, do special stuff
1345 const Value *CondVal = I.getCondition();
1346 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1348 // If this is a series of conditions that are or'd or and'd together, emit
1349 // this as a sequence of branches instead of setcc's with and/or operations.
1350 // For example, instead of something like:
1363 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1364 if (BOp->hasOneUse() &&
1365 (BOp->getOpcode() == Instruction::And ||
1366 BOp->getOpcode() == Instruction::Or)) {
1367 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1369 // If the compares in later blocks need to use values not currently
1370 // exported from this block, export them now. This block should always
1371 // be the first entry.
1372 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1374 // Allow some cases to be rejected.
1375 if (ShouldEmitAsBranches(SwitchCases)) {
1376 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1377 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1378 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1381 // Emit the branch for this block.
1382 visitSwitchCase(SwitchCases[0], BrMBB);
1383 SwitchCases.erase(SwitchCases.begin());
1387 // Okay, we decided not to do this, remove any inserted MBB's and clear
1389 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1390 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1392 SwitchCases.clear();
1396 // Create a CaseBlock record representing this branch.
1397 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1398 NULL, Succ0MBB, Succ1MBB, BrMBB);
1400 // Use visitSwitchCase to actually insert the fast branch sequence for this
1402 visitSwitchCase(CB, BrMBB);
1405 /// visitSwitchCase - Emits the necessary code to represent a single node in
1406 /// the binary search tree resulting from lowering a switch instruction.
1407 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1408 MachineBasicBlock *SwitchBB) {
1410 SDValue CondLHS = getValue(CB.CmpLHS);
1411 DebugLoc dl = getCurDebugLoc();
1413 // Build the setcc now.
1414 if (CB.CmpMHS == NULL) {
1415 // Fold "(X == true)" to X and "(X == false)" to !X to
1416 // handle common cases produced by branch lowering.
1417 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1418 CB.CC == ISD::SETEQ)
1420 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1421 CB.CC == ISD::SETEQ) {
1422 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1423 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1425 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1427 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1429 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1430 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1432 SDValue CmpOp = getValue(CB.CmpMHS);
1433 EVT VT = CmpOp.getValueType();
1435 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1436 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1439 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1440 VT, CmpOp, DAG.getConstant(Low, VT));
1441 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1442 DAG.getConstant(High-Low, VT), ISD::SETULE);
1446 // Update successor info
1447 SwitchBB->addSuccessor(CB.TrueBB);
1448 SwitchBB->addSuccessor(CB.FalseBB);
1450 // Set NextBlock to be the MBB immediately after the current one, if any.
1451 // This is used to avoid emitting unnecessary branches to the next block.
1452 MachineBasicBlock *NextBlock = 0;
1453 MachineFunction::iterator BBI = SwitchBB;
1454 if (++BBI != FuncInfo.MF->end())
1457 // If the lhs block is the next block, invert the condition so that we can
1458 // fall through to the lhs instead of the rhs block.
1459 if (CB.TrueBB == NextBlock) {
1460 std::swap(CB.TrueBB, CB.FalseBB);
1461 SDValue True = DAG.getConstant(1, Cond.getValueType());
1462 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1465 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1466 MVT::Other, getControlRoot(), Cond,
1467 DAG.getBasicBlock(CB.TrueBB));
1469 // Insert the false branch.
1470 if (CB.FalseBB != NextBlock)
1471 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1472 DAG.getBasicBlock(CB.FalseBB));
1474 DAG.setRoot(BrCond);
1477 /// visitJumpTable - Emit JumpTable node in the current MBB
1478 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1479 // Emit the code for the jump table
1480 assert(JT.Reg != -1U && "Should lower JT Header first!");
1481 EVT PTy = TLI.getPointerTy();
1482 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1484 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1485 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1486 MVT::Other, Index.getValue(1),
1488 DAG.setRoot(BrJumpTable);
1491 /// visitJumpTableHeader - This function emits necessary code to produce index
1492 /// in the JumpTable from switch case.
1493 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1494 JumpTableHeader &JTH,
1495 MachineBasicBlock *SwitchBB) {
1496 // Subtract the lowest switch case value from the value being switched on and
1497 // conditional branch to default mbb if the result is greater than the
1498 // difference between smallest and largest cases.
1499 SDValue SwitchOp = getValue(JTH.SValue);
1500 EVT VT = SwitchOp.getValueType();
1501 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1502 DAG.getConstant(JTH.First, VT));
1504 // The SDNode we just created, which holds the value being switched on minus
1505 // the smallest case value, needs to be copied to a virtual register so it
1506 // can be used as an index into the jump table in a subsequent basic block.
1507 // This value may be smaller or larger than the target's pointer type, and
1508 // therefore require extension or truncating.
1509 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1511 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1512 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1513 JumpTableReg, SwitchOp);
1514 JT.Reg = JumpTableReg;
1516 // Emit the range check for the jump table, and branch to the default block
1517 // for the switch statement if the value being switched on exceeds the largest
1518 // case in the switch.
1519 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1520 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1521 DAG.getConstant(JTH.Last-JTH.First,VT),
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;
1529 if (++BBI != FuncInfo.MF->end())
1532 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1533 MVT::Other, CopyTo, CMP,
1534 DAG.getBasicBlock(JT.Default));
1536 if (JT.MBB != NextBlock)
1537 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1538 DAG.getBasicBlock(JT.MBB));
1540 DAG.setRoot(BrCond);
1543 /// visitBitTestHeader - This function emits necessary code to produce value
1544 /// suitable for "bit tests"
1545 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1546 MachineBasicBlock *SwitchBB) {
1547 // Subtract the minimum value
1548 SDValue SwitchOp = getValue(B.SValue);
1549 EVT VT = SwitchOp.getValueType();
1550 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1551 DAG.getConstant(B.First, VT));
1554 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1555 TLI.getSetCCResultType(Sub.getValueType()),
1556 Sub, DAG.getConstant(B.Range, VT),
1559 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1560 TLI.getPointerTy());
1562 B.Reg = FuncInfo.CreateReg(TLI.getPointerTy());
1563 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1566 // Set NextBlock to be the MBB immediately after the current one, if any.
1567 // This is used to avoid emitting unnecessary branches to the next block.
1568 MachineBasicBlock *NextBlock = 0;
1569 MachineFunction::iterator BBI = SwitchBB;
1570 if (++BBI != FuncInfo.MF->end())
1573 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1575 SwitchBB->addSuccessor(B.Default);
1576 SwitchBB->addSuccessor(MBB);
1578 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1579 MVT::Other, CopyTo, RangeCmp,
1580 DAG.getBasicBlock(B.Default));
1582 if (MBB != NextBlock)
1583 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1584 DAG.getBasicBlock(MBB));
1586 DAG.setRoot(BrRange);
1589 /// visitBitTestCase - this function produces one "bit test"
1590 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1593 MachineBasicBlock *SwitchBB) {
1594 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1595 TLI.getPointerTy());
1597 if (CountPopulation_64(B.Mask) == 1) {
1598 // Testing for a single bit; just compare the shift count with what it
1599 // would need to be to shift a 1 bit in that position.
1600 Cmp = DAG.getSetCC(getCurDebugLoc(),
1601 TLI.getSetCCResultType(ShiftOp.getValueType()),
1603 DAG.getConstant(CountTrailingZeros_64(B.Mask),
1604 TLI.getPointerTy()),
1607 // Make desired shift
1608 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1610 DAG.getConstant(1, TLI.getPointerTy()),
1613 // Emit bit tests and jumps
1614 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1615 TLI.getPointerTy(), SwitchVal,
1616 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1617 Cmp = DAG.getSetCC(getCurDebugLoc(),
1618 TLI.getSetCCResultType(AndOp.getValueType()),
1619 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1623 SwitchBB->addSuccessor(B.TargetBB);
1624 SwitchBB->addSuccessor(NextMBB);
1626 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1627 MVT::Other, getControlRoot(),
1628 Cmp, DAG.getBasicBlock(B.TargetBB));
1630 // Set NextBlock to be the MBB immediately after the current one, if any.
1631 // This is used to avoid emitting unnecessary branches to the next block.
1632 MachineBasicBlock *NextBlock = 0;
1633 MachineFunction::iterator BBI = SwitchBB;
1634 if (++BBI != FuncInfo.MF->end())
1637 if (NextMBB != NextBlock)
1638 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1639 DAG.getBasicBlock(NextMBB));
1644 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1645 MachineBasicBlock *InvokeMBB = FuncInfo.MBBMap[I.getParent()];
1647 // Retrieve successors.
1648 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1649 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1651 const Value *Callee(I.getCalledValue());
1652 if (isa<InlineAsm>(Callee))
1655 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1657 // If the value of the invoke is used outside of its defining block, make it
1658 // available as a virtual register.
1659 CopyToExportRegsIfNeeded(&I);
1661 // Update successor info
1662 InvokeMBB->addSuccessor(Return);
1663 InvokeMBB->addSuccessor(LandingPad);
1665 // Drop into normal successor.
1666 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1667 MVT::Other, getControlRoot(),
1668 DAG.getBasicBlock(Return)));
1671 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1674 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1675 /// small case ranges).
1676 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1677 CaseRecVector& WorkList,
1679 MachineBasicBlock *Default,
1680 MachineBasicBlock *SwitchBB) {
1681 Case& BackCase = *(CR.Range.second-1);
1683 // Size is the number of Cases represented by this range.
1684 size_t Size = CR.Range.second - CR.Range.first;
1688 // Get the MachineFunction which holds the current MBB. This is used when
1689 // inserting any additional MBBs necessary to represent the switch.
1690 MachineFunction *CurMF = FuncInfo.MF;
1692 // Figure out which block is immediately after the current one.
1693 MachineBasicBlock *NextBlock = 0;
1694 MachineFunction::iterator BBI = CR.CaseBB;
1696 if (++BBI != FuncInfo.MF->end())
1699 // TODO: If any two of the cases has the same destination, and if one value
1700 // is the same as the other, but has one bit unset that the other has set,
1701 // use bit manipulation to do two compares at once. For example:
1702 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1704 // Rearrange the case blocks so that the last one falls through if possible.
1705 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1706 // The last case block won't fall through into 'NextBlock' if we emit the
1707 // branches in this order. See if rearranging a case value would help.
1708 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1709 if (I->BB == NextBlock) {
1710 std::swap(*I, BackCase);
1716 // Create a CaseBlock record representing a conditional branch to
1717 // the Case's target mbb if the value being switched on SV is equal
1719 MachineBasicBlock *CurBlock = CR.CaseBB;
1720 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1721 MachineBasicBlock *FallThrough;
1723 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1724 CurMF->insert(BBI, FallThrough);
1726 // Put SV in a virtual register to make it available from the new blocks.
1727 ExportFromCurrentBlock(SV);
1729 // If the last case doesn't match, go to the default block.
1730 FallThrough = Default;
1733 const Value *RHS, *LHS, *MHS;
1735 if (I->High == I->Low) {
1736 // This is just small small case range :) containing exactly 1 case
1738 LHS = SV; RHS = I->High; MHS = NULL;
1741 LHS = I->Low; MHS = SV; RHS = I->High;
1743 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1745 // If emitting the first comparison, just call visitSwitchCase to emit the
1746 // code into the current block. Otherwise, push the CaseBlock onto the
1747 // vector to be later processed by SDISel, and insert the node's MBB
1748 // before the next MBB.
1749 if (CurBlock == SwitchBB)
1750 visitSwitchCase(CB, SwitchBB);
1752 SwitchCases.push_back(CB);
1754 CurBlock = FallThrough;
1760 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1761 return !DisableJumpTables &&
1762 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1763 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1766 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1767 APInt LastExt(Last), FirstExt(First);
1768 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1769 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1770 return (LastExt - FirstExt + 1ULL);
1773 /// handleJTSwitchCase - Emit jumptable for current switch case range
1774 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1775 CaseRecVector& WorkList,
1777 MachineBasicBlock* Default,
1778 MachineBasicBlock *SwitchBB) {
1779 Case& FrontCase = *CR.Range.first;
1780 Case& BackCase = *(CR.Range.second-1);
1782 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1783 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1785 APInt TSize(First.getBitWidth(), 0);
1786 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1790 if (!areJTsAllowed(TLI) || TSize.ult(4))
1793 APInt Range = ComputeRange(First, Last);
1794 double Density = TSize.roundToDouble() / Range.roundToDouble();
1798 DEBUG(dbgs() << "Lowering jump table\n"
1799 << "First entry: " << First << ". Last entry: " << Last << '\n'
1800 << "Range: " << Range
1801 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1803 // Get the MachineFunction which holds the current MBB. This is used when
1804 // inserting any additional MBBs necessary to represent the switch.
1805 MachineFunction *CurMF = FuncInfo.MF;
1807 // Figure out which block is immediately after the current one.
1808 MachineFunction::iterator BBI = CR.CaseBB;
1811 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1813 // Create a new basic block to hold the code for loading the address
1814 // of the jump table, and jumping to it. Update successor information;
1815 // we will either branch to the default case for the switch, or the jump
1817 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1818 CurMF->insert(BBI, JumpTableBB);
1819 CR.CaseBB->addSuccessor(Default);
1820 CR.CaseBB->addSuccessor(JumpTableBB);
1822 // Build a vector of destination BBs, corresponding to each target
1823 // of the jump table. If the value of the jump table slot corresponds to
1824 // a case statement, push the case's BB onto the vector, otherwise, push
1826 std::vector<MachineBasicBlock*> DestBBs;
1828 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1829 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1830 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1832 if (Low.sle(TEI) && TEI.sle(High)) {
1833 DestBBs.push_back(I->BB);
1837 DestBBs.push_back(Default);
1841 // Update successor info. Add one edge to each unique successor.
1842 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1843 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1844 E = DestBBs.end(); I != E; ++I) {
1845 if (!SuccsHandled[(*I)->getNumber()]) {
1846 SuccsHandled[(*I)->getNumber()] = true;
1847 JumpTableBB->addSuccessor(*I);
1851 // Create a jump table index for this jump table.
1852 unsigned JTEncoding = TLI.getJumpTableEncoding();
1853 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1854 ->createJumpTableIndex(DestBBs);
1856 // Set the jump table information so that we can codegen it as a second
1857 // MachineBasicBlock
1858 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1859 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
1860 if (CR.CaseBB == SwitchBB)
1861 visitJumpTableHeader(JT, JTH, SwitchBB);
1863 JTCases.push_back(JumpTableBlock(JTH, JT));
1868 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1870 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1871 CaseRecVector& WorkList,
1873 MachineBasicBlock *Default,
1874 MachineBasicBlock *SwitchBB) {
1875 // Get the MachineFunction which holds the current MBB. This is used when
1876 // inserting any additional MBBs necessary to represent the switch.
1877 MachineFunction *CurMF = FuncInfo.MF;
1879 // Figure out which block is immediately after the current one.
1880 MachineFunction::iterator BBI = CR.CaseBB;
1883 Case& FrontCase = *CR.Range.first;
1884 Case& BackCase = *(CR.Range.second-1);
1885 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1887 // Size is the number of Cases represented by this range.
1888 unsigned Size = CR.Range.second - CR.Range.first;
1890 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1891 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1893 CaseItr Pivot = CR.Range.first + Size/2;
1895 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1896 // (heuristically) allow us to emit JumpTable's later.
1897 APInt TSize(First.getBitWidth(), 0);
1898 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1902 APInt LSize = FrontCase.size();
1903 APInt RSize = TSize-LSize;
1904 DEBUG(dbgs() << "Selecting best pivot: \n"
1905 << "First: " << First << ", Last: " << Last <<'\n'
1906 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1907 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1909 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1910 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1911 APInt Range = ComputeRange(LEnd, RBegin);
1912 assert((Range - 2ULL).isNonNegative() &&
1913 "Invalid case distance");
1914 double LDensity = (double)LSize.roundToDouble() /
1915 (LEnd - First + 1ULL).roundToDouble();
1916 double RDensity = (double)RSize.roundToDouble() /
1917 (Last - RBegin + 1ULL).roundToDouble();
1918 double Metric = Range.logBase2()*(LDensity+RDensity);
1919 // Should always split in some non-trivial place
1920 DEBUG(dbgs() <<"=>Step\n"
1921 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1922 << "LDensity: " << LDensity
1923 << ", RDensity: " << RDensity << '\n'
1924 << "Metric: " << Metric << '\n');
1925 if (FMetric < Metric) {
1928 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1934 if (areJTsAllowed(TLI)) {
1935 // If our case is dense we *really* should handle it earlier!
1936 assert((FMetric > 0) && "Should handle dense range earlier!");
1938 Pivot = CR.Range.first + Size/2;
1941 CaseRange LHSR(CR.Range.first, Pivot);
1942 CaseRange RHSR(Pivot, CR.Range.second);
1943 Constant *C = Pivot->Low;
1944 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1946 // We know that we branch to the LHS if the Value being switched on is
1947 // less than the Pivot value, C. We use this to optimize our binary
1948 // tree a bit, by recognizing that if SV is greater than or equal to the
1949 // LHS's Case Value, and that Case Value is exactly one less than the
1950 // Pivot's Value, then we can branch directly to the LHS's Target,
1951 // rather than creating a leaf node for it.
1952 if ((LHSR.second - LHSR.first) == 1 &&
1953 LHSR.first->High == CR.GE &&
1954 cast<ConstantInt>(C)->getValue() ==
1955 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1956 TrueBB = LHSR.first->BB;
1958 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1959 CurMF->insert(BBI, TrueBB);
1960 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1962 // Put SV in a virtual register to make it available from the new blocks.
1963 ExportFromCurrentBlock(SV);
1966 // Similar to the optimization above, if the Value being switched on is
1967 // known to be less than the Constant CR.LT, and the current Case Value
1968 // is CR.LT - 1, then we can branch directly to the target block for
1969 // the current Case Value, rather than emitting a RHS leaf node for it.
1970 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1971 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1972 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1973 FalseBB = RHSR.first->BB;
1975 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1976 CurMF->insert(BBI, FalseBB);
1977 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1979 // Put SV in a virtual register to make it available from the new blocks.
1980 ExportFromCurrentBlock(SV);
1983 // Create a CaseBlock record representing a conditional branch to
1984 // the LHS node if the value being switched on SV is less than C.
1985 // Otherwise, branch to LHS.
1986 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1988 if (CR.CaseBB == SwitchBB)
1989 visitSwitchCase(CB, SwitchBB);
1991 SwitchCases.push_back(CB);
1996 /// handleBitTestsSwitchCase - if current case range has few destination and
1997 /// range span less, than machine word bitwidth, encode case range into series
1998 /// of masks and emit bit tests with these masks.
1999 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2000 CaseRecVector& WorkList,
2002 MachineBasicBlock* Default,
2003 MachineBasicBlock *SwitchBB){
2004 EVT PTy = TLI.getPointerTy();
2005 unsigned IntPtrBits = PTy.getSizeInBits();
2007 Case& FrontCase = *CR.Range.first;
2008 Case& BackCase = *(CR.Range.second-1);
2010 // Get the MachineFunction which holds the current MBB. This is used when
2011 // inserting any additional MBBs necessary to represent the switch.
2012 MachineFunction *CurMF = FuncInfo.MF;
2014 // If target does not have legal shift left, do not emit bit tests at all.
2015 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2019 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2021 // Single case counts one, case range - two.
2022 numCmps += (I->Low == I->High ? 1 : 2);
2025 // Count unique destinations
2026 SmallSet<MachineBasicBlock*, 4> Dests;
2027 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2028 Dests.insert(I->BB);
2029 if (Dests.size() > 3)
2030 // Don't bother the code below, if there are too much unique destinations
2033 DEBUG(dbgs() << "Total number of unique destinations: "
2034 << Dests.size() << '\n'
2035 << "Total number of comparisons: " << numCmps << '\n');
2037 // Compute span of values.
2038 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2039 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2040 APInt cmpRange = maxValue - minValue;
2042 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2043 << "Low bound: " << minValue << '\n'
2044 << "High bound: " << maxValue << '\n');
2046 if (cmpRange.uge(IntPtrBits) ||
2047 (!(Dests.size() == 1 && numCmps >= 3) &&
2048 !(Dests.size() == 2 && numCmps >= 5) &&
2049 !(Dests.size() >= 3 && numCmps >= 6)))
2052 DEBUG(dbgs() << "Emitting bit tests\n");
2053 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2055 // Optimize the case where all the case values fit in a
2056 // word without having to subtract minValue. In this case,
2057 // we can optimize away the subtraction.
2058 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2059 cmpRange = maxValue;
2061 lowBound = minValue;
2064 CaseBitsVector CasesBits;
2065 unsigned i, count = 0;
2067 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2068 MachineBasicBlock* Dest = I->BB;
2069 for (i = 0; i < count; ++i)
2070 if (Dest == CasesBits[i].BB)
2074 assert((count < 3) && "Too much destinations to test!");
2075 CasesBits.push_back(CaseBits(0, Dest, 0));
2079 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2080 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2082 uint64_t lo = (lowValue - lowBound).getZExtValue();
2083 uint64_t hi = (highValue - lowBound).getZExtValue();
2085 for (uint64_t j = lo; j <= hi; j++) {
2086 CasesBits[i].Mask |= 1ULL << j;
2087 CasesBits[i].Bits++;
2091 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2095 // Figure out which block is immediately after the current one.
2096 MachineFunction::iterator BBI = CR.CaseBB;
2099 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2101 DEBUG(dbgs() << "Cases:\n");
2102 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2103 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2104 << ", Bits: " << CasesBits[i].Bits
2105 << ", BB: " << CasesBits[i].BB << '\n');
2107 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2108 CurMF->insert(BBI, CaseBB);
2109 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2113 // Put SV in a virtual register to make it available from the new blocks.
2114 ExportFromCurrentBlock(SV);
2117 BitTestBlock BTB(lowBound, cmpRange, SV,
2118 -1U, (CR.CaseBB == SwitchBB),
2119 CR.CaseBB, Default, BTC);
2121 if (CR.CaseBB == SwitchBB)
2122 visitBitTestHeader(BTB, SwitchBB);
2124 BitTestCases.push_back(BTB);
2129 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2130 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2131 const SwitchInst& SI) {
2134 // Start with "simple" cases
2135 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2136 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2137 Cases.push_back(Case(SI.getSuccessorValue(i),
2138 SI.getSuccessorValue(i),
2141 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2143 // Merge case into clusters
2144 if (Cases.size() >= 2)
2145 // Must recompute end() each iteration because it may be
2146 // invalidated by erase if we hold on to it
2147 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2148 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2149 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2150 MachineBasicBlock* nextBB = J->BB;
2151 MachineBasicBlock* currentBB = I->BB;
2153 // If the two neighboring cases go to the same destination, merge them
2154 // into a single case.
2155 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2163 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2164 if (I->Low != I->High)
2165 // A range counts double, since it requires two compares.
2172 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2173 MachineBasicBlock *SwitchMBB = FuncInfo.MBBMap[SI.getParent()];
2175 // Figure out which block is immediately after the current one.
2176 MachineBasicBlock *NextBlock = 0;
2177 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2179 // If there is only the default destination, branch to it if it is not the
2180 // next basic block. Otherwise, just fall through.
2181 if (SI.getNumOperands() == 2) {
2182 // Update machine-CFG edges.
2184 // If this is not a fall-through branch, emit the branch.
2185 SwitchMBB->addSuccessor(Default);
2186 if (Default != NextBlock)
2187 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2188 MVT::Other, getControlRoot(),
2189 DAG.getBasicBlock(Default)));
2194 // If there are any non-default case statements, create a vector of Cases
2195 // representing each one, and sort the vector so that we can efficiently
2196 // create a binary search tree from them.
2198 size_t numCmps = Clusterify(Cases, SI);
2199 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2200 << ". Total compares: " << numCmps << '\n');
2203 // Get the Value to be switched on and default basic blocks, which will be
2204 // inserted into CaseBlock records, representing basic blocks in the binary
2206 const Value *SV = SI.getOperand(0);
2208 // Push the initial CaseRec onto the worklist
2209 CaseRecVector WorkList;
2210 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2211 CaseRange(Cases.begin(),Cases.end())));
2213 while (!WorkList.empty()) {
2214 // Grab a record representing a case range to process off the worklist
2215 CaseRec CR = WorkList.back();
2216 WorkList.pop_back();
2218 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2221 // If the range has few cases (two or less) emit a series of specific
2223 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2226 // If the switch has more than 5 blocks, and at least 40% dense, and the
2227 // target supports indirect branches, then emit a jump table rather than
2228 // lowering the switch to a binary tree of conditional branches.
2229 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2232 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2233 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2234 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2238 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2239 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBBMap[I.getParent()];
2241 // Update machine-CFG edges with unique successors.
2242 SmallVector<BasicBlock*, 32> succs;
2243 succs.reserve(I.getNumSuccessors());
2244 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2245 succs.push_back(I.getSuccessor(i));
2246 array_pod_sort(succs.begin(), succs.end());
2247 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2248 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2249 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2251 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2252 MVT::Other, getControlRoot(),
2253 getValue(I.getAddress())));
2256 void SelectionDAGBuilder::visitFSub(const User &I) {
2257 // -0.0 - X --> fneg
2258 const Type *Ty = I.getType();
2259 if (Ty->isVectorTy()) {
2260 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2261 const VectorType *DestTy = cast<VectorType>(I.getType());
2262 const Type *ElTy = DestTy->getElementType();
2263 unsigned VL = DestTy->getNumElements();
2264 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2265 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2267 SDValue Op2 = getValue(I.getOperand(1));
2268 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2269 Op2.getValueType(), Op2));
2275 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2276 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2277 SDValue Op2 = getValue(I.getOperand(1));
2278 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2279 Op2.getValueType(), Op2));
2283 visitBinary(I, ISD::FSUB);
2286 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2287 SDValue Op1 = getValue(I.getOperand(0));
2288 SDValue Op2 = getValue(I.getOperand(1));
2289 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2290 Op1.getValueType(), Op1, Op2));
2293 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2294 SDValue Op1 = getValue(I.getOperand(0));
2295 SDValue Op2 = getValue(I.getOperand(1));
2296 if (!I.getType()->isVectorTy() &&
2297 Op2.getValueType() != TLI.getShiftAmountTy()) {
2298 // If the operand is smaller than the shift count type, promote it.
2299 EVT PTy = TLI.getPointerTy();
2300 EVT STy = TLI.getShiftAmountTy();
2301 if (STy.bitsGT(Op2.getValueType()))
2302 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2303 TLI.getShiftAmountTy(), Op2);
2304 // If the operand is larger than the shift count type but the shift
2305 // count type has enough bits to represent any shift value, truncate
2306 // it now. This is a common case and it exposes the truncate to
2307 // optimization early.
2308 else if (STy.getSizeInBits() >=
2309 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2310 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2311 TLI.getShiftAmountTy(), Op2);
2312 // Otherwise we'll need to temporarily settle for some other
2313 // convenient type; type legalization will make adjustments as
2315 else if (PTy.bitsLT(Op2.getValueType()))
2316 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2317 TLI.getPointerTy(), Op2);
2318 else if (PTy.bitsGT(Op2.getValueType()))
2319 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2320 TLI.getPointerTy(), Op2);
2323 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2324 Op1.getValueType(), Op1, Op2));
2327 void SelectionDAGBuilder::visitICmp(const User &I) {
2328 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2329 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2330 predicate = IC->getPredicate();
2331 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2332 predicate = ICmpInst::Predicate(IC->getPredicate());
2333 SDValue Op1 = getValue(I.getOperand(0));
2334 SDValue Op2 = getValue(I.getOperand(1));
2335 ISD::CondCode Opcode = getICmpCondCode(predicate);
2337 EVT DestVT = TLI.getValueType(I.getType());
2338 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2341 void SelectionDAGBuilder::visitFCmp(const User &I) {
2342 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2343 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2344 predicate = FC->getPredicate();
2345 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2346 predicate = FCmpInst::Predicate(FC->getPredicate());
2347 SDValue Op1 = getValue(I.getOperand(0));
2348 SDValue Op2 = getValue(I.getOperand(1));
2349 ISD::CondCode Condition = getFCmpCondCode(predicate);
2350 EVT DestVT = TLI.getValueType(I.getType());
2351 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2354 void SelectionDAGBuilder::visitSelect(const User &I) {
2355 SmallVector<EVT, 4> ValueVTs;
2356 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2357 unsigned NumValues = ValueVTs.size();
2358 if (NumValues == 0) return;
2360 SmallVector<SDValue, 4> Values(NumValues);
2361 SDValue Cond = getValue(I.getOperand(0));
2362 SDValue TrueVal = getValue(I.getOperand(1));
2363 SDValue FalseVal = getValue(I.getOperand(2));
2365 for (unsigned i = 0; i != NumValues; ++i)
2366 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2367 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2369 SDValue(TrueVal.getNode(),
2370 TrueVal.getResNo() + i),
2371 SDValue(FalseVal.getNode(),
2372 FalseVal.getResNo() + i));
2374 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2375 DAG.getVTList(&ValueVTs[0], NumValues),
2376 &Values[0], NumValues));
2379 void SelectionDAGBuilder::visitTrunc(const User &I) {
2380 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2381 SDValue N = getValue(I.getOperand(0));
2382 EVT DestVT = TLI.getValueType(I.getType());
2383 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2386 void SelectionDAGBuilder::visitZExt(const User &I) {
2387 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2388 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2389 SDValue N = getValue(I.getOperand(0));
2390 EVT DestVT = TLI.getValueType(I.getType());
2391 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2394 void SelectionDAGBuilder::visitSExt(const User &I) {
2395 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2396 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2397 SDValue N = getValue(I.getOperand(0));
2398 EVT DestVT = TLI.getValueType(I.getType());
2399 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2402 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2403 // FPTrunc is never a no-op cast, no need to check
2404 SDValue N = getValue(I.getOperand(0));
2405 EVT DestVT = TLI.getValueType(I.getType());
2406 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2407 DestVT, N, DAG.getIntPtrConstant(0)));
2410 void SelectionDAGBuilder::visitFPExt(const User &I){
2411 // FPTrunc is never a no-op cast, no need to check
2412 SDValue N = getValue(I.getOperand(0));
2413 EVT DestVT = TLI.getValueType(I.getType());
2414 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2417 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2418 // FPToUI is never a no-op cast, no need to check
2419 SDValue N = getValue(I.getOperand(0));
2420 EVT DestVT = TLI.getValueType(I.getType());
2421 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2424 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2425 // FPToSI is never a no-op cast, no need to check
2426 SDValue N = getValue(I.getOperand(0));
2427 EVT DestVT = TLI.getValueType(I.getType());
2428 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2431 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2432 // UIToFP is never a no-op cast, no need to check
2433 SDValue N = getValue(I.getOperand(0));
2434 EVT DestVT = TLI.getValueType(I.getType());
2435 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2438 void SelectionDAGBuilder::visitSIToFP(const User &I){
2439 // SIToFP is never a no-op cast, no need to check
2440 SDValue N = getValue(I.getOperand(0));
2441 EVT DestVT = TLI.getValueType(I.getType());
2442 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2445 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2446 // What to do depends on the size of the integer and the size of the pointer.
2447 // We can either truncate, zero extend, or no-op, accordingly.
2448 SDValue N = getValue(I.getOperand(0));
2449 EVT DestVT = TLI.getValueType(I.getType());
2450 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2453 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2454 // What to do depends on the size of the integer and the size of the pointer.
2455 // We can either truncate, zero extend, or no-op, accordingly.
2456 SDValue N = getValue(I.getOperand(0));
2457 EVT DestVT = TLI.getValueType(I.getType());
2458 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2461 void SelectionDAGBuilder::visitBitCast(const User &I) {
2462 SDValue N = getValue(I.getOperand(0));
2463 EVT DestVT = TLI.getValueType(I.getType());
2465 // BitCast assures us that source and destination are the same size so this is
2466 // either a BIT_CONVERT or a no-op.
2467 if (DestVT != N.getValueType())
2468 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2469 DestVT, N)); // convert types.
2471 setValue(&I, N); // noop cast.
2474 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2475 SDValue InVec = getValue(I.getOperand(0));
2476 SDValue InVal = getValue(I.getOperand(1));
2477 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2479 getValue(I.getOperand(2)));
2480 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2481 TLI.getValueType(I.getType()),
2482 InVec, InVal, InIdx));
2485 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2486 SDValue InVec = getValue(I.getOperand(0));
2487 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2489 getValue(I.getOperand(1)));
2490 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2491 TLI.getValueType(I.getType()), InVec, InIdx));
2494 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2495 // from SIndx and increasing to the element length (undefs are allowed).
2496 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2497 unsigned MaskNumElts = Mask.size();
2498 for (unsigned i = 0; i != MaskNumElts; ++i)
2499 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2504 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2505 SmallVector<int, 8> Mask;
2506 SDValue Src1 = getValue(I.getOperand(0));
2507 SDValue Src2 = getValue(I.getOperand(1));
2509 // Convert the ConstantVector mask operand into an array of ints, with -1
2510 // representing undef values.
2511 SmallVector<Constant*, 8> MaskElts;
2512 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2513 unsigned MaskNumElts = MaskElts.size();
2514 for (unsigned i = 0; i != MaskNumElts; ++i) {
2515 if (isa<UndefValue>(MaskElts[i]))
2518 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2521 EVT VT = TLI.getValueType(I.getType());
2522 EVT SrcVT = Src1.getValueType();
2523 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2525 if (SrcNumElts == MaskNumElts) {
2526 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2531 // Normalize the shuffle vector since mask and vector length don't match.
2532 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2533 // Mask is longer than the source vectors and is a multiple of the source
2534 // vectors. We can use concatenate vector to make the mask and vectors
2536 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2537 // The shuffle is concatenating two vectors together.
2538 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2543 // Pad both vectors with undefs to make them the same length as the mask.
2544 unsigned NumConcat = MaskNumElts / SrcNumElts;
2545 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2546 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2547 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2549 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2550 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2554 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2555 getCurDebugLoc(), VT,
2556 &MOps1[0], NumConcat);
2557 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2558 getCurDebugLoc(), VT,
2559 &MOps2[0], NumConcat);
2561 // Readjust mask for new input vector length.
2562 SmallVector<int, 8> MappedOps;
2563 for (unsigned i = 0; i != MaskNumElts; ++i) {
2565 if (Idx < (int)SrcNumElts)
2566 MappedOps.push_back(Idx);
2568 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2571 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2576 if (SrcNumElts > MaskNumElts) {
2577 // Analyze the access pattern of the vector to see if we can extract
2578 // two subvectors and do the shuffle. The analysis is done by calculating
2579 // the range of elements the mask access on both vectors.
2580 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2581 int MaxRange[2] = {-1, -1};
2583 for (unsigned i = 0; i != MaskNumElts; ++i) {
2589 if (Idx >= (int)SrcNumElts) {
2593 if (Idx > MaxRange[Input])
2594 MaxRange[Input] = Idx;
2595 if (Idx < MinRange[Input])
2596 MinRange[Input] = Idx;
2599 // Check if the access is smaller than the vector size and can we find
2600 // a reasonable extract index.
2601 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2603 int StartIdx[2]; // StartIdx to extract from
2604 for (int Input=0; Input < 2; ++Input) {
2605 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2606 RangeUse[Input] = 0; // Unused
2607 StartIdx[Input] = 0;
2608 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2609 // Fits within range but we should see if we can find a good
2610 // start index that is a multiple of the mask length.
2611 if (MaxRange[Input] < (int)MaskNumElts) {
2612 RangeUse[Input] = 1; // Extract from beginning of the vector
2613 StartIdx[Input] = 0;
2615 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2616 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2617 StartIdx[Input] + MaskNumElts < SrcNumElts)
2618 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2623 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2624 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2627 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2628 // Extract appropriate subvector and generate a vector shuffle
2629 for (int Input=0; Input < 2; ++Input) {
2630 SDValue &Src = Input == 0 ? Src1 : Src2;
2631 if (RangeUse[Input] == 0)
2632 Src = DAG.getUNDEF(VT);
2634 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2635 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2638 // Calculate new mask.
2639 SmallVector<int, 8> MappedOps;
2640 for (unsigned i = 0; i != MaskNumElts; ++i) {
2643 MappedOps.push_back(Idx);
2644 else if (Idx < (int)SrcNumElts)
2645 MappedOps.push_back(Idx - StartIdx[0]);
2647 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2650 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2656 // We can't use either concat vectors or extract subvectors so fall back to
2657 // replacing the shuffle with extract and build vector.
2658 // to insert and build vector.
2659 EVT EltVT = VT.getVectorElementType();
2660 EVT PtrVT = TLI.getPointerTy();
2661 SmallVector<SDValue,8> Ops;
2662 for (unsigned i = 0; i != MaskNumElts; ++i) {
2664 Ops.push_back(DAG.getUNDEF(EltVT));
2669 if (Idx < (int)SrcNumElts)
2670 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2671 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2673 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2675 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2681 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2682 VT, &Ops[0], Ops.size()));
2685 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2686 const Value *Op0 = I.getOperand(0);
2687 const Value *Op1 = I.getOperand(1);
2688 const Type *AggTy = I.getType();
2689 const Type *ValTy = Op1->getType();
2690 bool IntoUndef = isa<UndefValue>(Op0);
2691 bool FromUndef = isa<UndefValue>(Op1);
2693 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2694 I.idx_begin(), I.idx_end());
2696 SmallVector<EVT, 4> AggValueVTs;
2697 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2698 SmallVector<EVT, 4> ValValueVTs;
2699 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2701 unsigned NumAggValues = AggValueVTs.size();
2702 unsigned NumValValues = ValValueVTs.size();
2703 SmallVector<SDValue, 4> Values(NumAggValues);
2705 SDValue Agg = getValue(Op0);
2706 SDValue Val = getValue(Op1);
2708 // Copy the beginning value(s) from the original aggregate.
2709 for (; i != LinearIndex; ++i)
2710 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2711 SDValue(Agg.getNode(), Agg.getResNo() + i);
2712 // Copy values from the inserted value(s).
2713 for (; i != LinearIndex + NumValValues; ++i)
2714 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2715 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2716 // Copy remaining value(s) from the original aggregate.
2717 for (; i != NumAggValues; ++i)
2718 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2719 SDValue(Agg.getNode(), Agg.getResNo() + i);
2721 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2722 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2723 &Values[0], NumAggValues));
2726 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2727 const Value *Op0 = I.getOperand(0);
2728 const Type *AggTy = Op0->getType();
2729 const Type *ValTy = I.getType();
2730 bool OutOfUndef = isa<UndefValue>(Op0);
2732 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2733 I.idx_begin(), I.idx_end());
2735 SmallVector<EVT, 4> ValValueVTs;
2736 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2738 unsigned NumValValues = ValValueVTs.size();
2739 SmallVector<SDValue, 4> Values(NumValValues);
2741 SDValue Agg = getValue(Op0);
2742 // Copy out the selected value(s).
2743 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2744 Values[i - LinearIndex] =
2746 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2747 SDValue(Agg.getNode(), Agg.getResNo() + i);
2749 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2750 DAG.getVTList(&ValValueVTs[0], NumValValues),
2751 &Values[0], NumValValues));
2754 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2755 SDValue N = getValue(I.getOperand(0));
2756 const Type *Ty = I.getOperand(0)->getType();
2758 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2760 const Value *Idx = *OI;
2761 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2762 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2765 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2766 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2767 DAG.getIntPtrConstant(Offset));
2770 Ty = StTy->getElementType(Field);
2771 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2772 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2774 // Offset canonically 0 for unions, but type changes
2775 Ty = UnTy->getElementType(Field);
2777 Ty = cast<SequentialType>(Ty)->getElementType();
2779 // If this is a constant subscript, handle it quickly.
2780 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2781 if (CI->isZero()) continue;
2783 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2785 EVT PTy = TLI.getPointerTy();
2786 unsigned PtrBits = PTy.getSizeInBits();
2788 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2790 DAG.getConstant(Offs, MVT::i64));
2792 OffsVal = DAG.getIntPtrConstant(Offs);
2794 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2799 // N = N + Idx * ElementSize;
2800 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2801 TD->getTypeAllocSize(Ty));
2802 SDValue IdxN = getValue(Idx);
2804 // If the index is smaller or larger than intptr_t, truncate or extend
2806 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2808 // If this is a multiply by a power of two, turn it into a shl
2809 // immediately. This is a very common case.
2810 if (ElementSize != 1) {
2811 if (ElementSize.isPowerOf2()) {
2812 unsigned Amt = ElementSize.logBase2();
2813 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2814 N.getValueType(), IdxN,
2815 DAG.getConstant(Amt, TLI.getPointerTy()));
2817 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2818 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2819 N.getValueType(), IdxN, Scale);
2823 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2824 N.getValueType(), N, IdxN);
2831 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2832 // If this is a fixed sized alloca in the entry block of the function,
2833 // allocate it statically on the stack.
2834 if (FuncInfo.StaticAllocaMap.count(&I))
2835 return; // getValue will auto-populate this.
2837 const Type *Ty = I.getAllocatedType();
2838 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2840 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2843 SDValue AllocSize = getValue(I.getArraySize());
2845 EVT IntPtr = TLI.getPointerTy();
2846 if (AllocSize.getValueType() != IntPtr)
2847 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2849 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
2851 DAG.getConstant(TySize, IntPtr));
2853 // Handle alignment. If the requested alignment is less than or equal to
2854 // the stack alignment, ignore it. If the size is greater than or equal to
2855 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2856 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment();
2857 if (Align <= StackAlign)
2860 // Round the size of the allocation up to the stack alignment size
2861 // by add SA-1 to the size.
2862 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2863 AllocSize.getValueType(), AllocSize,
2864 DAG.getIntPtrConstant(StackAlign-1));
2866 // Mask out the low bits for alignment purposes.
2867 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2868 AllocSize.getValueType(), AllocSize,
2869 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2871 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2872 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2873 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2876 DAG.setRoot(DSA.getValue(1));
2878 // Inform the Frame Information that we have just allocated a variable-sized
2880 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2883 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2884 const Value *SV = I.getOperand(0);
2885 SDValue Ptr = getValue(SV);
2887 const Type *Ty = I.getType();
2889 bool isVolatile = I.isVolatile();
2890 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2891 unsigned Alignment = I.getAlignment();
2893 SmallVector<EVT, 4> ValueVTs;
2894 SmallVector<uint64_t, 4> Offsets;
2895 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2896 unsigned NumValues = ValueVTs.size();
2901 bool ConstantMemory = false;
2903 // Serialize volatile loads with other side effects.
2905 else if (AA->pointsToConstantMemory(SV)) {
2906 // Do not serialize (non-volatile) loads of constant memory with anything.
2907 Root = DAG.getEntryNode();
2908 ConstantMemory = true;
2910 // Do not serialize non-volatile loads against each other.
2911 Root = DAG.getRoot();
2914 SmallVector<SDValue, 4> Values(NumValues);
2915 SmallVector<SDValue, 4> Chains(NumValues);
2916 EVT PtrVT = Ptr.getValueType();
2917 for (unsigned i = 0; i != NumValues; ++i) {
2918 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2920 DAG.getConstant(Offsets[i], PtrVT));
2921 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2922 A, SV, Offsets[i], isVolatile,
2923 isNonTemporal, Alignment);
2926 Chains[i] = L.getValue(1);
2929 if (!ConstantMemory) {
2930 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2931 MVT::Other, &Chains[0], NumValues);
2935 PendingLoads.push_back(Chain);
2938 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2939 DAG.getVTList(&ValueVTs[0], NumValues),
2940 &Values[0], NumValues));
2943 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2944 const Value *SrcV = I.getOperand(0);
2945 const Value *PtrV = I.getOperand(1);
2947 SmallVector<EVT, 4> ValueVTs;
2948 SmallVector<uint64_t, 4> Offsets;
2949 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2950 unsigned NumValues = ValueVTs.size();
2954 // Get the lowered operands. Note that we do this after
2955 // checking if NumResults is zero, because with zero results
2956 // the operands won't have values in the map.
2957 SDValue Src = getValue(SrcV);
2958 SDValue Ptr = getValue(PtrV);
2960 SDValue Root = getRoot();
2961 SmallVector<SDValue, 4> Chains(NumValues);
2962 EVT PtrVT = Ptr.getValueType();
2963 bool isVolatile = I.isVolatile();
2964 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2965 unsigned Alignment = I.getAlignment();
2967 for (unsigned i = 0; i != NumValues; ++i) {
2968 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2969 DAG.getConstant(Offsets[i], PtrVT));
2970 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2971 SDValue(Src.getNode(), Src.getResNo() + i),
2972 Add, PtrV, Offsets[i], isVolatile,
2973 isNonTemporal, Alignment);
2976 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2977 MVT::Other, &Chains[0], NumValues));
2980 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2982 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
2983 unsigned Intrinsic) {
2984 bool HasChain = !I.doesNotAccessMemory();
2985 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2987 // Build the operand list.
2988 SmallVector<SDValue, 8> Ops;
2989 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2991 // We don't need to serialize loads against other loads.
2992 Ops.push_back(DAG.getRoot());
2994 Ops.push_back(getRoot());
2998 // Info is set by getTgtMemInstrinsic
2999 TargetLowering::IntrinsicInfo Info;
3000 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3002 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3003 if (!IsTgtIntrinsic)
3004 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3006 // Add all operands of the call to the operand list.
3007 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3008 SDValue Op = getValue(I.getArgOperand(i));
3009 assert(TLI.isTypeLegal(Op.getValueType()) &&
3010 "Intrinsic uses a non-legal type?");
3014 SmallVector<EVT, 4> ValueVTs;
3015 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3017 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3018 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3019 "Intrinsic uses a non-legal type?");
3024 ValueVTs.push_back(MVT::Other);
3026 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3030 if (IsTgtIntrinsic) {
3031 // This is target intrinsic that touches memory
3032 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3033 VTs, &Ops[0], Ops.size(),
3034 Info.memVT, Info.ptrVal, Info.offset,
3035 Info.align, Info.vol,
3036 Info.readMem, Info.writeMem);
3037 } else if (!HasChain) {
3038 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3039 VTs, &Ops[0], Ops.size());
3040 } else if (!I.getType()->isVoidTy()) {
3041 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3042 VTs, &Ops[0], Ops.size());
3044 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3045 VTs, &Ops[0], Ops.size());
3049 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3051 PendingLoads.push_back(Chain);
3056 if (!I.getType()->isVoidTy()) {
3057 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3058 EVT VT = TLI.getValueType(PTy);
3059 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3062 setValue(&I, Result);
3066 /// GetSignificand - Get the significand and build it into a floating-point
3067 /// number with exponent of 1:
3069 /// Op = (Op & 0x007fffff) | 0x3f800000;
3071 /// where Op is the hexidecimal representation of floating point value.
3073 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3074 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3075 DAG.getConstant(0x007fffff, MVT::i32));
3076 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3077 DAG.getConstant(0x3f800000, MVT::i32));
3078 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3081 /// GetExponent - Get the exponent:
3083 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3085 /// where Op is the hexidecimal representation of floating point value.
3087 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3089 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3090 DAG.getConstant(0x7f800000, MVT::i32));
3091 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3092 DAG.getConstant(23, TLI.getPointerTy()));
3093 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3094 DAG.getConstant(127, MVT::i32));
3095 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3098 /// getF32Constant - Get 32-bit floating point constant.
3100 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3101 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3104 /// Inlined utility function to implement binary input atomic intrinsics for
3105 /// visitIntrinsicCall: I is a call instruction
3106 /// Op is the associated NodeType for I
3108 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3110 SDValue Root = getRoot();
3112 DAG.getAtomic(Op, getCurDebugLoc(),
3113 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3115 getValue(I.getArgOperand(0)),
3116 getValue(I.getArgOperand(1)),
3117 I.getArgOperand(0));
3119 DAG.setRoot(L.getValue(1));
3123 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3125 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3126 SDValue Op1 = getValue(I.getArgOperand(0));
3127 SDValue Op2 = getValue(I.getArgOperand(1));
3129 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3130 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3134 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3135 /// limited-precision mode.
3137 SelectionDAGBuilder::visitExp(const CallInst &I) {
3139 DebugLoc dl = getCurDebugLoc();
3141 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3142 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3143 SDValue Op = getValue(I.getArgOperand(0));
3145 // Put the exponent in the right bit position for later addition to the
3148 // #define LOG2OFe 1.4426950f
3149 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3150 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3151 getF32Constant(DAG, 0x3fb8aa3b));
3152 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3154 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3155 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3156 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3158 // IntegerPartOfX <<= 23;
3159 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3160 DAG.getConstant(23, TLI.getPointerTy()));
3162 if (LimitFloatPrecision <= 6) {
3163 // For floating-point precision of 6:
3165 // TwoToFractionalPartOfX =
3167 // (0.735607626f + 0.252464424f * x) * x;
3169 // error 0.0144103317, which is 6 bits
3170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3171 getF32Constant(DAG, 0x3e814304));
3172 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3173 getF32Constant(DAG, 0x3f3c50c8));
3174 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3175 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3176 getF32Constant(DAG, 0x3f7f5e7e));
3177 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3179 // Add the exponent into the result in integer domain.
3180 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3181 TwoToFracPartOfX, IntegerPartOfX);
3183 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3184 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3185 // For floating-point precision of 12:
3187 // TwoToFractionalPartOfX =
3190 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3192 // 0.000107046256 error, which is 13 to 14 bits
3193 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3194 getF32Constant(DAG, 0x3da235e3));
3195 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3196 getF32Constant(DAG, 0x3e65b8f3));
3197 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3198 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3199 getF32Constant(DAG, 0x3f324b07));
3200 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3201 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3202 getF32Constant(DAG, 0x3f7ff8fd));
3203 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3205 // Add the exponent into the result in integer domain.
3206 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3207 TwoToFracPartOfX, IntegerPartOfX);
3209 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3210 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3211 // For floating-point precision of 18:
3213 // TwoToFractionalPartOfX =
3217 // (0.554906021e-1f +
3218 // (0.961591928e-2f +
3219 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3221 // error 2.47208000*10^(-7), which is better than 18 bits
3222 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3223 getF32Constant(DAG, 0x3924b03e));
3224 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3225 getF32Constant(DAG, 0x3ab24b87));
3226 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3227 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3228 getF32Constant(DAG, 0x3c1d8c17));
3229 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3230 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3231 getF32Constant(DAG, 0x3d634a1d));
3232 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3233 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3234 getF32Constant(DAG, 0x3e75fe14));
3235 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3236 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3237 getF32Constant(DAG, 0x3f317234));
3238 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3239 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3240 getF32Constant(DAG, 0x3f800000));
3241 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3244 // Add the exponent into the result in integer domain.
3245 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3246 TwoToFracPartOfX, IntegerPartOfX);
3248 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3251 // No special expansion.
3252 result = DAG.getNode(ISD::FEXP, dl,
3253 getValue(I.getArgOperand(0)).getValueType(),
3254 getValue(I.getArgOperand(0)));
3257 setValue(&I, result);
3260 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3261 /// limited-precision mode.
3263 SelectionDAGBuilder::visitLog(const CallInst &I) {
3265 DebugLoc dl = getCurDebugLoc();
3267 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3268 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3269 SDValue Op = getValue(I.getArgOperand(0));
3270 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3272 // Scale the exponent by log(2) [0.69314718f].
3273 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3274 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3275 getF32Constant(DAG, 0x3f317218));
3277 // Get the significand and build it into a floating-point number with
3279 SDValue X = GetSignificand(DAG, Op1, dl);
3281 if (LimitFloatPrecision <= 6) {
3282 // For floating-point precision of 6:
3286 // (1.4034025f - 0.23903021f * x) * x;
3288 // error 0.0034276066, which is better than 8 bits
3289 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3290 getF32Constant(DAG, 0xbe74c456));
3291 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3292 getF32Constant(DAG, 0x3fb3a2b1));
3293 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3294 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3295 getF32Constant(DAG, 0x3f949a29));
3297 result = DAG.getNode(ISD::FADD, dl,
3298 MVT::f32, LogOfExponent, LogOfMantissa);
3299 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3300 // For floating-point precision of 12:
3306 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3308 // error 0.000061011436, which is 14 bits
3309 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3310 getF32Constant(DAG, 0xbd67b6d6));
3311 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3312 getF32Constant(DAG, 0x3ee4f4b8));
3313 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3314 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3315 getF32Constant(DAG, 0x3fbc278b));
3316 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3317 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3318 getF32Constant(DAG, 0x40348e95));
3319 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3320 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3321 getF32Constant(DAG, 0x3fdef31a));
3323 result = DAG.getNode(ISD::FADD, dl,
3324 MVT::f32, LogOfExponent, LogOfMantissa);
3325 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3326 // For floating-point precision of 18:
3334 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3336 // error 0.0000023660568, which is better than 18 bits
3337 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3338 getF32Constant(DAG, 0xbc91e5ac));
3339 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3340 getF32Constant(DAG, 0x3e4350aa));
3341 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3342 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3343 getF32Constant(DAG, 0x3f60d3e3));
3344 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3345 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3346 getF32Constant(DAG, 0x4011cdf0));
3347 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3348 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3349 getF32Constant(DAG, 0x406cfd1c));
3350 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3351 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3352 getF32Constant(DAG, 0x408797cb));
3353 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3354 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3355 getF32Constant(DAG, 0x4006dcab));
3357 result = DAG.getNode(ISD::FADD, dl,
3358 MVT::f32, LogOfExponent, LogOfMantissa);
3361 // No special expansion.
3362 result = DAG.getNode(ISD::FLOG, dl,
3363 getValue(I.getArgOperand(0)).getValueType(),
3364 getValue(I.getArgOperand(0)));
3367 setValue(&I, result);
3370 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3371 /// limited-precision mode.
3373 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3375 DebugLoc dl = getCurDebugLoc();
3377 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3378 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3379 SDValue Op = getValue(I.getArgOperand(0));
3380 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3382 // Get the exponent.
3383 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3385 // Get the significand and build it into a floating-point number with
3387 SDValue X = GetSignificand(DAG, Op1, dl);
3389 // Different possible minimax approximations of significand in
3390 // floating-point for various degrees of accuracy over [1,2].
3391 if (LimitFloatPrecision <= 6) {
3392 // For floating-point precision of 6:
3394 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3396 // error 0.0049451742, which is more than 7 bits
3397 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3398 getF32Constant(DAG, 0xbeb08fe0));
3399 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3400 getF32Constant(DAG, 0x40019463));
3401 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3402 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3403 getF32Constant(DAG, 0x3fd6633d));
3405 result = DAG.getNode(ISD::FADD, dl,
3406 MVT::f32, LogOfExponent, Log2ofMantissa);
3407 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3408 // For floating-point precision of 12:
3414 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3416 // error 0.0000876136000, which is better than 13 bits
3417 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3418 getF32Constant(DAG, 0xbda7262e));
3419 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3420 getF32Constant(DAG, 0x3f25280b));
3421 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3422 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3423 getF32Constant(DAG, 0x4007b923));
3424 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3425 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3426 getF32Constant(DAG, 0x40823e2f));
3427 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3428 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3429 getF32Constant(DAG, 0x4020d29c));
3431 result = DAG.getNode(ISD::FADD, dl,
3432 MVT::f32, LogOfExponent, Log2ofMantissa);
3433 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3434 // For floating-point precision of 18:
3443 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3445 // error 0.0000018516, which is better than 18 bits
3446 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3447 getF32Constant(DAG, 0xbcd2769e));
3448 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3449 getF32Constant(DAG, 0x3e8ce0b9));
3450 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3451 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3452 getF32Constant(DAG, 0x3fa22ae7));
3453 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3454 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3455 getF32Constant(DAG, 0x40525723));
3456 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3457 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3458 getF32Constant(DAG, 0x40aaf200));
3459 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3460 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3461 getF32Constant(DAG, 0x40c39dad));
3462 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3463 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3464 getF32Constant(DAG, 0x4042902c));
3466 result = DAG.getNode(ISD::FADD, dl,
3467 MVT::f32, LogOfExponent, Log2ofMantissa);
3470 // No special expansion.
3471 result = DAG.getNode(ISD::FLOG2, dl,
3472 getValue(I.getArgOperand(0)).getValueType(),
3473 getValue(I.getArgOperand(0)));
3476 setValue(&I, result);
3479 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3480 /// limited-precision mode.
3482 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3484 DebugLoc dl = getCurDebugLoc();
3486 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3487 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3488 SDValue Op = getValue(I.getArgOperand(0));
3489 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3491 // Scale the exponent by log10(2) [0.30102999f].
3492 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3493 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3494 getF32Constant(DAG, 0x3e9a209a));
3496 // Get the significand and build it into a floating-point number with
3498 SDValue X = GetSignificand(DAG, Op1, dl);
3500 if (LimitFloatPrecision <= 6) {
3501 // For floating-point precision of 6:
3503 // Log10ofMantissa =
3505 // (0.60948995f - 0.10380950f * x) * x;
3507 // error 0.0014886165, which is 6 bits
3508 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3509 getF32Constant(DAG, 0xbdd49a13));
3510 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3511 getF32Constant(DAG, 0x3f1c0789));
3512 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3513 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3514 getF32Constant(DAG, 0x3f011300));
3516 result = DAG.getNode(ISD::FADD, dl,
3517 MVT::f32, LogOfExponent, Log10ofMantissa);
3518 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3519 // For floating-point precision of 12:
3521 // Log10ofMantissa =
3524 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3526 // error 0.00019228036, which is better than 12 bits
3527 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3528 getF32Constant(DAG, 0x3d431f31));
3529 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3530 getF32Constant(DAG, 0x3ea21fb2));
3531 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3532 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3533 getF32Constant(DAG, 0x3f6ae232));
3534 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3535 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3536 getF32Constant(DAG, 0x3f25f7c3));
3538 result = DAG.getNode(ISD::FADD, dl,
3539 MVT::f32, LogOfExponent, Log10ofMantissa);
3540 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3541 // For floating-point precision of 18:
3543 // Log10ofMantissa =
3548 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3550 // error 0.0000037995730, which is better than 18 bits
3551 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3552 getF32Constant(DAG, 0x3c5d51ce));
3553 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3554 getF32Constant(DAG, 0x3e00685a));
3555 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3556 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3557 getF32Constant(DAG, 0x3efb6798));
3558 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3559 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3560 getF32Constant(DAG, 0x3f88d192));
3561 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3562 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3563 getF32Constant(DAG, 0x3fc4316c));
3564 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3565 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3566 getF32Constant(DAG, 0x3f57ce70));
3568 result = DAG.getNode(ISD::FADD, dl,
3569 MVT::f32, LogOfExponent, Log10ofMantissa);
3572 // No special expansion.
3573 result = DAG.getNode(ISD::FLOG10, dl,
3574 getValue(I.getArgOperand(0)).getValueType(),
3575 getValue(I.getArgOperand(0)));
3578 setValue(&I, result);
3581 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3582 /// limited-precision mode.
3584 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3586 DebugLoc dl = getCurDebugLoc();
3588 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3589 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3590 SDValue Op = getValue(I.getArgOperand(0));
3592 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3594 // FractionalPartOfX = x - (float)IntegerPartOfX;
3595 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3596 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3598 // IntegerPartOfX <<= 23;
3599 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3600 DAG.getConstant(23, TLI.getPointerTy()));
3602 if (LimitFloatPrecision <= 6) {
3603 // For floating-point precision of 6:
3605 // TwoToFractionalPartOfX =
3607 // (0.735607626f + 0.252464424f * x) * x;
3609 // error 0.0144103317, which is 6 bits
3610 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3611 getF32Constant(DAG, 0x3e814304));
3612 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3613 getF32Constant(DAG, 0x3f3c50c8));
3614 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3615 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3616 getF32Constant(DAG, 0x3f7f5e7e));
3617 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3618 SDValue TwoToFractionalPartOfX =
3619 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3621 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3622 MVT::f32, TwoToFractionalPartOfX);
3623 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3624 // For floating-point precision of 12:
3626 // TwoToFractionalPartOfX =
3629 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3631 // error 0.000107046256, which is 13 to 14 bits
3632 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3633 getF32Constant(DAG, 0x3da235e3));
3634 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3635 getF32Constant(DAG, 0x3e65b8f3));
3636 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3637 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3638 getF32Constant(DAG, 0x3f324b07));
3639 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3640 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3641 getF32Constant(DAG, 0x3f7ff8fd));
3642 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3643 SDValue TwoToFractionalPartOfX =
3644 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3646 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3647 MVT::f32, TwoToFractionalPartOfX);
3648 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3649 // For floating-point precision of 18:
3651 // TwoToFractionalPartOfX =
3655 // (0.554906021e-1f +
3656 // (0.961591928e-2f +
3657 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3658 // error 2.47208000*10^(-7), which is better than 18 bits
3659 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3660 getF32Constant(DAG, 0x3924b03e));
3661 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3662 getF32Constant(DAG, 0x3ab24b87));
3663 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3664 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3665 getF32Constant(DAG, 0x3c1d8c17));
3666 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3667 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3668 getF32Constant(DAG, 0x3d634a1d));
3669 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3670 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3671 getF32Constant(DAG, 0x3e75fe14));
3672 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3673 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3674 getF32Constant(DAG, 0x3f317234));
3675 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3676 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3677 getF32Constant(DAG, 0x3f800000));
3678 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3679 SDValue TwoToFractionalPartOfX =
3680 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3682 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3683 MVT::f32, TwoToFractionalPartOfX);
3686 // No special expansion.
3687 result = DAG.getNode(ISD::FEXP2, dl,
3688 getValue(I.getArgOperand(0)).getValueType(),
3689 getValue(I.getArgOperand(0)));
3692 setValue(&I, result);
3695 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3696 /// limited-precision mode with x == 10.0f.
3698 SelectionDAGBuilder::visitPow(const CallInst &I) {
3700 const Value *Val = I.getArgOperand(0);
3701 DebugLoc dl = getCurDebugLoc();
3702 bool IsExp10 = false;
3704 if (getValue(Val).getValueType() == MVT::f32 &&
3705 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3706 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3707 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3708 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3710 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3715 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3716 SDValue Op = getValue(I.getArgOperand(1));
3718 // Put the exponent in the right bit position for later addition to the
3721 // #define LOG2OF10 3.3219281f
3722 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3723 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3724 getF32Constant(DAG, 0x40549a78));
3725 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3727 // FractionalPartOfX = x - (float)IntegerPartOfX;
3728 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3729 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3731 // IntegerPartOfX <<= 23;
3732 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3733 DAG.getConstant(23, TLI.getPointerTy()));
3735 if (LimitFloatPrecision <= 6) {
3736 // For floating-point precision of 6:
3738 // twoToFractionalPartOfX =
3740 // (0.735607626f + 0.252464424f * x) * x;
3742 // error 0.0144103317, which is 6 bits
3743 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3744 getF32Constant(DAG, 0x3e814304));
3745 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3746 getF32Constant(DAG, 0x3f3c50c8));
3747 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3748 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3749 getF32Constant(DAG, 0x3f7f5e7e));
3750 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3751 SDValue TwoToFractionalPartOfX =
3752 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3754 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3755 MVT::f32, TwoToFractionalPartOfX);
3756 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3757 // For floating-point precision of 12:
3759 // TwoToFractionalPartOfX =
3762 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3764 // error 0.000107046256, which is 13 to 14 bits
3765 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3766 getF32Constant(DAG, 0x3da235e3));
3767 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3768 getF32Constant(DAG, 0x3e65b8f3));
3769 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3770 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3771 getF32Constant(DAG, 0x3f324b07));
3772 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3773 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3774 getF32Constant(DAG, 0x3f7ff8fd));
3775 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3776 SDValue TwoToFractionalPartOfX =
3777 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3779 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3780 MVT::f32, TwoToFractionalPartOfX);
3781 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3782 // For floating-point precision of 18:
3784 // TwoToFractionalPartOfX =
3788 // (0.554906021e-1f +
3789 // (0.961591928e-2f +
3790 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3791 // error 2.47208000*10^(-7), which is better than 18 bits
3792 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3793 getF32Constant(DAG, 0x3924b03e));
3794 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3795 getF32Constant(DAG, 0x3ab24b87));
3796 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3797 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3798 getF32Constant(DAG, 0x3c1d8c17));
3799 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3800 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3801 getF32Constant(DAG, 0x3d634a1d));
3802 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3803 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3804 getF32Constant(DAG, 0x3e75fe14));
3805 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3806 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3807 getF32Constant(DAG, 0x3f317234));
3808 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3809 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3810 getF32Constant(DAG, 0x3f800000));
3811 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3812 SDValue TwoToFractionalPartOfX =
3813 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3815 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3816 MVT::f32, TwoToFractionalPartOfX);
3819 // No special expansion.
3820 result = DAG.getNode(ISD::FPOW, dl,
3821 getValue(I.getArgOperand(0)).getValueType(),
3822 getValue(I.getArgOperand(0)),
3823 getValue(I.getArgOperand(1)));
3826 setValue(&I, result);
3830 /// ExpandPowI - Expand a llvm.powi intrinsic.
3831 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3832 SelectionDAG &DAG) {
3833 // If RHS is a constant, we can expand this out to a multiplication tree,
3834 // otherwise we end up lowering to a call to __powidf2 (for example). When
3835 // optimizing for size, we only want to do this if the expansion would produce
3836 // a small number of multiplies, otherwise we do the full expansion.
3837 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3838 // Get the exponent as a positive value.
3839 unsigned Val = RHSC->getSExtValue();
3840 if ((int)Val < 0) Val = -Val;
3842 // powi(x, 0) -> 1.0
3844 return DAG.getConstantFP(1.0, LHS.getValueType());
3846 const Function *F = DAG.getMachineFunction().getFunction();
3847 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3848 // If optimizing for size, don't insert too many multiplies. This
3849 // inserts up to 5 multiplies.
3850 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3851 // We use the simple binary decomposition method to generate the multiply
3852 // sequence. There are more optimal ways to do this (for example,
3853 // powi(x,15) generates one more multiply than it should), but this has
3854 // the benefit of being both really simple and much better than a libcall.
3855 SDValue Res; // Logically starts equal to 1.0
3856 SDValue CurSquare = LHS;
3860 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3862 Res = CurSquare; // 1.0*CurSquare.
3865 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3866 CurSquare, CurSquare);
3870 // If the original was negative, invert the result, producing 1/(x*x*x).
3871 if (RHSC->getSExtValue() < 0)
3872 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3873 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3878 // Otherwise, expand to a libcall.
3879 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3882 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
3883 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
3884 /// At the end of instruction selection, they will be inserted to the entry BB.
3886 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const DbgValueInst &DI,
3887 const Value *V, MDNode *Variable,
3890 if (!isa<Argument>(V))
3893 MachineFunction &MF = DAG.getMachineFunction();
3894 // Ignore inlined function arguments here.
3895 DIVariable DV(Variable);
3896 if (DV.isInlinedFnArgument(MF.getFunction()))
3899 MachineBasicBlock *MBB = FuncInfo.MBBMap[DI.getParent()];
3900 if (MBB != &MF.front())
3904 if (N.getOpcode() == ISD::CopyFromReg) {
3905 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
3906 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
3907 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3908 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
3915 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
3916 if (VMI == FuncInfo.ValueMap.end())
3921 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
3922 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
3923 TII->get(TargetOpcode::DBG_VALUE))
3924 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
3925 FuncInfo.ArgDbgValues.push_back(&*MIB);
3929 // VisualStudio defines setjmp as _setjmp
3930 #if defined(_MSC_VER) && defined(setjmp)
3931 #define setjmp_undefined_for_visual_studio
3935 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3936 /// we want to emit this as a call to a named external function, return the name
3937 /// otherwise lower it and return null.
3939 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
3940 DebugLoc dl = getCurDebugLoc();
3943 switch (Intrinsic) {
3945 // By default, turn this into a target intrinsic node.
3946 visitTargetIntrinsic(I, Intrinsic);
3948 case Intrinsic::vastart: visitVAStart(I); return 0;
3949 case Intrinsic::vaend: visitVAEnd(I); return 0;
3950 case Intrinsic::vacopy: visitVACopy(I); return 0;
3951 case Intrinsic::returnaddress:
3952 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3953 getValue(I.getArgOperand(0))));
3955 case Intrinsic::frameaddress:
3956 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3957 getValue(I.getArgOperand(0))));
3959 case Intrinsic::setjmp:
3960 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3961 case Intrinsic::longjmp:
3962 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3963 case Intrinsic::memcpy: {
3964 // Assert for address < 256 since we support only user defined address
3966 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
3968 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
3970 "Unknown address space");
3971 SDValue Op1 = getValue(I.getArgOperand(0));
3972 SDValue Op2 = getValue(I.getArgOperand(1));
3973 SDValue Op3 = getValue(I.getArgOperand(2));
3974 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
3975 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
3976 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
3977 I.getArgOperand(0), 0, I.getArgOperand(1), 0));
3980 case Intrinsic::memset: {
3981 // Assert for address < 256 since we support only user defined address
3983 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
3985 "Unknown address space");
3986 SDValue Op1 = getValue(I.getArgOperand(0));
3987 SDValue Op2 = getValue(I.getArgOperand(1));
3988 SDValue Op3 = getValue(I.getArgOperand(2));
3989 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
3990 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
3991 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3992 I.getArgOperand(0), 0));
3995 case Intrinsic::memmove: {
3996 // Assert for address < 256 since we support only user defined address
3998 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4000 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4002 "Unknown address space");
4003 SDValue Op1 = getValue(I.getArgOperand(0));
4004 SDValue Op2 = getValue(I.getArgOperand(1));
4005 SDValue Op3 = getValue(I.getArgOperand(2));
4006 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4007 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4009 // If the source and destination are known to not be aliases, we can
4010 // lower memmove as memcpy.
4011 uint64_t Size = -1ULL;
4012 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4013 Size = C->getZExtValue();
4014 if (AA->alias(I.getArgOperand(0), Size, I.getArgOperand(1), Size) ==
4015 AliasAnalysis::NoAlias) {
4016 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4017 false, I.getArgOperand(0), 0, I.getArgOperand(1), 0));
4021 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4022 I.getArgOperand(0), 0, I.getArgOperand(1), 0));
4025 case Intrinsic::dbg_declare: {
4026 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4027 if (!DIVariable(DI.getVariable()).Verify())
4030 MDNode *Variable = DI.getVariable();
4031 // Parameters are handled specially.
4033 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4034 const Value *Address = DI.getAddress();
4037 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4038 Address = BCI->getOperand(0);
4039 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4041 // Don't handle byval arguments or VLAs, for example.
4042 // Non-byval arguments are handled here (they refer to the stack temporary
4043 // alloca at this point).
4044 DenseMap<const AllocaInst*, int>::iterator SI =
4045 FuncInfo.StaticAllocaMap.find(AI);
4046 if (SI == FuncInfo.StaticAllocaMap.end())
4048 int FI = SI->second;
4050 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4051 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4052 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4055 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4056 // but do not always have a corresponding SDNode built. The SDNodeOrder
4057 // absolute, but not relative, values are different depending on whether
4058 // debug info exists.
4060 SDValue &N = NodeMap[Address];
4063 if (isParameter && !AI) {
4064 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4066 // Byval parameter. We have a frame index at this point.
4067 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4068 0, dl, SDNodeOrder);
4070 // Can't do anything with other non-AI cases yet. This might be a
4071 // parameter of a callee function that got inlined, for example.
4074 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4075 0, dl, SDNodeOrder);
4077 // Can't do anything with other non-AI cases yet.
4079 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4081 // This isn't useful, but it shows what we're missing.
4082 SDV = DAG.getDbgValue(Variable, UndefValue::get(Address->getType()),
4083 0, dl, SDNodeOrder);
4084 DAG.AddDbgValue(SDV, 0, isParameter);
4088 case Intrinsic::dbg_value: {
4089 const DbgValueInst &DI = cast<DbgValueInst>(I);
4090 if (!DIVariable(DI.getVariable()).Verify())
4093 MDNode *Variable = DI.getVariable();
4094 uint64_t Offset = DI.getOffset();
4095 const Value *V = DI.getValue();
4099 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4100 // but do not always have a corresponding SDNode built. The SDNodeOrder
4101 // absolute, but not relative, values are different depending on whether
4102 // debug info exists.
4105 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4106 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4107 DAG.AddDbgValue(SDV, 0, false);
4109 bool createUndef = false;
4110 // FIXME : Why not use getValue() directly ?
4111 SDValue N = NodeMap[V];
4112 if (!N.getNode() && isa<Argument>(V))
4113 // Check unused arguments map.
4114 N = UnusedArgNodeMap[V];
4116 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) {
4117 SDV = DAG.getDbgValue(Variable, N.getNode(),
4118 N.getResNo(), Offset, dl, SDNodeOrder);
4119 DAG.AddDbgValue(SDV, N.getNode(), false);
4121 } else if (isa<PHINode>(V) && !V->use_empty()) {
4122 SDValue N = getValue(V);
4124 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) {
4125 SDV = DAG.getDbgValue(Variable, N.getNode(),
4126 N.getResNo(), Offset, dl, SDNodeOrder);
4127 DAG.AddDbgValue(SDV, N.getNode(), false);
4134 // We may expand this to cover more cases. One case where we have no
4135 // data available is an unreferenced parameter; we need this fallback.
4136 SDV = DAG.getDbgValue(Variable, UndefValue::get(V->getType()),
4137 Offset, dl, SDNodeOrder);
4138 DAG.AddDbgValue(SDV, 0, false);
4142 // Build a debug info table entry.
4143 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4144 V = BCI->getOperand(0);
4145 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4146 // Don't handle byval struct arguments or VLAs, for example.
4149 DenseMap<const AllocaInst*, int>::iterator SI =
4150 FuncInfo.StaticAllocaMap.find(AI);
4151 if (SI == FuncInfo.StaticAllocaMap.end())
4153 int FI = SI->second;
4155 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4156 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4157 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4160 case Intrinsic::eh_exception: {
4161 // Insert the EXCEPTIONADDR instruction.
4162 assert(FuncInfo.MBBMap[I.getParent()]->isLandingPad() &&
4163 "Call to eh.exception not in landing pad!");
4164 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4166 Ops[0] = DAG.getRoot();
4167 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4169 DAG.setRoot(Op.getValue(1));
4173 case Intrinsic::eh_selector: {
4174 MachineBasicBlock *CallMBB = FuncInfo.MBBMap[I.getParent()];
4175 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4176 if (CallMBB->isLandingPad())
4177 AddCatchInfo(I, &MMI, CallMBB);
4180 FuncInfo.CatchInfoLost.insert(&I);
4182 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4183 unsigned Reg = TLI.getExceptionSelectorRegister();
4184 if (Reg) FuncInfo.MBBMap[I.getParent()]->addLiveIn(Reg);
4187 // Insert the EHSELECTION instruction.
4188 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4190 Ops[0] = getValue(I.getArgOperand(0));
4192 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4193 DAG.setRoot(Op.getValue(1));
4194 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4198 case Intrinsic::eh_typeid_for: {
4199 // Find the type id for the given typeinfo.
4200 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4201 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4202 Res = DAG.getConstant(TypeID, MVT::i32);
4207 case Intrinsic::eh_return_i32:
4208 case Intrinsic::eh_return_i64:
4209 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4210 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4213 getValue(I.getArgOperand(0)),
4214 getValue(I.getArgOperand(1))));
4216 case Intrinsic::eh_unwind_init:
4217 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4219 case Intrinsic::eh_dwarf_cfa: {
4220 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4221 TLI.getPointerTy());
4222 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4224 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4225 TLI.getPointerTy()),
4227 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4229 DAG.getConstant(0, TLI.getPointerTy()));
4230 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4234 case Intrinsic::eh_sjlj_callsite: {
4235 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4236 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4237 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4238 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4240 MMI.setCurrentCallSite(CI->getZExtValue());
4243 case Intrinsic::eh_sjlj_setjmp: {
4244 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4245 getValue(I.getArgOperand(0))));
4248 case Intrinsic::eh_sjlj_longjmp: {
4249 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4251 getValue(I.getArgOperand(0))));
4255 case Intrinsic::convertff:
4256 case Intrinsic::convertfsi:
4257 case Intrinsic::convertfui:
4258 case Intrinsic::convertsif:
4259 case Intrinsic::convertuif:
4260 case Intrinsic::convertss:
4261 case Intrinsic::convertsu:
4262 case Intrinsic::convertus:
4263 case Intrinsic::convertuu: {
4264 ISD::CvtCode Code = ISD::CVT_INVALID;
4265 switch (Intrinsic) {
4266 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4267 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4268 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4269 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4270 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4271 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4272 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4273 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4274 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4276 EVT DestVT = TLI.getValueType(I.getType());
4277 const Value *Op1 = I.getArgOperand(0);
4278 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4279 DAG.getValueType(DestVT),
4280 DAG.getValueType(getValue(Op1).getValueType()),
4281 getValue(I.getArgOperand(1)),
4282 getValue(I.getArgOperand(2)),
4287 case Intrinsic::sqrt:
4288 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4289 getValue(I.getArgOperand(0)).getValueType(),
4290 getValue(I.getArgOperand(0))));
4292 case Intrinsic::powi:
4293 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4294 getValue(I.getArgOperand(1)), DAG));
4296 case Intrinsic::sin:
4297 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4298 getValue(I.getArgOperand(0)).getValueType(),
4299 getValue(I.getArgOperand(0))));
4301 case Intrinsic::cos:
4302 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4303 getValue(I.getArgOperand(0)).getValueType(),
4304 getValue(I.getArgOperand(0))));
4306 case Intrinsic::log:
4309 case Intrinsic::log2:
4312 case Intrinsic::log10:
4315 case Intrinsic::exp:
4318 case Intrinsic::exp2:
4321 case Intrinsic::pow:
4324 case Intrinsic::convert_to_fp16:
4325 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4326 MVT::i16, getValue(I.getArgOperand(0))));
4328 case Intrinsic::convert_from_fp16:
4329 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4330 MVT::f32, getValue(I.getArgOperand(0))));
4332 case Intrinsic::pcmarker: {
4333 SDValue Tmp = getValue(I.getArgOperand(0));
4334 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4337 case Intrinsic::readcyclecounter: {
4338 SDValue Op = getRoot();
4339 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4340 DAG.getVTList(MVT::i64, MVT::Other),
4343 DAG.setRoot(Res.getValue(1));
4346 case Intrinsic::bswap:
4347 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4348 getValue(I.getArgOperand(0)).getValueType(),
4349 getValue(I.getArgOperand(0))));
4351 case Intrinsic::cttz: {
4352 SDValue Arg = getValue(I.getArgOperand(0));
4353 EVT Ty = Arg.getValueType();
4354 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4357 case Intrinsic::ctlz: {
4358 SDValue Arg = getValue(I.getArgOperand(0));
4359 EVT Ty = Arg.getValueType();
4360 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4363 case Intrinsic::ctpop: {
4364 SDValue Arg = getValue(I.getArgOperand(0));
4365 EVT Ty = Arg.getValueType();
4366 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4369 case Intrinsic::stacksave: {
4370 SDValue Op = getRoot();
4371 Res = DAG.getNode(ISD::STACKSAVE, dl,
4372 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4374 DAG.setRoot(Res.getValue(1));
4377 case Intrinsic::stackrestore: {
4378 Res = getValue(I.getArgOperand(0));
4379 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4382 case Intrinsic::stackprotector: {
4383 // Emit code into the DAG to store the stack guard onto the stack.
4384 MachineFunction &MF = DAG.getMachineFunction();
4385 MachineFrameInfo *MFI = MF.getFrameInfo();
4386 EVT PtrTy = TLI.getPointerTy();
4388 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4389 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4391 int FI = FuncInfo.StaticAllocaMap[Slot];
4392 MFI->setStackProtectorIndex(FI);
4394 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4396 // Store the stack protector onto the stack.
4397 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4398 PseudoSourceValue::getFixedStack(FI),
4404 case Intrinsic::objectsize: {
4405 // If we don't know by now, we're never going to know.
4406 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4408 assert(CI && "Non-constant type in __builtin_object_size?");
4410 SDValue Arg = getValue(I.getCalledValue());
4411 EVT Ty = Arg.getValueType();
4414 Res = DAG.getConstant(-1ULL, Ty);
4416 Res = DAG.getConstant(0, Ty);
4421 case Intrinsic::var_annotation:
4422 // Discard annotate attributes
4425 case Intrinsic::init_trampoline: {
4426 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4430 Ops[1] = getValue(I.getArgOperand(0));
4431 Ops[2] = getValue(I.getArgOperand(1));
4432 Ops[3] = getValue(I.getArgOperand(2));
4433 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4434 Ops[5] = DAG.getSrcValue(F);
4436 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4437 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4441 DAG.setRoot(Res.getValue(1));
4444 case Intrinsic::gcroot:
4446 const Value *Alloca = I.getArgOperand(0);
4447 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4449 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4450 GFI->addStackRoot(FI->getIndex(), TypeMap);
4453 case Intrinsic::gcread:
4454 case Intrinsic::gcwrite:
4455 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4457 case Intrinsic::flt_rounds:
4458 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4460 case Intrinsic::trap:
4461 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4463 case Intrinsic::uadd_with_overflow:
4464 return implVisitAluOverflow(I, ISD::UADDO);
4465 case Intrinsic::sadd_with_overflow:
4466 return implVisitAluOverflow(I, ISD::SADDO);
4467 case Intrinsic::usub_with_overflow:
4468 return implVisitAluOverflow(I, ISD::USUBO);
4469 case Intrinsic::ssub_with_overflow:
4470 return implVisitAluOverflow(I, ISD::SSUBO);
4471 case Intrinsic::umul_with_overflow:
4472 return implVisitAluOverflow(I, ISD::UMULO);
4473 case Intrinsic::smul_with_overflow:
4474 return implVisitAluOverflow(I, ISD::SMULO);
4476 case Intrinsic::prefetch: {
4479 Ops[1] = getValue(I.getArgOperand(0));
4480 Ops[2] = getValue(I.getArgOperand(1));
4481 Ops[3] = getValue(I.getArgOperand(2));
4482 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4486 case Intrinsic::memory_barrier: {
4489 for (int x = 1; x < 6; ++x)
4490 Ops[x] = getValue(I.getArgOperand(x - 1));
4492 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4495 case Intrinsic::atomic_cmp_swap: {
4496 SDValue Root = getRoot();
4498 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4499 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4501 getValue(I.getArgOperand(0)),
4502 getValue(I.getArgOperand(1)),
4503 getValue(I.getArgOperand(2)),
4504 I.getArgOperand(0));
4506 DAG.setRoot(L.getValue(1));
4509 case Intrinsic::atomic_load_add:
4510 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4511 case Intrinsic::atomic_load_sub:
4512 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4513 case Intrinsic::atomic_load_or:
4514 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4515 case Intrinsic::atomic_load_xor:
4516 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4517 case Intrinsic::atomic_load_and:
4518 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4519 case Intrinsic::atomic_load_nand:
4520 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4521 case Intrinsic::atomic_load_max:
4522 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4523 case Intrinsic::atomic_load_min:
4524 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4525 case Intrinsic::atomic_load_umin:
4526 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4527 case Intrinsic::atomic_load_umax:
4528 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4529 case Intrinsic::atomic_swap:
4530 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4532 case Intrinsic::invariant_start:
4533 case Intrinsic::lifetime_start:
4534 // Discard region information.
4535 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4537 case Intrinsic::invariant_end:
4538 case Intrinsic::lifetime_end:
4539 // Discard region information.
4544 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4546 MachineBasicBlock *LandingPad) {
4547 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4548 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4549 const Type *RetTy = FTy->getReturnType();
4550 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4551 MCSymbol *BeginLabel = 0;
4553 TargetLowering::ArgListTy Args;
4554 TargetLowering::ArgListEntry Entry;
4555 Args.reserve(CS.arg_size());
4557 // Check whether the function can return without sret-demotion.
4558 SmallVector<EVT, 4> OutVTs;
4559 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4560 SmallVector<uint64_t, 4> Offsets;
4561 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4562 OutVTs, OutsFlags, TLI, &Offsets);
4564 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4565 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4567 SDValue DemoteStackSlot;
4569 if (!CanLowerReturn) {
4570 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4571 FTy->getReturnType());
4572 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4573 FTy->getReturnType());
4574 MachineFunction &MF = DAG.getMachineFunction();
4575 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4576 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4578 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4579 Entry.Node = DemoteStackSlot;
4580 Entry.Ty = StackSlotPtrType;
4581 Entry.isSExt = false;
4582 Entry.isZExt = false;
4583 Entry.isInReg = false;
4584 Entry.isSRet = true;
4585 Entry.isNest = false;
4586 Entry.isByVal = false;
4587 Entry.Alignment = Align;
4588 Args.push_back(Entry);
4589 RetTy = Type::getVoidTy(FTy->getContext());
4592 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4594 SDValue ArgNode = getValue(*i);
4595 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4597 unsigned attrInd = i - CS.arg_begin() + 1;
4598 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4599 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4600 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4601 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4602 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4603 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4604 Entry.Alignment = CS.getParamAlignment(attrInd);
4605 Args.push_back(Entry);
4609 // Insert a label before the invoke call to mark the try range. This can be
4610 // used to detect deletion of the invoke via the MachineModuleInfo.
4611 BeginLabel = MMI.getContext().CreateTempSymbol();
4613 // For SjLj, keep track of which landing pads go with which invokes
4614 // so as to maintain the ordering of pads in the LSDA.
4615 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4616 if (CallSiteIndex) {
4617 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4618 // Now that the call site is handled, stop tracking it.
4619 MMI.setCurrentCallSite(0);
4622 // Both PendingLoads and PendingExports must be flushed here;
4623 // this call might not return.
4625 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4628 // Check if target-independent constraints permit a tail call here.
4629 // Target-dependent constraints are checked within TLI.LowerCallTo.
4631 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4634 std::pair<SDValue,SDValue> Result =
4635 TLI.LowerCallTo(getRoot(), RetTy,
4636 CS.paramHasAttr(0, Attribute::SExt),
4637 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4638 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4639 CS.getCallingConv(),
4641 !CS.getInstruction()->use_empty(),
4642 Callee, Args, DAG, getCurDebugLoc());
4643 assert((isTailCall || Result.second.getNode()) &&
4644 "Non-null chain expected with non-tail call!");
4645 assert((Result.second.getNode() || !Result.first.getNode()) &&
4646 "Null value expected with tail call!");
4647 if (Result.first.getNode()) {
4648 setValue(CS.getInstruction(), Result.first);
4649 } else if (!CanLowerReturn && Result.second.getNode()) {
4650 // The instruction result is the result of loading from the
4651 // hidden sret parameter.
4652 SmallVector<EVT, 1> PVTs;
4653 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4655 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4656 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4657 EVT PtrVT = PVTs[0];
4658 unsigned NumValues = OutVTs.size();
4659 SmallVector<SDValue, 4> Values(NumValues);
4660 SmallVector<SDValue, 4> Chains(NumValues);
4662 for (unsigned i = 0; i < NumValues; ++i) {
4663 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4665 DAG.getConstant(Offsets[i], PtrVT));
4666 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4667 Add, NULL, Offsets[i], false, false, 1);
4669 Chains[i] = L.getValue(1);
4672 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4673 MVT::Other, &Chains[0], NumValues);
4674 PendingLoads.push_back(Chain);
4676 // Collect the legal value parts into potentially illegal values
4677 // that correspond to the original function's return values.
4678 SmallVector<EVT, 4> RetTys;
4679 RetTy = FTy->getReturnType();
4680 ComputeValueVTs(TLI, RetTy, RetTys);
4681 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4682 SmallVector<SDValue, 4> ReturnValues;
4683 unsigned CurReg = 0;
4684 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4686 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4687 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4689 SDValue ReturnValue =
4690 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4691 RegisterVT, VT, AssertOp);
4692 ReturnValues.push_back(ReturnValue);
4696 setValue(CS.getInstruction(),
4697 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4698 DAG.getVTList(&RetTys[0], RetTys.size()),
4699 &ReturnValues[0], ReturnValues.size()));
4703 // As a special case, a null chain means that a tail call has been emitted and
4704 // the DAG root is already updated.
4705 if (Result.second.getNode())
4706 DAG.setRoot(Result.second);
4711 // Insert a label at the end of the invoke call to mark the try range. This
4712 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4713 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
4714 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4716 // Inform MachineModuleInfo of range.
4717 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
4721 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4722 /// value is equal or not-equal to zero.
4723 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
4724 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
4726 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4727 if (IC->isEquality())
4728 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4729 if (C->isNullValue())
4731 // Unknown instruction.
4737 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
4739 SelectionDAGBuilder &Builder) {
4741 // Check to see if this load can be trivially constant folded, e.g. if the
4742 // input is from a string literal.
4743 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4744 // Cast pointer to the type we really want to load.
4745 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
4746 PointerType::getUnqual(LoadTy));
4748 if (const Constant *LoadCst =
4749 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
4751 return Builder.getValue(LoadCst);
4754 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4755 // still constant memory, the input chain can be the entry node.
4757 bool ConstantMemory = false;
4759 // Do not serialize (non-volatile) loads of constant memory with anything.
4760 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4761 Root = Builder.DAG.getEntryNode();
4762 ConstantMemory = true;
4764 // Do not serialize non-volatile loads against each other.
4765 Root = Builder.DAG.getRoot();
4768 SDValue Ptr = Builder.getValue(PtrVal);
4769 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4770 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4772 false /*nontemporal*/, 1 /* align=1 */);
4774 if (!ConstantMemory)
4775 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4780 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4781 /// If so, return true and lower it, otherwise return false and it will be
4782 /// lowered like a normal call.
4783 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
4784 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4785 if (I.getNumArgOperands() != 3)
4788 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
4789 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4790 !I.getArgOperand(2)->getType()->isIntegerTy() ||
4791 !I.getType()->isIntegerTy())
4794 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
4796 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4797 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
4798 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4799 bool ActuallyDoIt = true;
4802 switch (Size->getZExtValue()) {
4804 LoadVT = MVT::Other;
4806 ActuallyDoIt = false;
4810 LoadTy = Type::getInt16Ty(Size->getContext());
4814 LoadTy = Type::getInt32Ty(Size->getContext());
4818 LoadTy = Type::getInt64Ty(Size->getContext());
4822 LoadVT = MVT::v4i32;
4823 LoadTy = Type::getInt32Ty(Size->getContext());
4824 LoadTy = VectorType::get(LoadTy, 4);
4829 // This turns into unaligned loads. We only do this if the target natively
4830 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4831 // we'll only produce a small number of byte loads.
4833 // Require that we can find a legal MVT, and only do this if the target
4834 // supports unaligned loads of that type. Expanding into byte loads would
4836 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4837 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4838 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4839 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4840 ActuallyDoIt = false;
4844 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4845 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
4847 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4849 EVT CallVT = TLI.getValueType(I.getType(), true);
4850 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4860 void SelectionDAGBuilder::visitCall(const CallInst &I) {
4861 const char *RenameFn = 0;
4862 if (Function *F = I.getCalledFunction()) {
4863 if (F->isDeclaration()) {
4864 const TargetIntrinsicInfo *II = TM.getIntrinsicInfo();
4866 if (unsigned IID = II->getIntrinsicID(F)) {
4867 RenameFn = visitIntrinsicCall(I, IID);
4872 if (unsigned IID = F->getIntrinsicID()) {
4873 RenameFn = visitIntrinsicCall(I, IID);
4879 // Check for well-known libc/libm calls. If the function is internal, it
4880 // can't be a library call.
4881 if (!F->hasLocalLinkage() && F->hasName()) {
4882 StringRef Name = F->getName();
4883 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
4884 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
4885 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4886 I.getType() == I.getArgOperand(0)->getType() &&
4887 I.getType() == I.getArgOperand(1)->getType()) {
4888 SDValue LHS = getValue(I.getArgOperand(0));
4889 SDValue RHS = getValue(I.getArgOperand(1));
4890 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4891 LHS.getValueType(), LHS, RHS));
4894 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4895 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4896 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4897 I.getType() == I.getArgOperand(0)->getType()) {
4898 SDValue Tmp = getValue(I.getArgOperand(0));
4899 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4900 Tmp.getValueType(), Tmp));
4903 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4904 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4905 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4906 I.getType() == I.getArgOperand(0)->getType() &&
4907 I.onlyReadsMemory()) {
4908 SDValue Tmp = getValue(I.getArgOperand(0));
4909 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4910 Tmp.getValueType(), Tmp));
4913 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4914 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4915 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4916 I.getType() == I.getArgOperand(0)->getType() &&
4917 I.onlyReadsMemory()) {
4918 SDValue Tmp = getValue(I.getArgOperand(0));
4919 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4920 Tmp.getValueType(), Tmp));
4923 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4924 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
4925 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
4926 I.getType() == I.getArgOperand(0)->getType() &&
4927 I.onlyReadsMemory()) {
4928 SDValue Tmp = getValue(I.getArgOperand(0));
4929 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4930 Tmp.getValueType(), Tmp));
4933 } else if (Name == "memcmp") {
4934 if (visitMemCmpCall(I))
4938 } else if (isa<InlineAsm>(I.getCalledValue())) {
4945 Callee = getValue(I.getCalledValue());
4947 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4949 // Check if we can potentially perform a tail call. More detailed checking is
4950 // be done within LowerCallTo, after more information about the call is known.
4951 LowerCallTo(&I, Callee, I.isTailCall());
4956 /// AsmOperandInfo - This contains information for each constraint that we are
4958 class LLVM_LIBRARY_VISIBILITY SDISelAsmOperandInfo :
4959 public TargetLowering::AsmOperandInfo {
4961 /// CallOperand - If this is the result output operand or a clobber
4962 /// this is null, otherwise it is the incoming operand to the CallInst.
4963 /// This gets modified as the asm is processed.
4964 SDValue CallOperand;
4966 /// AssignedRegs - If this is a register or register class operand, this
4967 /// contains the set of register corresponding to the operand.
4968 RegsForValue AssignedRegs;
4970 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4971 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4974 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4975 /// busy in OutputRegs/InputRegs.
4976 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4977 std::set<unsigned> &OutputRegs,
4978 std::set<unsigned> &InputRegs,
4979 const TargetRegisterInfo &TRI) const {
4981 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4982 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4985 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4986 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4990 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4991 /// corresponds to. If there is no Value* for this operand, it returns
4993 EVT getCallOperandValEVT(LLVMContext &Context,
4994 const TargetLowering &TLI,
4995 const TargetData *TD) const {
4996 if (CallOperandVal == 0) return MVT::Other;
4998 if (isa<BasicBlock>(CallOperandVal))
4999 return TLI.getPointerTy();
5001 const llvm::Type *OpTy = CallOperandVal->getType();
5003 // If this is an indirect operand, the operand is a pointer to the
5006 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5008 report_fatal_error("Indirect operand for inline asm not a pointer!");
5009 OpTy = PtrTy->getElementType();
5012 // If OpTy is not a single value, it may be a struct/union that we
5013 // can tile with integers.
5014 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5015 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5024 OpTy = IntegerType::get(Context, BitSize);
5029 return TLI.getValueType(OpTy, true);
5033 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5035 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5036 const TargetRegisterInfo &TRI) {
5037 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5039 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5040 for (; *Aliases; ++Aliases)
5041 Regs.insert(*Aliases);
5045 } // end llvm namespace.
5047 /// isAllocatableRegister - If the specified register is safe to allocate,
5048 /// i.e. it isn't a stack pointer or some other special register, return the
5049 /// register class for the register. Otherwise, return null.
5050 static const TargetRegisterClass *
5051 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5052 const TargetLowering &TLI,
5053 const TargetRegisterInfo *TRI) {
5054 EVT FoundVT = MVT::Other;
5055 const TargetRegisterClass *FoundRC = 0;
5056 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5057 E = TRI->regclass_end(); RCI != E; ++RCI) {
5058 EVT ThisVT = MVT::Other;
5060 const TargetRegisterClass *RC = *RCI;
5061 // If none of the value types for this register class are valid, we
5062 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5063 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5065 if (TLI.isTypeLegal(*I)) {
5066 // If we have already found this register in a different register class,
5067 // choose the one with the largest VT specified. For example, on
5068 // PowerPC, we favor f64 register classes over f32.
5069 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5076 if (ThisVT == MVT::Other) continue;
5078 // NOTE: This isn't ideal. In particular, this might allocate the
5079 // frame pointer in functions that need it (due to them not being taken
5080 // out of allocation, because a variable sized allocation hasn't been seen
5081 // yet). This is a slight code pessimization, but should still work.
5082 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5083 E = RC->allocation_order_end(MF); I != E; ++I)
5085 // We found a matching register class. Keep looking at others in case
5086 // we find one with larger registers that this physreg is also in.
5095 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5096 /// specified operand. We prefer to assign virtual registers, to allow the
5097 /// register allocator to handle the assignment process. However, if the asm
5098 /// uses features that we can't model on machineinstrs, we have SDISel do the
5099 /// allocation. This produces generally horrible, but correct, code.
5101 /// OpInfo describes the operand.
5102 /// Input and OutputRegs are the set of already allocated physical registers.
5104 void SelectionDAGBuilder::
5105 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5106 std::set<unsigned> &OutputRegs,
5107 std::set<unsigned> &InputRegs) {
5108 LLVMContext &Context = FuncInfo.Fn->getContext();
5110 // Compute whether this value requires an input register, an output register,
5112 bool isOutReg = false;
5113 bool isInReg = false;
5114 switch (OpInfo.Type) {
5115 case InlineAsm::isOutput:
5118 // If there is an input constraint that matches this, we need to reserve
5119 // the input register so no other inputs allocate to it.
5120 isInReg = OpInfo.hasMatchingInput();
5122 case InlineAsm::isInput:
5126 case InlineAsm::isClobber:
5133 MachineFunction &MF = DAG.getMachineFunction();
5134 SmallVector<unsigned, 4> Regs;
5136 // If this is a constraint for a single physreg, or a constraint for a
5137 // register class, find it.
5138 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5139 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5140 OpInfo.ConstraintVT);
5142 unsigned NumRegs = 1;
5143 if (OpInfo.ConstraintVT != MVT::Other) {
5144 // If this is a FP input in an integer register (or visa versa) insert a bit
5145 // cast of the input value. More generally, handle any case where the input
5146 // value disagrees with the register class we plan to stick this in.
5147 if (OpInfo.Type == InlineAsm::isInput &&
5148 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5149 // Try to convert to the first EVT that the reg class contains. If the
5150 // types are identical size, use a bitcast to convert (e.g. two differing
5152 EVT RegVT = *PhysReg.second->vt_begin();
5153 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5154 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5155 RegVT, OpInfo.CallOperand);
5156 OpInfo.ConstraintVT = RegVT;
5157 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5158 // If the input is a FP value and we want it in FP registers, do a
5159 // bitcast to the corresponding integer type. This turns an f64 value
5160 // into i64, which can be passed with two i32 values on a 32-bit
5162 RegVT = EVT::getIntegerVT(Context,
5163 OpInfo.ConstraintVT.getSizeInBits());
5164 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5165 RegVT, OpInfo.CallOperand);
5166 OpInfo.ConstraintVT = RegVT;
5170 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5174 EVT ValueVT = OpInfo.ConstraintVT;
5176 // If this is a constraint for a specific physical register, like {r17},
5178 if (unsigned AssignedReg = PhysReg.first) {
5179 const TargetRegisterClass *RC = PhysReg.second;
5180 if (OpInfo.ConstraintVT == MVT::Other)
5181 ValueVT = *RC->vt_begin();
5183 // Get the actual register value type. This is important, because the user
5184 // may have asked for (e.g.) the AX register in i32 type. We need to
5185 // remember that AX is actually i16 to get the right extension.
5186 RegVT = *RC->vt_begin();
5188 // This is a explicit reference to a physical register.
5189 Regs.push_back(AssignedReg);
5191 // If this is an expanded reference, add the rest of the regs to Regs.
5193 TargetRegisterClass::iterator I = RC->begin();
5194 for (; *I != AssignedReg; ++I)
5195 assert(I != RC->end() && "Didn't find reg!");
5197 // Already added the first reg.
5199 for (; NumRegs; --NumRegs, ++I) {
5200 assert(I != RC->end() && "Ran out of registers to allocate!");
5205 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5206 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5207 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5211 // Otherwise, if this was a reference to an LLVM register class, create vregs
5212 // for this reference.
5213 if (const TargetRegisterClass *RC = PhysReg.second) {
5214 RegVT = *RC->vt_begin();
5215 if (OpInfo.ConstraintVT == MVT::Other)
5218 // Create the appropriate number of virtual registers.
5219 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5220 for (; NumRegs; --NumRegs)
5221 Regs.push_back(RegInfo.createVirtualRegister(RC));
5223 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5227 // This is a reference to a register class that doesn't directly correspond
5228 // to an LLVM register class. Allocate NumRegs consecutive, available,
5229 // registers from the class.
5230 std::vector<unsigned> RegClassRegs
5231 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5232 OpInfo.ConstraintVT);
5234 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5235 unsigned NumAllocated = 0;
5236 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5237 unsigned Reg = RegClassRegs[i];
5238 // See if this register is available.
5239 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5240 (isInReg && InputRegs.count(Reg))) { // Already used.
5241 // Make sure we find consecutive registers.
5246 // Check to see if this register is allocatable (i.e. don't give out the
5248 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5249 if (!RC) { // Couldn't allocate this register.
5250 // Reset NumAllocated to make sure we return consecutive registers.
5255 // Okay, this register is good, we can use it.
5258 // If we allocated enough consecutive registers, succeed.
5259 if (NumAllocated == NumRegs) {
5260 unsigned RegStart = (i-NumAllocated)+1;
5261 unsigned RegEnd = i+1;
5262 // Mark all of the allocated registers used.
5263 for (unsigned i = RegStart; i != RegEnd; ++i)
5264 Regs.push_back(RegClassRegs[i]);
5266 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
5267 OpInfo.ConstraintVT);
5268 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5273 // Otherwise, we couldn't allocate enough registers for this.
5276 /// visitInlineAsm - Handle a call to an InlineAsm object.
5278 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5279 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5281 /// ConstraintOperands - Information about all of the constraints.
5282 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5284 std::set<unsigned> OutputRegs, InputRegs;
5286 // Do a prepass over the constraints, canonicalizing them, and building up the
5287 // ConstraintOperands list.
5288 std::vector<InlineAsm::ConstraintInfo>
5289 ConstraintInfos = IA->ParseConstraints();
5291 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5293 SDValue Chain, Flag;
5295 // We won't need to flush pending loads if this asm doesn't touch
5296 // memory and is nonvolatile.
5297 if (hasMemory || IA->hasSideEffects())
5300 Chain = DAG.getRoot();
5302 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5303 unsigned ResNo = 0; // ResNo - The result number of the next output.
5304 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5305 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5306 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5308 EVT OpVT = MVT::Other;
5310 // Compute the value type for each operand.
5311 switch (OpInfo.Type) {
5312 case InlineAsm::isOutput:
5313 // Indirect outputs just consume an argument.
5314 if (OpInfo.isIndirect) {
5315 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5319 // The return value of the call is this value. As such, there is no
5320 // corresponding argument.
5321 assert(!CS.getType()->isVoidTy() &&
5323 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5324 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5326 assert(ResNo == 0 && "Asm only has one result!");
5327 OpVT = TLI.getValueType(CS.getType());
5331 case InlineAsm::isInput:
5332 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5334 case InlineAsm::isClobber:
5339 // If this is an input or an indirect output, process the call argument.
5340 // BasicBlocks are labels, currently appearing only in asm's.
5341 if (OpInfo.CallOperandVal) {
5342 // Strip bitcasts, if any. This mostly comes up for functions.
5343 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5345 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5346 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5348 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5351 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5354 OpInfo.ConstraintVT = OpVT;
5357 // Second pass over the constraints: compute which constraint option to use
5358 // and assign registers to constraints that want a specific physreg.
5359 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5360 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5362 // If this is an output operand with a matching input operand, look up the
5363 // matching input. If their types mismatch, e.g. one is an integer, the
5364 // other is floating point, or their sizes are different, flag it as an
5366 if (OpInfo.hasMatchingInput()) {
5367 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5369 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5370 if ((OpInfo.ConstraintVT.isInteger() !=
5371 Input.ConstraintVT.isInteger()) ||
5372 (OpInfo.ConstraintVT.getSizeInBits() !=
5373 Input.ConstraintVT.getSizeInBits())) {
5374 report_fatal_error("Unsupported asm: input constraint"
5375 " with a matching output constraint of"
5376 " incompatible type!");
5378 Input.ConstraintVT = OpInfo.ConstraintVT;
5382 // Compute the constraint code and ConstraintType to use.
5383 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5385 // If this is a memory input, and if the operand is not indirect, do what we
5386 // need to to provide an address for the memory input.
5387 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5388 !OpInfo.isIndirect) {
5389 assert(OpInfo.Type == InlineAsm::isInput &&
5390 "Can only indirectify direct input operands!");
5392 // Memory operands really want the address of the value. If we don't have
5393 // an indirect input, put it in the constpool if we can, otherwise spill
5394 // it to a stack slot.
5396 // If the operand is a float, integer, or vector constant, spill to a
5397 // constant pool entry to get its address.
5398 const Value *OpVal = OpInfo.CallOperandVal;
5399 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5400 isa<ConstantVector>(OpVal)) {
5401 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5402 TLI.getPointerTy());
5404 // Otherwise, create a stack slot and emit a store to it before the
5406 const Type *Ty = OpVal->getType();
5407 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5408 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5409 MachineFunction &MF = DAG.getMachineFunction();
5410 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5411 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5412 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5413 OpInfo.CallOperand, StackSlot, NULL, 0,
5415 OpInfo.CallOperand = StackSlot;
5418 // There is no longer a Value* corresponding to this operand.
5419 OpInfo.CallOperandVal = 0;
5421 // It is now an indirect operand.
5422 OpInfo.isIndirect = true;
5425 // If this constraint is for a specific register, allocate it before
5427 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5428 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5431 ConstraintInfos.clear();
5433 // Second pass - Loop over all of the operands, assigning virtual or physregs
5434 // to register class operands.
5435 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5436 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5438 // C_Register operands have already been allocated, Other/Memory don't need
5440 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5441 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5444 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5445 std::vector<SDValue> AsmNodeOperands;
5446 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5447 AsmNodeOperands.push_back(
5448 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5449 TLI.getPointerTy()));
5451 // If we have a !srcloc metadata node associated with it, we want to attach
5452 // this to the ultimately generated inline asm machineinstr. To do this, we
5453 // pass in the third operand as this (potentially null) inline asm MDNode.
5454 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5455 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5457 // Loop over all of the inputs, copying the operand values into the
5458 // appropriate registers and processing the output regs.
5459 RegsForValue RetValRegs;
5461 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5462 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5464 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5465 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5467 switch (OpInfo.Type) {
5468 case InlineAsm::isOutput: {
5469 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5470 OpInfo.ConstraintType != TargetLowering::C_Register) {
5471 // Memory output, or 'other' output (e.g. 'X' constraint).
5472 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5474 // Add information to the INLINEASM node to know about this output.
5475 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5476 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5477 TLI.getPointerTy()));
5478 AsmNodeOperands.push_back(OpInfo.CallOperand);
5482 // Otherwise, this is a register or register class output.
5484 // Copy the output from the appropriate register. Find a register that
5486 if (OpInfo.AssignedRegs.Regs.empty())
5487 report_fatal_error("Couldn't allocate output reg for constraint '" +
5488 Twine(OpInfo.ConstraintCode) + "'!");
5490 // If this is an indirect operand, store through the pointer after the
5492 if (OpInfo.isIndirect) {
5493 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5494 OpInfo.CallOperandVal));
5496 // This is the result value of the call.
5497 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5498 // Concatenate this output onto the outputs list.
5499 RetValRegs.append(OpInfo.AssignedRegs);
5502 // Add information to the INLINEASM node to know that this register is
5504 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5505 InlineAsm::Kind_RegDefEarlyClobber :
5506 InlineAsm::Kind_RegDef,
5513 case InlineAsm::isInput: {
5514 SDValue InOperandVal = OpInfo.CallOperand;
5516 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5517 // If this is required to match an output register we have already set,
5518 // just use its register.
5519 unsigned OperandNo = OpInfo.getMatchedOperand();
5521 // Scan until we find the definition we already emitted of this operand.
5522 // When we find it, create a RegsForValue operand.
5523 unsigned CurOp = InlineAsm::Op_FirstOperand;
5524 for (; OperandNo; --OperandNo) {
5525 // Advance to the next operand.
5527 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5528 assert((InlineAsm::isRegDefKind(OpFlag) ||
5529 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5530 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5531 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5535 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5536 if (InlineAsm::isRegDefKind(OpFlag) ||
5537 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5538 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5539 if (OpInfo.isIndirect) {
5540 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5541 LLVMContext &Ctx = *DAG.getContext();
5542 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5543 " don't know how to handle tied "
5544 "indirect register inputs");
5547 RegsForValue MatchedRegs;
5548 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5549 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5550 MatchedRegs.RegVTs.push_back(RegVT);
5551 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5552 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5554 MatchedRegs.Regs.push_back
5555 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5557 // Use the produced MatchedRegs object to
5558 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5560 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5561 true, OpInfo.getMatchedOperand(),
5562 DAG, AsmNodeOperands);
5566 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5567 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5568 "Unexpected number of operands");
5569 // Add information to the INLINEASM node to know about this input.
5570 // See InlineAsm.h isUseOperandTiedToDef.
5571 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5572 OpInfo.getMatchedOperand());
5573 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5574 TLI.getPointerTy()));
5575 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5579 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5580 assert(!OpInfo.isIndirect &&
5581 "Don't know how to handle indirect other inputs yet!");
5583 std::vector<SDValue> Ops;
5584 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5587 report_fatal_error("Invalid operand for inline asm constraint '" +
5588 Twine(OpInfo.ConstraintCode) + "'!");
5590 // Add information to the INLINEASM node to know about this input.
5591 unsigned ResOpType =
5592 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5593 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5594 TLI.getPointerTy()));
5595 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5599 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5600 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5601 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5602 "Memory operands expect pointer values");
5604 // Add information to the INLINEASM node to know about this input.
5605 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5606 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5607 TLI.getPointerTy()));
5608 AsmNodeOperands.push_back(InOperandVal);
5612 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5613 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5614 "Unknown constraint type!");
5615 assert(!OpInfo.isIndirect &&
5616 "Don't know how to handle indirect register inputs yet!");
5618 // Copy the input into the appropriate registers.
5619 if (OpInfo.AssignedRegs.Regs.empty() ||
5620 !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
5621 report_fatal_error("Couldn't allocate input reg for constraint '" +
5622 Twine(OpInfo.ConstraintCode) + "'!");
5624 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5627 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5628 DAG, AsmNodeOperands);
5631 case InlineAsm::isClobber: {
5632 // Add the clobbered value to the operand list, so that the register
5633 // allocator is aware that the physreg got clobbered.
5634 if (!OpInfo.AssignedRegs.Regs.empty())
5635 OpInfo.AssignedRegs.AddInlineAsmOperands(
5636 InlineAsm::Kind_RegDefEarlyClobber,
5644 // Finish up input operands. Set the input chain and add the flag last.
5645 AsmNodeOperands[0] = Chain;
5646 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5648 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5649 DAG.getVTList(MVT::Other, MVT::Flag),
5650 &AsmNodeOperands[0], AsmNodeOperands.size());
5651 Flag = Chain.getValue(1);
5653 // If this asm returns a register value, copy the result from that register
5654 // and set it as the value of the call.
5655 if (!RetValRegs.Regs.empty()) {
5656 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5659 // FIXME: Why don't we do this for inline asms with MRVs?
5660 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5661 EVT ResultType = TLI.getValueType(CS.getType());
5663 // If any of the results of the inline asm is a vector, it may have the
5664 // wrong width/num elts. This can happen for register classes that can
5665 // contain multiple different value types. The preg or vreg allocated may
5666 // not have the same VT as was expected. Convert it to the right type
5667 // with bit_convert.
5668 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5669 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5672 } else if (ResultType != Val.getValueType() &&
5673 ResultType.isInteger() && Val.getValueType().isInteger()) {
5674 // If a result value was tied to an input value, the computed result may
5675 // have a wider width than the expected result. Extract the relevant
5677 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5680 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5683 setValue(CS.getInstruction(), Val);
5684 // Don't need to use this as a chain in this case.
5685 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5689 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
5691 // Process indirect outputs, first output all of the flagged copies out of
5693 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5694 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5695 const Value *Ptr = IndirectStoresToEmit[i].second;
5696 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5698 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5701 // Emit the non-flagged stores from the physregs.
5702 SmallVector<SDValue, 8> OutChains;
5703 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5704 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5705 StoresToEmit[i].first,
5706 getValue(StoresToEmit[i].second),
5707 StoresToEmit[i].second, 0,
5709 OutChains.push_back(Val);
5712 if (!OutChains.empty())
5713 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5714 &OutChains[0], OutChains.size());
5719 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
5720 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5721 MVT::Other, getRoot(),
5722 getValue(I.getArgOperand(0)),
5723 DAG.getSrcValue(I.getArgOperand(0))));
5726 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
5727 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5728 getRoot(), getValue(I.getOperand(0)),
5729 DAG.getSrcValue(I.getOperand(0)));
5731 DAG.setRoot(V.getValue(1));
5734 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
5735 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5736 MVT::Other, getRoot(),
5737 getValue(I.getArgOperand(0)),
5738 DAG.getSrcValue(I.getArgOperand(0))));
5741 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
5742 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5743 MVT::Other, getRoot(),
5744 getValue(I.getArgOperand(0)),
5745 getValue(I.getArgOperand(1)),
5746 DAG.getSrcValue(I.getArgOperand(0)),
5747 DAG.getSrcValue(I.getArgOperand(1))));
5750 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5751 /// implementation, which just calls LowerCall.
5752 /// FIXME: When all targets are
5753 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5754 std::pair<SDValue, SDValue>
5755 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5756 bool RetSExt, bool RetZExt, bool isVarArg,
5757 bool isInreg, unsigned NumFixedArgs,
5758 CallingConv::ID CallConv, bool isTailCall,
5759 bool isReturnValueUsed,
5761 ArgListTy &Args, SelectionDAG &DAG,
5762 DebugLoc dl) const {
5763 // Handle all of the outgoing arguments.
5764 SmallVector<ISD::OutputArg, 32> Outs;
5765 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5766 SmallVector<EVT, 4> ValueVTs;
5767 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5768 for (unsigned Value = 0, NumValues = ValueVTs.size();
5769 Value != NumValues; ++Value) {
5770 EVT VT = ValueVTs[Value];
5771 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5772 SDValue Op = SDValue(Args[i].Node.getNode(),
5773 Args[i].Node.getResNo() + Value);
5774 ISD::ArgFlagsTy Flags;
5775 unsigned OriginalAlignment =
5776 getTargetData()->getABITypeAlignment(ArgTy);
5782 if (Args[i].isInReg)
5786 if (Args[i].isByVal) {
5788 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5789 const Type *ElementTy = Ty->getElementType();
5790 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5791 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5792 // For ByVal, alignment should come from FE. BE will guess if this
5793 // info is not there but there are cases it cannot get right.
5794 if (Args[i].Alignment)
5795 FrameAlign = Args[i].Alignment;
5796 Flags.setByValAlign(FrameAlign);
5797 Flags.setByValSize(FrameSize);
5801 Flags.setOrigAlign(OriginalAlignment);
5803 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5804 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5805 SmallVector<SDValue, 4> Parts(NumParts);
5806 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5809 ExtendKind = ISD::SIGN_EXTEND;
5810 else if (Args[i].isZExt)
5811 ExtendKind = ISD::ZERO_EXTEND;
5813 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
5814 PartVT, ExtendKind);
5816 for (unsigned j = 0; j != NumParts; ++j) {
5817 // if it isn't first piece, alignment must be 1
5818 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5819 if (NumParts > 1 && j == 0)
5820 MyFlags.Flags.setSplit();
5822 MyFlags.Flags.setOrigAlign(1);
5824 Outs.push_back(MyFlags);
5829 // Handle the incoming return values from the call.
5830 SmallVector<ISD::InputArg, 32> Ins;
5831 SmallVector<EVT, 4> RetTys;
5832 ComputeValueVTs(*this, RetTy, RetTys);
5833 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5835 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5836 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5837 for (unsigned i = 0; i != NumRegs; ++i) {
5838 ISD::InputArg MyFlags;
5839 MyFlags.VT = RegisterVT;
5840 MyFlags.Used = isReturnValueUsed;
5842 MyFlags.Flags.setSExt();
5844 MyFlags.Flags.setZExt();
5846 MyFlags.Flags.setInReg();
5847 Ins.push_back(MyFlags);
5851 SmallVector<SDValue, 4> InVals;
5852 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5853 Outs, Ins, dl, DAG, InVals);
5855 // Verify that the target's LowerCall behaved as expected.
5856 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5857 "LowerCall didn't return a valid chain!");
5858 assert((!isTailCall || InVals.empty()) &&
5859 "LowerCall emitted a return value for a tail call!");
5860 assert((isTailCall || InVals.size() == Ins.size()) &&
5861 "LowerCall didn't emit the correct number of values!");
5863 // For a tail call, the return value is merely live-out and there aren't
5864 // any nodes in the DAG representing it. Return a special value to
5865 // indicate that a tail call has been emitted and no more Instructions
5866 // should be processed in the current block.
5869 return std::make_pair(SDValue(), SDValue());
5872 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5873 assert(InVals[i].getNode() &&
5874 "LowerCall emitted a null value!");
5875 assert(Ins[i].VT == InVals[i].getValueType() &&
5876 "LowerCall emitted a value with the wrong type!");
5879 // Collect the legal value parts into potentially illegal values
5880 // that correspond to the original function's return values.
5881 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5883 AssertOp = ISD::AssertSext;
5885 AssertOp = ISD::AssertZext;
5886 SmallVector<SDValue, 4> ReturnValues;
5887 unsigned CurReg = 0;
5888 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5890 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5891 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5893 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
5894 NumRegs, RegisterVT, VT,
5899 // For a function returning void, there is no return value. We can't create
5900 // such a node, so we just return a null return value in that case. In
5901 // that case, nothing will actualy look at the value.
5902 if (ReturnValues.empty())
5903 return std::make_pair(SDValue(), Chain);
5905 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5906 DAG.getVTList(&RetTys[0], RetTys.size()),
5907 &ReturnValues[0], ReturnValues.size());
5908 return std::make_pair(Res, Chain);
5911 void TargetLowering::LowerOperationWrapper(SDNode *N,
5912 SmallVectorImpl<SDValue> &Results,
5913 SelectionDAG &DAG) const {
5914 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5916 Results.push_back(Res);
5919 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5920 llvm_unreachable("LowerOperation not implemented for this target!");
5925 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
5926 SDValue Op = getNonRegisterValue(V);
5927 assert((Op.getOpcode() != ISD::CopyFromReg ||
5928 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5929 "Copy from a reg to the same reg!");
5930 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5932 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5933 SDValue Chain = DAG.getEntryNode();
5934 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5935 PendingExports.push_back(Chain);
5938 #include "llvm/CodeGen/SelectionDAGISel.h"
5940 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
5941 // If this is the entry block, emit arguments.
5942 const Function &F = *LLVMBB->getParent();
5943 SelectionDAG &DAG = SDB->DAG;
5944 DebugLoc dl = SDB->getCurDebugLoc();
5945 const TargetData *TD = TLI.getTargetData();
5946 SmallVector<ISD::InputArg, 16> Ins;
5948 // Check whether the function can return without sret-demotion.
5949 SmallVector<EVT, 4> OutVTs;
5950 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5951 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5952 OutVTs, OutsFlags, TLI);
5954 FuncInfo->CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(),
5956 OutVTs, OutsFlags, DAG);
5957 if (!FuncInfo->CanLowerReturn) {
5958 // Put in an sret pointer parameter before all the other parameters.
5959 SmallVector<EVT, 1> ValueVTs;
5960 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5962 // NOTE: Assuming that a pointer will never break down to more than one VT
5964 ISD::ArgFlagsTy Flags;
5966 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
5967 ISD::InputArg RetArg(Flags, RegisterVT, true);
5968 Ins.push_back(RetArg);
5971 // Set up the incoming argument description vector.
5973 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
5974 I != E; ++I, ++Idx) {
5975 SmallVector<EVT, 4> ValueVTs;
5976 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5977 bool isArgValueUsed = !I->use_empty();
5978 for (unsigned Value = 0, NumValues = ValueVTs.size();
5979 Value != NumValues; ++Value) {
5980 EVT VT = ValueVTs[Value];
5981 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5982 ISD::ArgFlagsTy Flags;
5983 unsigned OriginalAlignment =
5984 TD->getABITypeAlignment(ArgTy);
5986 if (F.paramHasAttr(Idx, Attribute::ZExt))
5988 if (F.paramHasAttr(Idx, Attribute::SExt))
5990 if (F.paramHasAttr(Idx, Attribute::InReg))
5992 if (F.paramHasAttr(Idx, Attribute::StructRet))
5994 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5996 const PointerType *Ty = cast<PointerType>(I->getType());
5997 const Type *ElementTy = Ty->getElementType();
5998 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5999 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
6000 // For ByVal, alignment should be passed from FE. BE will guess if
6001 // this info is not there but there are cases it cannot get right.
6002 if (F.getParamAlignment(Idx))
6003 FrameAlign = F.getParamAlignment(Idx);
6004 Flags.setByValAlign(FrameAlign);
6005 Flags.setByValSize(FrameSize);
6007 if (F.paramHasAttr(Idx, Attribute::Nest))
6009 Flags.setOrigAlign(OriginalAlignment);
6011 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6012 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6013 for (unsigned i = 0; i != NumRegs; ++i) {
6014 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6015 if (NumRegs > 1 && i == 0)
6016 MyFlags.Flags.setSplit();
6017 // if it isn't first piece, alignment must be 1
6019 MyFlags.Flags.setOrigAlign(1);
6020 Ins.push_back(MyFlags);
6025 // Call the target to set up the argument values.
6026 SmallVector<SDValue, 8> InVals;
6027 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6031 // Verify that the target's LowerFormalArguments behaved as expected.
6032 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6033 "LowerFormalArguments didn't return a valid chain!");
6034 assert(InVals.size() == Ins.size() &&
6035 "LowerFormalArguments didn't emit the correct number of values!");
6037 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6038 assert(InVals[i].getNode() &&
6039 "LowerFormalArguments emitted a null value!");
6040 assert(Ins[i].VT == InVals[i].getValueType() &&
6041 "LowerFormalArguments emitted a value with the wrong type!");
6045 // Update the DAG with the new chain value resulting from argument lowering.
6046 DAG.setRoot(NewRoot);
6048 // Set up the argument values.
6051 if (!FuncInfo->CanLowerReturn) {
6052 // Create a virtual register for the sret pointer, and put in a copy
6053 // from the sret argument into it.
6054 SmallVector<EVT, 1> ValueVTs;
6055 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6056 EVT VT = ValueVTs[0];
6057 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6058 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6059 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6060 RegVT, VT, AssertOp);
6062 MachineFunction& MF = SDB->DAG.getMachineFunction();
6063 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6064 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6065 FuncInfo->DemoteRegister = SRetReg;
6066 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6068 DAG.setRoot(NewRoot);
6070 // i indexes lowered arguments. Bump it past the hidden sret argument.
6071 // Idx indexes LLVM arguments. Don't touch it.
6075 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6077 SmallVector<SDValue, 4> ArgValues;
6078 SmallVector<EVT, 4> ValueVTs;
6079 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6080 unsigned NumValues = ValueVTs.size();
6082 // If this argument is unused then remember its value. It is used to generate
6083 // debugging information.
6084 if (I->use_empty() && NumValues)
6085 SDB->setUnusedArgValue(I, InVals[i]);
6087 for (unsigned Value = 0; Value != NumValues; ++Value) {
6088 EVT VT = ValueVTs[Value];
6089 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6090 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6092 if (!I->use_empty()) {
6093 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6094 if (F.paramHasAttr(Idx, Attribute::SExt))
6095 AssertOp = ISD::AssertSext;
6096 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6097 AssertOp = ISD::AssertZext;
6099 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6100 NumParts, PartVT, VT,
6107 if (!I->use_empty()) {
6109 if (!ArgValues.empty())
6110 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6111 SDB->getCurDebugLoc());
6112 SDB->setValue(I, Res);
6114 // If this argument is live outside of the entry block, insert a copy from
6115 // whereever we got it to the vreg that other BB's will reference it as.
6116 SDB->CopyToExportRegsIfNeeded(I);
6120 assert(i == InVals.size() && "Argument register count mismatch!");
6122 // Finally, if the target has anything special to do, allow it to do so.
6123 // FIXME: this should insert code into the DAG!
6124 EmitFunctionEntryCode();
6127 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6128 /// ensure constants are generated when needed. Remember the virtual registers
6129 /// that need to be added to the Machine PHI nodes as input. We cannot just
6130 /// directly add them, because expansion might result in multiple MBB's for one
6131 /// BB. As such, the start of the BB might correspond to a different MBB than
6135 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6136 const TerminatorInst *TI = LLVMBB->getTerminator();
6138 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6140 // Check successor nodes' PHI nodes that expect a constant to be available
6142 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6143 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6144 if (!isa<PHINode>(SuccBB->begin())) continue;
6145 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6147 // If this terminator has multiple identical successors (common for
6148 // switches), only handle each succ once.
6149 if (!SuccsHandled.insert(SuccMBB)) continue;
6151 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6153 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6154 // nodes and Machine PHI nodes, but the incoming operands have not been
6156 for (BasicBlock::const_iterator I = SuccBB->begin();
6157 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6158 // Ignore dead phi's.
6159 if (PN->use_empty()) continue;
6162 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6164 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6165 unsigned &RegOut = ConstantsOut[C];
6167 RegOut = FuncInfo.CreateRegs(C->getType());
6168 CopyValueToVirtualRegister(C, RegOut);
6172 DenseMap<const Value *, unsigned>::iterator I =
6173 FuncInfo.ValueMap.find(PHIOp);
6174 if (I != FuncInfo.ValueMap.end())
6177 assert(isa<AllocaInst>(PHIOp) &&
6178 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6179 "Didn't codegen value into a register!??");
6180 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6181 CopyValueToVirtualRegister(PHIOp, Reg);
6185 // Remember that this register needs to added to the machine PHI node as
6186 // the input for this MBB.
6187 SmallVector<EVT, 4> ValueVTs;
6188 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6189 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6190 EVT VT = ValueVTs[vti];
6191 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6192 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6193 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6194 Reg += NumRegisters;
6198 ConstantsOut.clear();