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 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GCMetadata.h"
27 #include "llvm/CodeGen/GCStrategy.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/StackMaps.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DebugInfo.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/LLVMContext.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetFrameLowering.h"
55 #include "llvm/Target/TargetInstrInfo.h"
56 #include "llvm/Target/TargetIntrinsicInfo.h"
57 #include "llvm/Target/TargetLibraryInfo.h"
58 #include "llvm/Target/TargetLowering.h"
59 #include "llvm/Target/TargetOptions.h"
60 #include "llvm/Target/TargetSelectionDAGInfo.h"
61 #include "llvm/Target/TargetSubtargetInfo.h"
65 #define DEBUG_TYPE "isel"
67 /// LimitFloatPrecision - Generate low-precision inline sequences for
68 /// some float libcalls (6, 8 or 12 bits).
69 static unsigned LimitFloatPrecision;
71 static cl::opt<unsigned, true>
72 LimitFPPrecision("limit-float-precision",
73 cl::desc("Generate low-precision inline sequences "
74 "for some float libcalls"),
75 cl::location(LimitFloatPrecision),
78 // Limit the width of DAG chains. This is important in general to prevent
79 // prevent DAG-based analysis from blowing up. For example, alias analysis and
80 // load clustering may not complete in reasonable time. It is difficult to
81 // recognize and avoid this situation within each individual analysis, and
82 // future analyses are likely to have the same behavior. Limiting DAG width is
83 // the safe approach, and will be especially important with global DAGs.
85 // MaxParallelChains default is arbitrarily high to avoid affecting
86 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
87 // sequence over this should have been converted to llvm.memcpy by the
88 // frontend. It easy to induce this behavior with .ll code such as:
89 // %buffer = alloca [4096 x i8]
90 // %data = load [4096 x i8]* %argPtr
91 // store [4096 x i8] %data, [4096 x i8]* %buffer
92 static const unsigned MaxParallelChains = 64;
94 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
95 const SDValue *Parts, unsigned NumParts,
96 MVT PartVT, EVT ValueVT, const Value *V);
98 /// getCopyFromParts - Create a value that contains the specified legal parts
99 /// combined into the value they represent. If the parts combine to a type
100 /// larger then ValueVT then AssertOp can be used to specify whether the extra
101 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
102 /// (ISD::AssertSext).
103 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
104 const SDValue *Parts,
105 unsigned NumParts, MVT PartVT, EVT ValueVT,
107 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
108 if (ValueVT.isVector())
109 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
112 assert(NumParts > 0 && "No parts to assemble!");
113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
114 SDValue Val = Parts[0];
117 // Assemble the value from multiple parts.
118 if (ValueVT.isInteger()) {
119 unsigned PartBits = PartVT.getSizeInBits();
120 unsigned ValueBits = ValueVT.getSizeInBits();
122 // Assemble the power of 2 part.
123 unsigned RoundParts = NumParts & (NumParts - 1) ?
124 1 << Log2_32(NumParts) : NumParts;
125 unsigned RoundBits = PartBits * RoundParts;
126 EVT RoundVT = RoundBits == ValueBits ?
127 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
130 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
132 if (RoundParts > 2) {
133 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
135 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
136 RoundParts / 2, PartVT, HalfVT, V);
138 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
139 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
142 if (TLI.isBigEndian())
145 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
147 if (RoundParts < NumParts) {
148 // Assemble the trailing non-power-of-2 part.
149 unsigned OddParts = NumParts - RoundParts;
150 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
151 Hi = getCopyFromParts(DAG, DL,
152 Parts + RoundParts, OddParts, PartVT, OddVT, V);
154 // Combine the round and odd parts.
156 if (TLI.isBigEndian())
158 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
159 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
160 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
161 DAG.getConstant(Lo.getValueType().getSizeInBits(),
162 TLI.getPointerTy()));
163 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
164 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
166 } else if (PartVT.isFloatingPoint()) {
167 // FP split into multiple FP parts (for ppcf128)
168 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
171 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
172 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
173 if (TLI.hasBigEndianPartOrdering(ValueVT))
175 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
177 // FP split into integer parts (soft fp)
178 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
179 !PartVT.isVector() && "Unexpected split");
180 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
181 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
185 // There is now one part, held in Val. Correct it to match ValueVT.
186 EVT PartEVT = Val.getValueType();
188 if (PartEVT == ValueVT)
191 if (PartEVT.isInteger() && ValueVT.isInteger()) {
192 if (ValueVT.bitsLT(PartEVT)) {
193 // For a truncate, see if we have any information to
194 // indicate whether the truncated bits will always be
195 // zero or sign-extension.
196 if (AssertOp != ISD::DELETED_NODE)
197 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
198 DAG.getValueType(ValueVT));
199 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
201 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
204 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
205 // FP_ROUND's are always exact here.
206 if (ValueVT.bitsLT(Val.getValueType()))
207 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
208 DAG.getTargetConstant(1, TLI.getPointerTy()));
210 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
213 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
214 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
216 llvm_unreachable("Unknown mismatch!");
219 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
220 const Twine &ErrMsg) {
221 const Instruction *I = dyn_cast_or_null<Instruction>(V);
223 return Ctx.emitError(ErrMsg);
225 const char *AsmError = ", possible invalid constraint for vector type";
226 if (const CallInst *CI = dyn_cast<CallInst>(I))
227 if (isa<InlineAsm>(CI->getCalledValue()))
228 return Ctx.emitError(I, ErrMsg + AsmError);
230 return Ctx.emitError(I, ErrMsg);
233 /// getCopyFromPartsVector - Create a value that contains the specified legal
234 /// parts combined into the value they represent. If the parts combine to a
235 /// type larger then ValueVT then AssertOp can be used to specify whether the
236 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
237 /// ValueVT (ISD::AssertSext).
238 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
239 const SDValue *Parts, unsigned NumParts,
240 MVT PartVT, EVT ValueVT, const Value *V) {
241 assert(ValueVT.isVector() && "Not a vector value");
242 assert(NumParts > 0 && "No parts to assemble!");
243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
244 SDValue Val = Parts[0];
246 // Handle a multi-element vector.
250 unsigned NumIntermediates;
252 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
253 NumIntermediates, RegisterVT);
254 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
255 NumParts = NumRegs; // Silence a compiler warning.
256 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
257 assert(RegisterVT == Parts[0].getSimpleValueType() &&
258 "Part type doesn't match part!");
260 // Assemble the parts into intermediate operands.
261 SmallVector<SDValue, 8> Ops(NumIntermediates);
262 if (NumIntermediates == NumParts) {
263 // If the register was not expanded, truncate or copy the value,
265 for (unsigned i = 0; i != NumParts; ++i)
266 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
267 PartVT, IntermediateVT, V);
268 } else if (NumParts > 0) {
269 // If the intermediate type was expanded, build the intermediate
270 // operands from the parts.
271 assert(NumParts % NumIntermediates == 0 &&
272 "Must expand into a divisible number of parts!");
273 unsigned Factor = NumParts / NumIntermediates;
274 for (unsigned i = 0; i != NumIntermediates; ++i)
275 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
276 PartVT, IntermediateVT, V);
279 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
280 // intermediate operands.
281 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
286 // There is now one part, held in Val. Correct it to match ValueVT.
287 EVT PartEVT = Val.getValueType();
289 if (PartEVT == ValueVT)
292 if (PartEVT.isVector()) {
293 // If the element type of the source/dest vectors are the same, but the
294 // parts vector has more elements than the value vector, then we have a
295 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
297 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
298 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
299 "Cannot narrow, it would be a lossy transformation");
300 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
301 DAG.getConstant(0, TLI.getVectorIdxTy()));
304 // Vector/Vector bitcast.
305 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
306 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
308 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
309 "Cannot handle this kind of promotion");
310 // Promoted vector extract
311 bool Smaller = ValueVT.bitsLE(PartEVT);
312 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
317 // Trivial bitcast if the types are the same size and the destination
318 // vector type is legal.
319 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
320 TLI.isTypeLegal(ValueVT))
321 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
323 // Handle cases such as i8 -> <1 x i1>
324 if (ValueVT.getVectorNumElements() != 1) {
325 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
326 "non-trivial scalar-to-vector conversion");
327 return DAG.getUNDEF(ValueVT);
330 if (ValueVT.getVectorNumElements() == 1 &&
331 ValueVT.getVectorElementType() != PartEVT) {
332 bool Smaller = ValueVT.bitsLE(PartEVT);
333 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
334 DL, ValueVT.getScalarType(), Val);
337 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
340 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
341 SDValue Val, SDValue *Parts, unsigned NumParts,
342 MVT PartVT, const Value *V);
344 /// getCopyToParts - Create a series of nodes that contain the specified value
345 /// split into legal parts. If the parts contain more bits than Val, then, for
346 /// integers, ExtendKind can be used to specify how to generate the extra bits.
347 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
348 SDValue Val, SDValue *Parts, unsigned NumParts,
349 MVT PartVT, const Value *V,
350 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
351 EVT ValueVT = Val.getValueType();
353 // Handle the vector case separately.
354 if (ValueVT.isVector())
355 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
358 unsigned PartBits = PartVT.getSizeInBits();
359 unsigned OrigNumParts = NumParts;
360 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
365 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
366 EVT PartEVT = PartVT;
367 if (PartEVT == ValueVT) {
368 assert(NumParts == 1 && "No-op copy with multiple parts!");
373 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374 // If the parts cover more bits than the value has, promote the value.
375 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376 assert(NumParts == 1 && "Do not know what to promote to!");
377 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
379 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
380 ValueVT.isInteger() &&
381 "Unknown mismatch!");
382 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
383 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
384 if (PartVT == MVT::x86mmx)
385 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
387 } else if (PartBits == ValueVT.getSizeInBits()) {
388 // Different types of the same size.
389 assert(NumParts == 1 && PartEVT != ValueVT);
390 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
391 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
392 // If the parts cover less bits than value has, truncate the value.
393 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
394 ValueVT.isInteger() &&
395 "Unknown mismatch!");
396 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
397 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
398 if (PartVT == MVT::x86mmx)
399 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
402 // The value may have changed - recompute ValueVT.
403 ValueVT = Val.getValueType();
404 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
405 "Failed to tile the value with PartVT!");
408 if (PartEVT != ValueVT)
409 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
410 "scalar-to-vector conversion failed");
416 // Expand the value into multiple parts.
417 if (NumParts & (NumParts - 1)) {
418 // The number of parts is not a power of 2. Split off and copy the tail.
419 assert(PartVT.isInteger() && ValueVT.isInteger() &&
420 "Do not know what to expand to!");
421 unsigned RoundParts = 1 << Log2_32(NumParts);
422 unsigned RoundBits = RoundParts * PartBits;
423 unsigned OddParts = NumParts - RoundParts;
424 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
425 DAG.getIntPtrConstant(RoundBits));
426 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
428 if (TLI.isBigEndian())
429 // The odd parts were reversed by getCopyToParts - unreverse them.
430 std::reverse(Parts + RoundParts, Parts + NumParts);
432 NumParts = RoundParts;
433 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
434 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
437 // The number of parts is a power of 2. Repeatedly bisect the value using
439 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
440 EVT::getIntegerVT(*DAG.getContext(),
441 ValueVT.getSizeInBits()),
444 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
445 for (unsigned i = 0; i < NumParts; i += StepSize) {
446 unsigned ThisBits = StepSize * PartBits / 2;
447 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
448 SDValue &Part0 = Parts[i];
449 SDValue &Part1 = Parts[i+StepSize/2];
451 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
452 ThisVT, Part0, DAG.getIntPtrConstant(1));
453 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454 ThisVT, Part0, DAG.getIntPtrConstant(0));
456 if (ThisBits == PartBits && ThisVT != PartVT) {
457 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
458 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
463 if (TLI.isBigEndian())
464 std::reverse(Parts, Parts + OrigNumParts);
468 /// getCopyToPartsVector - Create a series of nodes that contain the specified
469 /// value split into legal parts.
470 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
471 SDValue Val, SDValue *Parts, unsigned NumParts,
472 MVT PartVT, const Value *V) {
473 EVT ValueVT = Val.getValueType();
474 assert(ValueVT.isVector() && "Not a vector");
475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
478 EVT PartEVT = PartVT;
479 if (PartEVT == ValueVT) {
481 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
482 // Bitconvert vector->vector case.
483 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
484 } else if (PartVT.isVector() &&
485 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
486 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
487 EVT ElementVT = PartVT.getVectorElementType();
488 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
490 SmallVector<SDValue, 16> Ops;
491 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
492 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
493 ElementVT, Val, DAG.getConstant(i,
494 TLI.getVectorIdxTy())));
496 for (unsigned i = ValueVT.getVectorNumElements(),
497 e = PartVT.getVectorNumElements(); i != e; ++i)
498 Ops.push_back(DAG.getUNDEF(ElementVT));
500 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
502 // FIXME: Use CONCAT for 2x -> 4x.
504 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
505 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
506 } else if (PartVT.isVector() &&
507 PartEVT.getVectorElementType().bitsGE(
508 ValueVT.getVectorElementType()) &&
509 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
511 // Promoted vector extract
512 bool Smaller = PartEVT.bitsLE(ValueVT);
513 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
516 // Vector -> scalar conversion.
517 assert(ValueVT.getVectorNumElements() == 1 &&
518 "Only trivial vector-to-scalar conversions should get here!");
519 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
520 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
522 bool Smaller = ValueVT.bitsLE(PartVT);
523 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
531 // Handle a multi-element vector.
534 unsigned NumIntermediates;
535 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
537 NumIntermediates, RegisterVT);
538 unsigned NumElements = ValueVT.getVectorNumElements();
540 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
541 NumParts = NumRegs; // Silence a compiler warning.
542 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
544 // Split the vector into intermediate operands.
545 SmallVector<SDValue, 8> Ops(NumIntermediates);
546 for (unsigned i = 0; i != NumIntermediates; ++i) {
547 if (IntermediateVT.isVector())
548 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
550 DAG.getConstant(i * (NumElements / NumIntermediates),
551 TLI.getVectorIdxTy()));
553 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
555 DAG.getConstant(i, TLI.getVectorIdxTy()));
558 // Split the intermediate operands into legal parts.
559 if (NumParts == NumIntermediates) {
560 // If the register was not expanded, promote or copy the value,
562 for (unsigned i = 0; i != NumParts; ++i)
563 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
564 } else if (NumParts > 0) {
565 // If the intermediate type was expanded, split each the value into
567 assert(NumParts % NumIntermediates == 0 &&
568 "Must expand into a divisible number of parts!");
569 unsigned Factor = NumParts / NumIntermediates;
570 for (unsigned i = 0; i != NumIntermediates; ++i)
571 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
576 /// RegsForValue - This struct represents the registers (physical or virtual)
577 /// that a particular set of values is assigned, and the type information
578 /// about the value. The most common situation is to represent one value at a
579 /// time, but struct or array values are handled element-wise as multiple
580 /// values. The splitting of aggregates is performed recursively, so that we
581 /// never have aggregate-typed registers. The values at this point do not
582 /// necessarily have legal types, so each value may require one or more
583 /// registers of some legal type.
585 struct RegsForValue {
586 /// ValueVTs - The value types of the values, which may not be legal, and
587 /// may need be promoted or synthesized from one or more registers.
589 SmallVector<EVT, 4> ValueVTs;
591 /// RegVTs - The value types of the registers. This is the same size as
592 /// ValueVTs and it records, for each value, what the type of the assigned
593 /// register or registers are. (Individual values are never synthesized
594 /// from more than one type of register.)
596 /// With virtual registers, the contents of RegVTs is redundant with TLI's
597 /// getRegisterType member function, however when with physical registers
598 /// it is necessary to have a separate record of the types.
600 SmallVector<MVT, 4> RegVTs;
602 /// Regs - This list holds the registers assigned to the values.
603 /// Each legal or promoted value requires one register, and each
604 /// expanded value requires multiple registers.
606 SmallVector<unsigned, 4> Regs;
610 RegsForValue(const SmallVector<unsigned, 4> ®s,
611 MVT regvt, EVT valuevt)
612 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
614 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
615 unsigned Reg, Type *Ty) {
616 ComputeValueVTs(tli, Ty, ValueVTs);
618 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
619 EVT ValueVT = ValueVTs[Value];
620 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
621 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
622 for (unsigned i = 0; i != NumRegs; ++i)
623 Regs.push_back(Reg + i);
624 RegVTs.push_back(RegisterVT);
629 /// append - Add the specified values to this one.
630 void append(const RegsForValue &RHS) {
631 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
632 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
633 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
636 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
637 /// this value and returns the result as a ValueVTs value. This uses
638 /// Chain/Flag as the input and updates them for the output Chain/Flag.
639 /// If the Flag pointer is NULL, no flag is used.
640 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
642 SDValue &Chain, SDValue *Flag,
643 const Value *V = nullptr) const;
645 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
646 /// specified value into the registers specified by this object. This uses
647 /// Chain/Flag as the input and updates them for the output Chain/Flag.
648 /// If the Flag pointer is NULL, no flag is used.
650 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
651 SDValue *Flag, const Value *V,
652 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
654 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
655 /// operand list. This adds the code marker, matching input operand index
656 /// (if applicable), and includes the number of values added into it.
657 void AddInlineAsmOperands(unsigned Kind,
658 bool HasMatching, unsigned MatchingIdx,
660 std::vector<SDValue> &Ops) const;
664 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
665 /// this value and returns the result as a ValueVT value. This uses
666 /// Chain/Flag as the input and updates them for the output Chain/Flag.
667 /// If the Flag pointer is NULL, no flag is used.
668 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
669 FunctionLoweringInfo &FuncInfo,
671 SDValue &Chain, SDValue *Flag,
672 const Value *V) const {
673 // A Value with type {} or [0 x %t] needs no registers.
674 if (ValueVTs.empty())
677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
679 // Assemble the legal parts into the final values.
680 SmallVector<SDValue, 4> Values(ValueVTs.size());
681 SmallVector<SDValue, 8> Parts;
682 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
683 // Copy the legal parts from the registers.
684 EVT ValueVT = ValueVTs[Value];
685 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
686 MVT RegisterVT = RegVTs[Value];
688 Parts.resize(NumRegs);
689 for (unsigned i = 0; i != NumRegs; ++i) {
692 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
694 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
695 *Flag = P.getValue(2);
698 Chain = P.getValue(1);
701 // If the source register was virtual and if we know something about it,
702 // add an assert node.
703 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
704 !RegisterVT.isInteger() || RegisterVT.isVector())
707 const FunctionLoweringInfo::LiveOutInfo *LOI =
708 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
712 unsigned RegSize = RegisterVT.getSizeInBits();
713 unsigned NumSignBits = LOI->NumSignBits;
714 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
716 if (NumZeroBits == RegSize) {
717 // The current value is a zero.
718 // Explicitly express that as it would be easier for
719 // optimizations to kick in.
720 Parts[i] = DAG.getConstant(0, RegisterVT);
724 // FIXME: We capture more information than the dag can represent. For
725 // now, just use the tightest assertzext/assertsext possible.
727 EVT FromVT(MVT::Other);
728 if (NumSignBits == RegSize)
729 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
730 else if (NumZeroBits >= RegSize-1)
731 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
732 else if (NumSignBits > RegSize-8)
733 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
734 else if (NumZeroBits >= RegSize-8)
735 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
736 else if (NumSignBits > RegSize-16)
737 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
738 else if (NumZeroBits >= RegSize-16)
739 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
740 else if (NumSignBits > RegSize-32)
741 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
742 else if (NumZeroBits >= RegSize-32)
743 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
747 // Add an assertion node.
748 assert(FromVT != MVT::Other);
749 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
750 RegisterVT, P, DAG.getValueType(FromVT));
753 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
754 NumRegs, RegisterVT, ValueVT, V);
759 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
762 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
763 /// specified value into the registers specified by this object. This uses
764 /// Chain/Flag as the input and updates them for the output Chain/Flag.
765 /// If the Flag pointer is NULL, no flag is used.
766 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
767 SDValue &Chain, SDValue *Flag, const Value *V,
768 ISD::NodeType PreferredExtendType) const {
769 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
770 ISD::NodeType ExtendKind = PreferredExtendType;
772 // Get the list of the values's legal parts.
773 unsigned NumRegs = Regs.size();
774 SmallVector<SDValue, 8> Parts(NumRegs);
775 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
776 EVT ValueVT = ValueVTs[Value];
777 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
778 MVT RegisterVT = RegVTs[Value];
780 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
781 ExtendKind = ISD::ZERO_EXTEND;
783 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
784 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
788 // Copy the parts into the registers.
789 SmallVector<SDValue, 8> Chains(NumRegs);
790 for (unsigned i = 0; i != NumRegs; ++i) {
793 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
795 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
796 *Flag = Part.getValue(1);
799 Chains[i] = Part.getValue(0);
802 if (NumRegs == 1 || Flag)
803 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
804 // flagged to it. That is the CopyToReg nodes and the user are considered
805 // a single scheduling unit. If we create a TokenFactor and return it as
806 // chain, then the TokenFactor is both a predecessor (operand) of the
807 // user as well as a successor (the TF operands are flagged to the user).
808 // c1, f1 = CopyToReg
809 // c2, f2 = CopyToReg
810 // c3 = TokenFactor c1, c2
813 Chain = Chains[NumRegs-1];
815 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
818 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
819 /// operand list. This adds the code marker and includes the number of
820 /// values added into it.
821 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
822 unsigned MatchingIdx,
824 std::vector<SDValue> &Ops) const {
825 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
827 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
829 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
830 else if (!Regs.empty() &&
831 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
832 // Put the register class of the virtual registers in the flag word. That
833 // way, later passes can recompute register class constraints for inline
834 // assembly as well as normal instructions.
835 // Don't do this for tied operands that can use the regclass information
837 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
838 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
839 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
842 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
845 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
846 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
847 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
848 MVT RegisterVT = RegVTs[Value];
849 for (unsigned i = 0; i != NumRegs; ++i) {
850 assert(Reg < Regs.size() && "Mismatch in # registers expected");
851 unsigned TheReg = Regs[Reg++];
852 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
854 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
855 // If we clobbered the stack pointer, MFI should know about it.
856 assert(DAG.getMachineFunction().getFrameInfo()->
857 hasInlineAsmWithSPAdjust());
863 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
864 const TargetLibraryInfo *li) {
868 DL = DAG.getSubtarget().getDataLayout();
869 Context = DAG.getContext();
870 LPadToCallSiteMap.clear();
873 /// clear - Clear out the current SelectionDAG and the associated
874 /// state and prepare this SelectionDAGBuilder object to be used
875 /// for a new block. This doesn't clear out information about
876 /// additional blocks that are needed to complete switch lowering
877 /// or PHI node updating; that information is cleared out as it is
879 void SelectionDAGBuilder::clear() {
881 UnusedArgNodeMap.clear();
882 PendingLoads.clear();
883 PendingExports.clear();
886 SDNodeOrder = LowestSDNodeOrder;
889 /// clearDanglingDebugInfo - Clear the dangling debug information
890 /// map. This function is separated from the clear so that debug
891 /// information that is dangling in a basic block can be properly
892 /// resolved in a different basic block. This allows the
893 /// SelectionDAG to resolve dangling debug information attached
895 void SelectionDAGBuilder::clearDanglingDebugInfo() {
896 DanglingDebugInfoMap.clear();
899 /// getRoot - Return the current virtual root of the Selection DAG,
900 /// flushing any PendingLoad items. This must be done before emitting
901 /// a store or any other node that may need to be ordered after any
902 /// prior load instructions.
904 SDValue SelectionDAGBuilder::getRoot() {
905 if (PendingLoads.empty())
906 return DAG.getRoot();
908 if (PendingLoads.size() == 1) {
909 SDValue Root = PendingLoads[0];
911 PendingLoads.clear();
915 // Otherwise, we have to make a token factor node.
916 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
918 PendingLoads.clear();
923 /// getControlRoot - Similar to getRoot, but instead of flushing all the
924 /// PendingLoad items, flush all the PendingExports items. It is necessary
925 /// to do this before emitting a terminator instruction.
927 SDValue SelectionDAGBuilder::getControlRoot() {
928 SDValue Root = DAG.getRoot();
930 if (PendingExports.empty())
933 // Turn all of the CopyToReg chains into one factored node.
934 if (Root.getOpcode() != ISD::EntryToken) {
935 unsigned i = 0, e = PendingExports.size();
936 for (; i != e; ++i) {
937 assert(PendingExports[i].getNode()->getNumOperands() > 1);
938 if (PendingExports[i].getNode()->getOperand(0) == Root)
939 break; // Don't add the root if we already indirectly depend on it.
943 PendingExports.push_back(Root);
946 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
948 PendingExports.clear();
953 void SelectionDAGBuilder::visit(const Instruction &I) {
954 // Set up outgoing PHI node register values before emitting the terminator.
955 if (isa<TerminatorInst>(&I))
956 HandlePHINodesInSuccessorBlocks(I.getParent());
962 visit(I.getOpcode(), I);
964 if (!isa<TerminatorInst>(&I) && !HasTailCall)
965 CopyToExportRegsIfNeeded(&I);
970 void SelectionDAGBuilder::visitPHI(const PHINode &) {
971 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
974 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
975 // Note: this doesn't use InstVisitor, because it has to work with
976 // ConstantExpr's in addition to instructions.
978 default: llvm_unreachable("Unknown instruction type encountered!");
979 // Build the switch statement using the Instruction.def file.
980 #define HANDLE_INST(NUM, OPCODE, CLASS) \
981 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
982 #include "llvm/IR/Instruction.def"
986 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
987 // generate the debug data structures now that we've seen its definition.
988 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
990 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
992 const DbgValueInst *DI = DDI.getDI();
993 DebugLoc dl = DDI.getdl();
994 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
995 MDNode *Variable = DI->getVariable();
996 MDNode *Expr = DI->getExpression();
997 uint64_t Offset = DI->getOffset();
998 // A dbg.value for an alloca is always indirect.
999 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1001 if (Val.getNode()) {
1002 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1004 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1005 IsIndirect, Offset, dl, DbgSDNodeOrder);
1006 DAG.AddDbgValue(SDV, Val.getNode(), false);
1009 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1010 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1014 /// getValue - Return an SDValue for the given Value.
1015 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1016 // If we already have an SDValue for this value, use it. It's important
1017 // to do this first, so that we don't create a CopyFromReg if we already
1018 // have a regular SDValue.
1019 SDValue &N = NodeMap[V];
1020 if (N.getNode()) return N;
1022 // If there's a virtual register allocated and initialized for this
1024 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1025 if (It != FuncInfo.ValueMap.end()) {
1026 unsigned InReg = It->second;
1027 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1029 SDValue Chain = DAG.getEntryNode();
1030 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1031 resolveDanglingDebugInfo(V, N);
1035 // Otherwise create a new SDValue and remember it.
1036 SDValue Val = getValueImpl(V);
1038 resolveDanglingDebugInfo(V, Val);
1042 /// getNonRegisterValue - Return an SDValue for the given Value, but
1043 /// don't look in FuncInfo.ValueMap for a virtual register.
1044 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1045 // If we already have an SDValue for this value, use it.
1046 SDValue &N = NodeMap[V];
1047 if (N.getNode()) return N;
1049 // Otherwise create a new SDValue and remember it.
1050 SDValue Val = getValueImpl(V);
1052 resolveDanglingDebugInfo(V, Val);
1056 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1057 /// Create an SDValue for the given value.
1058 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1059 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1061 if (const Constant *C = dyn_cast<Constant>(V)) {
1062 EVT VT = TLI.getValueType(V->getType(), true);
1064 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1065 return DAG.getConstant(*CI, VT);
1067 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1068 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1070 if (isa<ConstantPointerNull>(C)) {
1071 unsigned AS = V->getType()->getPointerAddressSpace();
1072 return DAG.getConstant(0, TLI.getPointerTy(AS));
1075 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1076 return DAG.getConstantFP(*CFP, VT);
1078 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1079 return DAG.getUNDEF(VT);
1081 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1082 visit(CE->getOpcode(), *CE);
1083 SDValue N1 = NodeMap[V];
1084 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1088 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1089 SmallVector<SDValue, 4> Constants;
1090 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1092 SDNode *Val = getValue(*OI).getNode();
1093 // If the operand is an empty aggregate, there are no values.
1095 // Add each leaf value from the operand to the Constants list
1096 // to form a flattened list of all the values.
1097 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1098 Constants.push_back(SDValue(Val, i));
1101 return DAG.getMergeValues(Constants, getCurSDLoc());
1104 if (const ConstantDataSequential *CDS =
1105 dyn_cast<ConstantDataSequential>(C)) {
1106 SmallVector<SDValue, 4> Ops;
1107 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1108 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1109 // Add each leaf value from the operand to the Constants list
1110 // to form a flattened list of all the values.
1111 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1112 Ops.push_back(SDValue(Val, i));
1115 if (isa<ArrayType>(CDS->getType()))
1116 return DAG.getMergeValues(Ops, getCurSDLoc());
1117 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1121 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1122 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1123 "Unknown struct or array constant!");
1125 SmallVector<EVT, 4> ValueVTs;
1126 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1127 unsigned NumElts = ValueVTs.size();
1129 return SDValue(); // empty struct
1130 SmallVector<SDValue, 4> Constants(NumElts);
1131 for (unsigned i = 0; i != NumElts; ++i) {
1132 EVT EltVT = ValueVTs[i];
1133 if (isa<UndefValue>(C))
1134 Constants[i] = DAG.getUNDEF(EltVT);
1135 else if (EltVT.isFloatingPoint())
1136 Constants[i] = DAG.getConstantFP(0, EltVT);
1138 Constants[i] = DAG.getConstant(0, EltVT);
1141 return DAG.getMergeValues(Constants, getCurSDLoc());
1144 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1145 return DAG.getBlockAddress(BA, VT);
1147 VectorType *VecTy = cast<VectorType>(V->getType());
1148 unsigned NumElements = VecTy->getNumElements();
1150 // Now that we know the number and type of the elements, get that number of
1151 // elements into the Ops array based on what kind of constant it is.
1152 SmallVector<SDValue, 16> Ops;
1153 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1154 for (unsigned i = 0; i != NumElements; ++i)
1155 Ops.push_back(getValue(CV->getOperand(i)));
1157 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1158 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1161 if (EltVT.isFloatingPoint())
1162 Op = DAG.getConstantFP(0, EltVT);
1164 Op = DAG.getConstant(0, EltVT);
1165 Ops.assign(NumElements, Op);
1168 // Create a BUILD_VECTOR node.
1169 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1172 // If this is a static alloca, generate it as the frameindex instead of
1174 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1175 DenseMap<const AllocaInst*, int>::iterator SI =
1176 FuncInfo.StaticAllocaMap.find(AI);
1177 if (SI != FuncInfo.StaticAllocaMap.end())
1178 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1181 // If this is an instruction which fast-isel has deferred, select it now.
1182 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1183 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1184 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1185 SDValue Chain = DAG.getEntryNode();
1186 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1189 llvm_unreachable("Can't get register for value!");
1192 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1193 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1194 SDValue Chain = getControlRoot();
1195 SmallVector<ISD::OutputArg, 8> Outs;
1196 SmallVector<SDValue, 8> OutVals;
1198 if (!FuncInfo.CanLowerReturn) {
1199 unsigned DemoteReg = FuncInfo.DemoteRegister;
1200 const Function *F = I.getParent()->getParent();
1202 // Emit a store of the return value through the virtual register.
1203 // Leave Outs empty so that LowerReturn won't try to load return
1204 // registers the usual way.
1205 SmallVector<EVT, 1> PtrValueVTs;
1206 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1209 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1210 SDValue RetOp = getValue(I.getOperand(0));
1212 SmallVector<EVT, 4> ValueVTs;
1213 SmallVector<uint64_t, 4> Offsets;
1214 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1215 unsigned NumValues = ValueVTs.size();
1217 SmallVector<SDValue, 4> Chains(NumValues);
1218 for (unsigned i = 0; i != NumValues; ++i) {
1219 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1220 RetPtr.getValueType(), RetPtr,
1221 DAG.getIntPtrConstant(Offsets[i]));
1223 DAG.getStore(Chain, getCurSDLoc(),
1224 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1225 // FIXME: better loc info would be nice.
1226 Add, MachinePointerInfo(), false, false, 0);
1229 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1230 MVT::Other, Chains);
1231 } else if (I.getNumOperands() != 0) {
1232 SmallVector<EVT, 4> ValueVTs;
1233 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1234 unsigned NumValues = ValueVTs.size();
1236 SDValue RetOp = getValue(I.getOperand(0));
1237 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1238 EVT VT = ValueVTs[j];
1240 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1242 const Function *F = I.getParent()->getParent();
1243 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1245 ExtendKind = ISD::SIGN_EXTEND;
1246 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1248 ExtendKind = ISD::ZERO_EXTEND;
1250 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1251 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1253 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1254 MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1255 SmallVector<SDValue, 4> Parts(NumParts);
1256 getCopyToParts(DAG, getCurSDLoc(),
1257 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1258 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1260 // 'inreg' on function refers to return value
1261 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1262 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1266 // Propagate extension type if any
1267 if (ExtendKind == ISD::SIGN_EXTEND)
1269 else if (ExtendKind == ISD::ZERO_EXTEND)
1272 for (unsigned i = 0; i < NumParts; ++i) {
1273 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1274 VT, /*isfixed=*/true, 0, 0));
1275 OutVals.push_back(Parts[i]);
1281 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1282 CallingConv::ID CallConv =
1283 DAG.getMachineFunction().getFunction()->getCallingConv();
1284 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1285 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1287 // Verify that the target's LowerReturn behaved as expected.
1288 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1289 "LowerReturn didn't return a valid chain!");
1291 // Update the DAG with the new chain value resulting from return lowering.
1295 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1296 /// created for it, emit nodes to copy the value into the virtual
1298 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1300 if (V->getType()->isEmptyTy())
1303 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1304 if (VMI != FuncInfo.ValueMap.end()) {
1305 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1306 CopyValueToVirtualRegister(V, VMI->second);
1310 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1311 /// the current basic block, add it to ValueMap now so that we'll get a
1313 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1314 // No need to export constants.
1315 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1317 // Already exported?
1318 if (FuncInfo.isExportedInst(V)) return;
1320 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1321 CopyValueToVirtualRegister(V, Reg);
1324 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1325 const BasicBlock *FromBB) {
1326 // The operands of the setcc have to be in this block. We don't know
1327 // how to export them from some other block.
1328 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1329 // Can export from current BB.
1330 if (VI->getParent() == FromBB)
1333 // Is already exported, noop.
1334 return FuncInfo.isExportedInst(V);
1337 // If this is an argument, we can export it if the BB is the entry block or
1338 // if it is already exported.
1339 if (isa<Argument>(V)) {
1340 if (FromBB == &FromBB->getParent()->getEntryBlock())
1343 // Otherwise, can only export this if it is already exported.
1344 return FuncInfo.isExportedInst(V);
1347 // Otherwise, constants can always be exported.
1351 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1352 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1353 const MachineBasicBlock *Dst) const {
1354 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1357 const BasicBlock *SrcBB = Src->getBasicBlock();
1358 const BasicBlock *DstBB = Dst->getBasicBlock();
1359 return BPI->getEdgeWeight(SrcBB, DstBB);
1362 void SelectionDAGBuilder::
1363 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1364 uint32_t Weight /* = 0 */) {
1366 Weight = getEdgeWeight(Src, Dst);
1367 Src->addSuccessor(Dst, Weight);
1371 static bool InBlock(const Value *V, const BasicBlock *BB) {
1372 if (const Instruction *I = dyn_cast<Instruction>(V))
1373 return I->getParent() == BB;
1377 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1378 /// This function emits a branch and is used at the leaves of an OR or an
1379 /// AND operator tree.
1382 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1383 MachineBasicBlock *TBB,
1384 MachineBasicBlock *FBB,
1385 MachineBasicBlock *CurBB,
1386 MachineBasicBlock *SwitchBB,
1389 const BasicBlock *BB = CurBB->getBasicBlock();
1391 // If the leaf of the tree is a comparison, merge the condition into
1393 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1394 // The operands of the cmp have to be in this block. We don't know
1395 // how to export them from some other block. If this is the first block
1396 // of the sequence, no exporting is needed.
1397 if (CurBB == SwitchBB ||
1398 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1399 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1400 ISD::CondCode Condition;
1401 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1402 Condition = getICmpCondCode(IC->getPredicate());
1403 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1404 Condition = getFCmpCondCode(FC->getPredicate());
1405 if (TM.Options.NoNaNsFPMath)
1406 Condition = getFCmpCodeWithoutNaN(Condition);
1408 Condition = ISD::SETEQ; // silence warning.
1409 llvm_unreachable("Unknown compare instruction");
1412 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1413 TBB, FBB, CurBB, TWeight, FWeight);
1414 SwitchCases.push_back(CB);
1419 // Create a CaseBlock record representing this branch.
1420 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1421 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1422 SwitchCases.push_back(CB);
1425 /// Scale down both weights to fit into uint32_t.
1426 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1427 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1428 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1429 NewTrue = NewTrue / Scale;
1430 NewFalse = NewFalse / Scale;
1433 /// FindMergedConditions - If Cond is an expression like
1434 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1435 MachineBasicBlock *TBB,
1436 MachineBasicBlock *FBB,
1437 MachineBasicBlock *CurBB,
1438 MachineBasicBlock *SwitchBB,
1439 unsigned Opc, uint32_t TWeight,
1441 // If this node is not part of the or/and tree, emit it as a branch.
1442 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1443 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1444 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1445 BOp->getParent() != CurBB->getBasicBlock() ||
1446 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1447 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1448 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1453 // Create TmpBB after CurBB.
1454 MachineFunction::iterator BBI = CurBB;
1455 MachineFunction &MF = DAG.getMachineFunction();
1456 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1457 CurBB->getParent()->insert(++BBI, TmpBB);
1459 if (Opc == Instruction::Or) {
1460 // Codegen X | Y as:
1469 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1470 // The requirement is that
1471 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1472 // = TrueProb for orignal BB.
1473 // Assuming the orignal weights are A and B, one choice is to set BB1's
1474 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1476 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1477 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1478 // TmpBB, but the math is more complicated.
1480 uint64_t NewTrueWeight = TWeight;
1481 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1482 ScaleWeights(NewTrueWeight, NewFalseWeight);
1483 // Emit the LHS condition.
1484 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1485 NewTrueWeight, NewFalseWeight);
1487 NewTrueWeight = TWeight;
1488 NewFalseWeight = 2 * (uint64_t)FWeight;
1489 ScaleWeights(NewTrueWeight, NewFalseWeight);
1490 // Emit the RHS condition into TmpBB.
1491 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1492 NewTrueWeight, NewFalseWeight);
1494 assert(Opc == Instruction::And && "Unknown merge op!");
1495 // Codegen X & Y as:
1503 // This requires creation of TmpBB after CurBB.
1505 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1506 // The requirement is that
1507 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1508 // = FalseProb for orignal BB.
1509 // Assuming the orignal weights are A and B, one choice is to set BB1's
1510 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1512 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1514 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1515 uint64_t NewFalseWeight = FWeight;
1516 ScaleWeights(NewTrueWeight, NewFalseWeight);
1517 // Emit the LHS condition.
1518 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1519 NewTrueWeight, NewFalseWeight);
1521 NewTrueWeight = 2 * (uint64_t)TWeight;
1522 NewFalseWeight = FWeight;
1523 ScaleWeights(NewTrueWeight, NewFalseWeight);
1524 // Emit the RHS condition into TmpBB.
1525 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1526 NewTrueWeight, NewFalseWeight);
1530 /// If the set of cases should be emitted as a series of branches, return true.
1531 /// If we should emit this as a bunch of and/or'd together conditions, return
1534 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1535 if (Cases.size() != 2) return true;
1537 // If this is two comparisons of the same values or'd or and'd together, they
1538 // will get folded into a single comparison, so don't emit two blocks.
1539 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1540 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1541 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1542 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1546 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1547 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1548 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1549 Cases[0].CC == Cases[1].CC &&
1550 isa<Constant>(Cases[0].CmpRHS) &&
1551 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1552 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1554 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1561 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1562 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1564 // Update machine-CFG edges.
1565 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1567 // Figure out which block is immediately after the current one.
1568 MachineBasicBlock *NextBlock = nullptr;
1569 MachineFunction::iterator BBI = BrMBB;
1570 if (++BBI != FuncInfo.MF->end())
1573 if (I.isUnconditional()) {
1574 // Update machine-CFG edges.
1575 BrMBB->addSuccessor(Succ0MBB);
1577 // If this is not a fall-through branch or optimizations are switched off,
1579 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1580 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1581 MVT::Other, getControlRoot(),
1582 DAG.getBasicBlock(Succ0MBB)));
1587 // If this condition is one of the special cases we handle, do special stuff
1589 const Value *CondVal = I.getCondition();
1590 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1592 // If this is a series of conditions that are or'd or and'd together, emit
1593 // this as a sequence of branches instead of setcc's with and/or operations.
1594 // As long as jumps are not expensive, this should improve performance.
1595 // For example, instead of something like:
1608 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1609 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1610 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1611 BOp->getOpcode() == Instruction::Or)) {
1612 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1613 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1614 getEdgeWeight(BrMBB, Succ1MBB));
1615 // If the compares in later blocks need to use values not currently
1616 // exported from this block, export them now. This block should always
1617 // be the first entry.
1618 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1620 // Allow some cases to be rejected.
1621 if (ShouldEmitAsBranches(SwitchCases)) {
1622 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1623 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1624 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1627 // Emit the branch for this block.
1628 visitSwitchCase(SwitchCases[0], BrMBB);
1629 SwitchCases.erase(SwitchCases.begin());
1633 // Okay, we decided not to do this, remove any inserted MBB's and clear
1635 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1636 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1638 SwitchCases.clear();
1642 // Create a CaseBlock record representing this branch.
1643 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1644 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1646 // Use visitSwitchCase to actually insert the fast branch sequence for this
1648 visitSwitchCase(CB, BrMBB);
1651 /// visitSwitchCase - Emits the necessary code to represent a single node in
1652 /// the binary search tree resulting from lowering a switch instruction.
1653 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1654 MachineBasicBlock *SwitchBB) {
1656 SDValue CondLHS = getValue(CB.CmpLHS);
1657 SDLoc dl = getCurSDLoc();
1659 // Build the setcc now.
1661 // Fold "(X == true)" to X and "(X == false)" to !X to
1662 // handle common cases produced by branch lowering.
1663 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1664 CB.CC == ISD::SETEQ)
1666 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1667 CB.CC == ISD::SETEQ) {
1668 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1669 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1671 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1673 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1675 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1676 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1678 SDValue CmpOp = getValue(CB.CmpMHS);
1679 EVT VT = CmpOp.getValueType();
1681 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1682 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1685 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1686 VT, CmpOp, DAG.getConstant(Low, VT));
1687 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1688 DAG.getConstant(High-Low, VT), ISD::SETULE);
1692 // Update successor info
1693 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1694 // TrueBB and FalseBB are always different unless the incoming IR is
1695 // degenerate. This only happens when running llc on weird IR.
1696 if (CB.TrueBB != CB.FalseBB)
1697 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1699 // Set NextBlock to be the MBB immediately after the current one, if any.
1700 // This is used to avoid emitting unnecessary branches to the next block.
1701 MachineBasicBlock *NextBlock = nullptr;
1702 MachineFunction::iterator BBI = SwitchBB;
1703 if (++BBI != FuncInfo.MF->end())
1706 // If the lhs block is the next block, invert the condition so that we can
1707 // fall through to the lhs instead of the rhs block.
1708 if (CB.TrueBB == NextBlock) {
1709 std::swap(CB.TrueBB, CB.FalseBB);
1710 SDValue True = DAG.getConstant(1, Cond.getValueType());
1711 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1714 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1715 MVT::Other, getControlRoot(), Cond,
1716 DAG.getBasicBlock(CB.TrueBB));
1718 // Insert the false branch. Do this even if it's a fall through branch,
1719 // this makes it easier to do DAG optimizations which require inverting
1720 // the branch condition.
1721 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1722 DAG.getBasicBlock(CB.FalseBB));
1724 DAG.setRoot(BrCond);
1727 /// visitJumpTable - Emit JumpTable node in the current MBB
1728 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1729 // Emit the code for the jump table
1730 assert(JT.Reg != -1U && "Should lower JT Header first!");
1731 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1732 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1734 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1735 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1736 MVT::Other, Index.getValue(1),
1738 DAG.setRoot(BrJumpTable);
1741 /// visitJumpTableHeader - This function emits necessary code to produce index
1742 /// in the JumpTable from switch case.
1743 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1744 JumpTableHeader &JTH,
1745 MachineBasicBlock *SwitchBB) {
1746 // Subtract the lowest switch case value from the value being switched on and
1747 // conditional branch to default mbb if the result is greater than the
1748 // difference between smallest and largest cases.
1749 SDValue SwitchOp = getValue(JTH.SValue);
1750 EVT VT = SwitchOp.getValueType();
1751 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1752 DAG.getConstant(JTH.First, VT));
1754 // The SDNode we just created, which holds the value being switched on minus
1755 // the smallest case value, needs to be copied to a virtual register so it
1756 // can be used as an index into the jump table in a subsequent basic block.
1757 // This value may be smaller or larger than the target's pointer type, and
1758 // therefore require extension or truncating.
1759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1760 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1762 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1763 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1764 JumpTableReg, SwitchOp);
1765 JT.Reg = JumpTableReg;
1767 // Emit the range check for the jump table, and branch to the default block
1768 // for the switch statement if the value being switched on exceeds the largest
1769 // case in the switch.
1771 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1772 Sub.getValueType()),
1773 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1775 // Set NextBlock to be the MBB immediately after the current one, if any.
1776 // This is used to avoid emitting unnecessary branches to the next block.
1777 MachineBasicBlock *NextBlock = nullptr;
1778 MachineFunction::iterator BBI = SwitchBB;
1780 if (++BBI != FuncInfo.MF->end())
1783 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1784 MVT::Other, CopyTo, CMP,
1785 DAG.getBasicBlock(JT.Default));
1787 if (JT.MBB != NextBlock)
1788 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1789 DAG.getBasicBlock(JT.MBB));
1791 DAG.setRoot(BrCond);
1794 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1795 /// tail spliced into a stack protector check success bb.
1797 /// For a high level explanation of how this fits into the stack protector
1798 /// generation see the comment on the declaration of class
1799 /// StackProtectorDescriptor.
1800 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1801 MachineBasicBlock *ParentBB) {
1803 // First create the loads to the guard/stack slot for the comparison.
1804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1805 EVT PtrTy = TLI.getPointerTy();
1807 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1808 int FI = MFI->getStackProtectorIndex();
1810 const Value *IRGuard = SPD.getGuard();
1811 SDValue GuardPtr = getValue(IRGuard);
1812 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1815 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1819 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1820 // guard value from the virtual register holding the value. Otherwise, emit a
1821 // volatile load to retrieve the stack guard value.
1822 unsigned GuardReg = SPD.getGuardReg();
1824 if (GuardReg && TLI.useLoadStackGuardNode())
1825 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1828 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1829 GuardPtr, MachinePointerInfo(IRGuard, 0),
1830 true, false, false, Align);
1832 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1834 MachinePointerInfo::getFixedStack(FI),
1835 true, false, false, Align);
1837 // Perform the comparison via a subtract/getsetcc.
1838 EVT VT = Guard.getValueType();
1839 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1842 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1843 Sub.getValueType()),
1844 Sub, DAG.getConstant(0, VT), ISD::SETNE);
1846 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1847 // branch to failure MBB.
1848 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1849 MVT::Other, StackSlot.getOperand(0),
1850 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1851 // Otherwise branch to success MBB.
1852 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1854 DAG.getBasicBlock(SPD.getSuccessMBB()));
1859 /// Codegen the failure basic block for a stack protector check.
1861 /// A failure stack protector machine basic block consists simply of a call to
1862 /// __stack_chk_fail().
1864 /// For a high level explanation of how this fits into the stack protector
1865 /// generation see the comment on the declaration of class
1866 /// StackProtectorDescriptor.
1868 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1871 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1872 nullptr, 0, false, getCurSDLoc(), false, false).second;
1876 /// visitBitTestHeader - This function emits necessary code to produce value
1877 /// suitable for "bit tests"
1878 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1879 MachineBasicBlock *SwitchBB) {
1880 // Subtract the minimum value
1881 SDValue SwitchOp = getValue(B.SValue);
1882 EVT VT = SwitchOp.getValueType();
1883 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1884 DAG.getConstant(B.First, VT));
1887 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1889 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1890 Sub.getValueType()),
1891 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1893 // Determine the type of the test operands.
1894 bool UsePtrType = false;
1895 if (!TLI.isTypeLegal(VT))
1898 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1899 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1900 // Switch table case range are encoded into series of masks.
1901 // Just use pointer type, it's guaranteed to fit.
1907 VT = TLI.getPointerTy();
1908 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1911 B.RegVT = VT.getSimpleVT();
1912 B.Reg = FuncInfo.CreateReg(B.RegVT);
1913 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1916 // Set NextBlock to be the MBB immediately after the current one, if any.
1917 // This is used to avoid emitting unnecessary branches to the next block.
1918 MachineBasicBlock *NextBlock = nullptr;
1919 MachineFunction::iterator BBI = SwitchBB;
1920 if (++BBI != FuncInfo.MF->end())
1923 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1925 addSuccessorWithWeight(SwitchBB, B.Default);
1926 addSuccessorWithWeight(SwitchBB, MBB);
1928 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1929 MVT::Other, CopyTo, RangeCmp,
1930 DAG.getBasicBlock(B.Default));
1932 if (MBB != NextBlock)
1933 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1934 DAG.getBasicBlock(MBB));
1936 DAG.setRoot(BrRange);
1939 /// visitBitTestCase - this function produces one "bit test"
1940 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1941 MachineBasicBlock* NextMBB,
1942 uint32_t BranchWeightToNext,
1945 MachineBasicBlock *SwitchBB) {
1947 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1950 unsigned PopCount = CountPopulation_64(B.Mask);
1951 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1952 if (PopCount == 1) {
1953 // Testing for a single bit; just compare the shift count with what it
1954 // would need to be to shift a 1 bit in that position.
1956 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1957 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1958 } else if (PopCount == BB.Range) {
1959 // There is only one zero bit in the range, test for it directly.
1961 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1962 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1964 // Make desired shift
1965 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1966 DAG.getConstant(1, VT), ShiftOp);
1968 // Emit bit tests and jumps
1969 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1970 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1971 Cmp = DAG.getSetCC(getCurSDLoc(),
1972 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1973 DAG.getConstant(0, VT), ISD::SETNE);
1976 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1977 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1978 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1979 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1981 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1982 MVT::Other, getControlRoot(),
1983 Cmp, DAG.getBasicBlock(B.TargetBB));
1985 // Set NextBlock to be the MBB immediately after the current one, if any.
1986 // This is used to avoid emitting unnecessary branches to the next block.
1987 MachineBasicBlock *NextBlock = nullptr;
1988 MachineFunction::iterator BBI = SwitchBB;
1989 if (++BBI != FuncInfo.MF->end())
1992 if (NextMBB != NextBlock)
1993 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1994 DAG.getBasicBlock(NextMBB));
1999 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2000 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2002 // Retrieve successors.
2003 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2004 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2006 const Value *Callee(I.getCalledValue());
2007 const Function *Fn = dyn_cast<Function>(Callee);
2008 if (isa<InlineAsm>(Callee))
2010 else if (Fn && Fn->isIntrinsic()) {
2011 switch (Fn->getIntrinsicID()) {
2013 llvm_unreachable("Cannot invoke this intrinsic");
2014 case Intrinsic::donothing:
2015 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2017 case Intrinsic::experimental_patchpoint_void:
2018 case Intrinsic::experimental_patchpoint_i64:
2019 visitPatchpoint(&I, LandingPad);
2023 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2025 // If the value of the invoke is used outside of its defining block, make it
2026 // available as a virtual register.
2027 CopyToExportRegsIfNeeded(&I);
2029 // Update successor info
2030 addSuccessorWithWeight(InvokeMBB, Return);
2031 addSuccessorWithWeight(InvokeMBB, LandingPad);
2033 // Drop into normal successor.
2034 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2035 MVT::Other, getControlRoot(),
2036 DAG.getBasicBlock(Return)));
2039 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2040 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2043 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2044 assert(FuncInfo.MBB->isLandingPad() &&
2045 "Call to landingpad not in landing pad!");
2047 MachineBasicBlock *MBB = FuncInfo.MBB;
2048 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2049 AddLandingPadInfo(LP, MMI, MBB);
2051 // If there aren't registers to copy the values into (e.g., during SjLj
2052 // exceptions), then don't bother to create these DAG nodes.
2053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2054 if (TLI.getExceptionPointerRegister() == 0 &&
2055 TLI.getExceptionSelectorRegister() == 0)
2058 SmallVector<EVT, 2> ValueVTs;
2059 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2060 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2062 // Get the two live-in registers as SDValues. The physregs have already been
2063 // copied into virtual registers.
2065 Ops[0] = DAG.getZExtOrTrunc(
2066 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2067 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2068 getCurSDLoc(), ValueVTs[0]);
2069 Ops[1] = DAG.getZExtOrTrunc(
2070 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2071 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2072 getCurSDLoc(), ValueVTs[1]);
2075 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2076 DAG.getVTList(ValueVTs), Ops);
2080 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2081 /// small case ranges).
2082 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2083 CaseRecVector& WorkList,
2085 MachineBasicBlock *Default,
2086 MachineBasicBlock *SwitchBB) {
2087 // Size is the number of Cases represented by this range.
2088 size_t Size = CR.Range.second - CR.Range.first;
2092 // Get the MachineFunction which holds the current MBB. This is used when
2093 // inserting any additional MBBs necessary to represent the switch.
2094 MachineFunction *CurMF = FuncInfo.MF;
2096 // Figure out which block is immediately after the current one.
2097 MachineBasicBlock *NextBlock = nullptr;
2098 MachineFunction::iterator BBI = CR.CaseBB;
2100 if (++BBI != FuncInfo.MF->end())
2103 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2104 // If any two of the cases has the same destination, and if one value
2105 // is the same as the other, but has one bit unset that the other has set,
2106 // use bit manipulation to do two compares at once. For example:
2107 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2108 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2109 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2110 if (Size == 2 && CR.CaseBB == SwitchBB) {
2111 Case &Small = *CR.Range.first;
2112 Case &Big = *(CR.Range.second-1);
2114 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2115 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2116 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2118 // Check that there is only one bit different.
2119 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2120 (SmallValue | BigValue) == BigValue) {
2121 // Isolate the common bit.
2122 APInt CommonBit = BigValue & ~SmallValue;
2123 assert((SmallValue | CommonBit) == BigValue &&
2124 CommonBit.countPopulation() == 1 && "Not a common bit?");
2126 SDValue CondLHS = getValue(SV);
2127 EVT VT = CondLHS.getValueType();
2128 SDLoc DL = getCurSDLoc();
2130 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2131 DAG.getConstant(CommonBit, VT));
2132 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2133 Or, DAG.getConstant(BigValue, VT),
2136 // Update successor info.
2137 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2138 addSuccessorWithWeight(SwitchBB, Small.BB,
2139 Small.ExtraWeight + Big.ExtraWeight);
2140 addSuccessorWithWeight(SwitchBB, Default,
2141 // The default destination is the first successor in IR.
2142 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2144 // Insert the true branch.
2145 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2146 getControlRoot(), Cond,
2147 DAG.getBasicBlock(Small.BB));
2149 // Insert the false branch.
2150 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2151 DAG.getBasicBlock(Default));
2153 DAG.setRoot(BrCond);
2159 // Order cases by weight so the most likely case will be checked first.
2160 uint32_t UnhandledWeights = 0;
2162 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2163 uint32_t IWeight = I->ExtraWeight;
2164 UnhandledWeights += IWeight;
2165 for (CaseItr J = CR.Range.first; J < I; ++J) {
2166 uint32_t JWeight = J->ExtraWeight;
2167 if (IWeight > JWeight)
2172 // Rearrange the case blocks so that the last one falls through if possible.
2173 Case &BackCase = *(CR.Range.second-1);
2175 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2176 // The last case block won't fall through into 'NextBlock' if we emit the
2177 // branches in this order. See if rearranging a case value would help.
2178 // We start at the bottom as it's the case with the least weight.
2179 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2180 if (I->BB == NextBlock) {
2181 std::swap(*I, BackCase);
2186 // Create a CaseBlock record representing a conditional branch to
2187 // the Case's target mbb if the value being switched on SV is equal
2189 MachineBasicBlock *CurBlock = CR.CaseBB;
2190 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2191 MachineBasicBlock *FallThrough;
2193 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2194 CurMF->insert(BBI, FallThrough);
2196 // Put SV in a virtual register to make it available from the new blocks.
2197 ExportFromCurrentBlock(SV);
2199 // If the last case doesn't match, go to the default block.
2200 FallThrough = Default;
2203 const Value *RHS, *LHS, *MHS;
2205 if (I->High == I->Low) {
2206 // This is just small small case range :) containing exactly 1 case
2208 LHS = SV; RHS = I->High; MHS = nullptr;
2211 LHS = I->Low; MHS = SV; RHS = I->High;
2214 // The false weight should be sum of all un-handled cases.
2215 UnhandledWeights -= I->ExtraWeight;
2216 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2218 /* trueweight */ I->ExtraWeight,
2219 /* falseweight */ UnhandledWeights);
2221 // If emitting the first comparison, just call visitSwitchCase to emit the
2222 // code into the current block. Otherwise, push the CaseBlock onto the
2223 // vector to be later processed by SDISel, and insert the node's MBB
2224 // before the next MBB.
2225 if (CurBlock == SwitchBB)
2226 visitSwitchCase(CB, SwitchBB);
2228 SwitchCases.push_back(CB);
2230 CurBlock = FallThrough;
2236 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2237 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2238 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2241 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2242 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2243 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2244 return (LastExt - FirstExt + 1ULL);
2247 /// handleJTSwitchCase - Emit jumptable for current switch case range
2248 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2249 CaseRecVector &WorkList,
2251 MachineBasicBlock *Default,
2252 MachineBasicBlock *SwitchBB) {
2253 Case& FrontCase = *CR.Range.first;
2254 Case& BackCase = *(CR.Range.second-1);
2256 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2257 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2259 APInt TSize(First.getBitWidth(), 0);
2260 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2264 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2267 APInt Range = ComputeRange(First, Last);
2268 // The density is TSize / Range. Require at least 40%.
2269 // It should not be possible for IntTSize to saturate for sane code, but make
2270 // sure we handle Range saturation correctly.
2271 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2272 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2273 if (IntTSize * 10 < IntRange * 4)
2276 DEBUG(dbgs() << "Lowering jump table\n"
2277 << "First entry: " << First << ". Last entry: " << Last << '\n'
2278 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2280 // Get the MachineFunction which holds the current MBB. This is used when
2281 // inserting any additional MBBs necessary to represent the switch.
2282 MachineFunction *CurMF = FuncInfo.MF;
2284 // Figure out which block is immediately after the current one.
2285 MachineFunction::iterator BBI = CR.CaseBB;
2288 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2290 // Create a new basic block to hold the code for loading the address
2291 // of the jump table, and jumping to it. Update successor information;
2292 // we will either branch to the default case for the switch, or the jump
2294 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2295 CurMF->insert(BBI, JumpTableBB);
2297 addSuccessorWithWeight(CR.CaseBB, Default);
2298 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2300 // Build a vector of destination BBs, corresponding to each target
2301 // of the jump table. If the value of the jump table slot corresponds to
2302 // a case statement, push the case's BB onto the vector, otherwise, push
2304 std::vector<MachineBasicBlock*> DestBBs;
2306 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2307 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2308 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2310 if (Low.sle(TEI) && TEI.sle(High)) {
2311 DestBBs.push_back(I->BB);
2315 DestBBs.push_back(Default);
2319 // Calculate weight for each unique destination in CR.
2320 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2322 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2323 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2324 DestWeights.find(I->BB);
2325 if (Itr != DestWeights.end())
2326 Itr->second += I->ExtraWeight;
2328 DestWeights[I->BB] = I->ExtraWeight;
2331 // Update successor info. Add one edge to each unique successor.
2332 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2333 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2334 E = DestBBs.end(); I != E; ++I) {
2335 if (!SuccsHandled[(*I)->getNumber()]) {
2336 SuccsHandled[(*I)->getNumber()] = true;
2337 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2338 DestWeights.find(*I);
2339 addSuccessorWithWeight(JumpTableBB, *I,
2340 Itr != DestWeights.end() ? Itr->second : 0);
2344 // Create a jump table index for this jump table.
2345 unsigned JTEncoding = TLI.getJumpTableEncoding();
2346 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2347 ->createJumpTableIndex(DestBBs);
2349 // Set the jump table information so that we can codegen it as a second
2350 // MachineBasicBlock
2351 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2352 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2353 if (CR.CaseBB == SwitchBB)
2354 visitJumpTableHeader(JT, JTH, SwitchBB);
2356 JTCases.push_back(JumpTableBlock(JTH, JT));
2360 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2362 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2363 CaseRecVector& WorkList,
2365 MachineBasicBlock* SwitchBB) {
2366 // Get the MachineFunction which holds the current MBB. This is used when
2367 // inserting any additional MBBs necessary to represent the switch.
2368 MachineFunction *CurMF = FuncInfo.MF;
2370 // Figure out which block is immediately after the current one.
2371 MachineFunction::iterator BBI = CR.CaseBB;
2374 Case& FrontCase = *CR.Range.first;
2375 Case& BackCase = *(CR.Range.second-1);
2376 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2378 // Size is the number of Cases represented by this range.
2379 unsigned Size = CR.Range.second - CR.Range.first;
2381 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2382 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2384 CaseItr Pivot = CR.Range.first + Size/2;
2386 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2387 // (heuristically) allow us to emit JumpTable's later.
2388 APInt TSize(First.getBitWidth(), 0);
2389 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2393 APInt LSize = FrontCase.size();
2394 APInt RSize = TSize-LSize;
2395 DEBUG(dbgs() << "Selecting best pivot: \n"
2396 << "First: " << First << ", Last: " << Last <<'\n'
2397 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2398 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2400 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2401 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2402 APInt Range = ComputeRange(LEnd, RBegin);
2403 assert((Range - 2ULL).isNonNegative() &&
2404 "Invalid case distance");
2405 // Use volatile double here to avoid excess precision issues on some hosts,
2406 // e.g. that use 80-bit X87 registers.
2407 volatile double LDensity =
2408 (double)LSize.roundToDouble() /
2409 (LEnd - First + 1ULL).roundToDouble();
2410 volatile double RDensity =
2411 (double)RSize.roundToDouble() /
2412 (Last - RBegin + 1ULL).roundToDouble();
2413 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2414 // Should always split in some non-trivial place
2415 DEBUG(dbgs() <<"=>Step\n"
2416 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2417 << "LDensity: " << LDensity
2418 << ", RDensity: " << RDensity << '\n'
2419 << "Metric: " << Metric << '\n');
2420 if (FMetric < Metric) {
2423 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2430 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2431 if (areJTsAllowed(TLI)) {
2432 // If our case is dense we *really* should handle it earlier!
2433 assert((FMetric > 0) && "Should handle dense range earlier!");
2435 Pivot = CR.Range.first + Size/2;
2438 CaseRange LHSR(CR.Range.first, Pivot);
2439 CaseRange RHSR(Pivot, CR.Range.second);
2440 const Constant *C = Pivot->Low;
2441 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2443 // We know that we branch to the LHS if the Value being switched on is
2444 // less than the Pivot value, C. We use this to optimize our binary
2445 // tree a bit, by recognizing that if SV is greater than or equal to the
2446 // LHS's Case Value, and that Case Value is exactly one less than the
2447 // Pivot's Value, then we can branch directly to the LHS's Target,
2448 // rather than creating a leaf node for it.
2449 if ((LHSR.second - LHSR.first) == 1 &&
2450 LHSR.first->High == CR.GE &&
2451 cast<ConstantInt>(C)->getValue() ==
2452 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2453 TrueBB = LHSR.first->BB;
2455 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2456 CurMF->insert(BBI, TrueBB);
2457 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2459 // Put SV in a virtual register to make it available from the new blocks.
2460 ExportFromCurrentBlock(SV);
2463 // Similar to the optimization above, if the Value being switched on is
2464 // known to be less than the Constant CR.LT, and the current Case Value
2465 // is CR.LT - 1, then we can branch directly to the target block for
2466 // the current Case Value, rather than emitting a RHS leaf node for it.
2467 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2468 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2469 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2470 FalseBB = RHSR.first->BB;
2472 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2473 CurMF->insert(BBI, FalseBB);
2474 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2476 // Put SV in a virtual register to make it available from the new blocks.
2477 ExportFromCurrentBlock(SV);
2480 // Create a CaseBlock record representing a conditional branch to
2481 // the LHS node if the value being switched on SV is less than C.
2482 // Otherwise, branch to LHS.
2483 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2485 if (CR.CaseBB == SwitchBB)
2486 visitSwitchCase(CB, SwitchBB);
2488 SwitchCases.push_back(CB);
2493 /// handleBitTestsSwitchCase - if current case range has few destination and
2494 /// range span less, than machine word bitwidth, encode case range into series
2495 /// of masks and emit bit tests with these masks.
2496 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2497 CaseRecVector& WorkList,
2499 MachineBasicBlock* Default,
2500 MachineBasicBlock* SwitchBB) {
2501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2502 EVT PTy = TLI.getPointerTy();
2503 unsigned IntPtrBits = PTy.getSizeInBits();
2505 Case& FrontCase = *CR.Range.first;
2506 Case& BackCase = *(CR.Range.second-1);
2508 // Get the MachineFunction which holds the current MBB. This is used when
2509 // inserting any additional MBBs necessary to represent the switch.
2510 MachineFunction *CurMF = FuncInfo.MF;
2512 // If target does not have legal shift left, do not emit bit tests at all.
2513 if (!TLI.isOperationLegal(ISD::SHL, PTy))
2517 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2519 // Single case counts one, case range - two.
2520 numCmps += (I->Low == I->High ? 1 : 2);
2523 // Count unique destinations
2524 SmallSet<MachineBasicBlock*, 4> Dests;
2525 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2526 Dests.insert(I->BB);
2527 if (Dests.size() > 3)
2528 // Don't bother the code below, if there are too much unique destinations
2531 DEBUG(dbgs() << "Total number of unique destinations: "
2532 << Dests.size() << '\n'
2533 << "Total number of comparisons: " << numCmps << '\n');
2535 // Compute span of values.
2536 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2537 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2538 APInt cmpRange = maxValue - minValue;
2540 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2541 << "Low bound: " << minValue << '\n'
2542 << "High bound: " << maxValue << '\n');
2544 if (cmpRange.uge(IntPtrBits) ||
2545 (!(Dests.size() == 1 && numCmps >= 3) &&
2546 !(Dests.size() == 2 && numCmps >= 5) &&
2547 !(Dests.size() >= 3 && numCmps >= 6)))
2550 DEBUG(dbgs() << "Emitting bit tests\n");
2551 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2553 // Optimize the case where all the case values fit in a
2554 // word without having to subtract minValue. In this case,
2555 // we can optimize away the subtraction.
2556 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2557 cmpRange = maxValue;
2559 lowBound = minValue;
2562 CaseBitsVector CasesBits;
2563 unsigned i, count = 0;
2565 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2566 MachineBasicBlock* Dest = I->BB;
2567 for (i = 0; i < count; ++i)
2568 if (Dest == CasesBits[i].BB)
2572 assert((count < 3) && "Too much destinations to test!");
2573 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2577 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2578 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2580 uint64_t lo = (lowValue - lowBound).getZExtValue();
2581 uint64_t hi = (highValue - lowBound).getZExtValue();
2582 CasesBits[i].ExtraWeight += I->ExtraWeight;
2584 for (uint64_t j = lo; j <= hi; j++) {
2585 CasesBits[i].Mask |= 1ULL << j;
2586 CasesBits[i].Bits++;
2590 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2594 // Figure out which block is immediately after the current one.
2595 MachineFunction::iterator BBI = CR.CaseBB;
2598 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2600 DEBUG(dbgs() << "Cases:\n");
2601 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2602 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2603 << ", Bits: " << CasesBits[i].Bits
2604 << ", BB: " << CasesBits[i].BB << '\n');
2606 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2607 CurMF->insert(BBI, CaseBB);
2608 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2610 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2612 // Put SV in a virtual register to make it available from the new blocks.
2613 ExportFromCurrentBlock(SV);
2616 BitTestBlock BTB(lowBound, cmpRange, SV,
2617 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2618 CR.CaseBB, Default, std::move(BTC));
2620 if (CR.CaseBB == SwitchBB)
2621 visitBitTestHeader(BTB, SwitchBB);
2623 BitTestCases.push_back(std::move(BTB));
2628 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2629 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2630 const SwitchInst& SI) {
2631 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2632 // Start with "simple" cases
2633 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2635 const BasicBlock *SuccBB = i.getCaseSuccessor();
2636 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2638 uint32_t ExtraWeight =
2639 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2641 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2642 SMBB, ExtraWeight));
2644 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2646 // Merge case into clusters
2647 if (Cases.size() >= 2)
2648 // Must recompute end() each iteration because it may be
2649 // invalidated by erase if we hold on to it
2650 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2651 J != Cases.end(); ) {
2652 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2653 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2654 MachineBasicBlock* nextBB = J->BB;
2655 MachineBasicBlock* currentBB = I->BB;
2657 // If the two neighboring cases go to the same destination, merge them
2658 // into a single case.
2659 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2661 I->ExtraWeight += J->ExtraWeight;
2670 for (auto &I : Cases)
2671 // A range counts double, since it requires two compares.
2672 numCmps += I.Low != I.High ? 2 : 1;
2674 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2675 << ". Total compares: " << numCmps << '\n';
2679 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2680 MachineBasicBlock *Last) {
2682 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2683 if (JTCases[i].first.HeaderBB == First)
2684 JTCases[i].first.HeaderBB = Last;
2686 // Update BitTestCases.
2687 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2688 if (BitTestCases[i].Parent == First)
2689 BitTestCases[i].Parent = Last;
2692 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2693 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2695 // Figure out which block is immediately after the current one.
2696 MachineBasicBlock *NextBlock = nullptr;
2697 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2699 // If there is only the default destination, branch to it if it is not the
2700 // next basic block. Otherwise, just fall through.
2701 if (!SI.getNumCases()) {
2702 // Update machine-CFG edges.
2704 // If this is not a fall-through branch, emit the branch.
2705 SwitchMBB->addSuccessor(Default);
2706 if (Default != NextBlock)
2707 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2708 MVT::Other, getControlRoot(),
2709 DAG.getBasicBlock(Default)));
2714 // If there are any non-default case statements, create a vector of Cases
2715 // representing each one, and sort the vector so that we can efficiently
2716 // create a binary search tree from them.
2718 Clusterify(Cases, SI);
2720 // Get the Value to be switched on and default basic blocks, which will be
2721 // inserted into CaseBlock records, representing basic blocks in the binary
2723 const Value *SV = SI.getCondition();
2725 // Push the initial CaseRec onto the worklist
2726 CaseRecVector WorkList;
2727 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2728 CaseRange(Cases.begin(),Cases.end())));
2730 while (!WorkList.empty()) {
2731 // Grab a record representing a case range to process off the worklist
2732 CaseRec CR = WorkList.back();
2733 WorkList.pop_back();
2735 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2738 // If the range has few cases (two or less) emit a series of specific
2740 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2743 // If the switch has more than N blocks, and is at least 40% dense, and the
2744 // target supports indirect branches, then emit a jump table rather than
2745 // lowering the switch to a binary tree of conditional branches.
2746 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2747 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2750 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2751 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2752 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2756 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2757 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2759 // Update machine-CFG edges with unique successors.
2760 SmallSet<BasicBlock*, 32> Done;
2761 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2762 BasicBlock *BB = I.getSuccessor(i);
2763 bool Inserted = Done.insert(BB);
2767 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2768 addSuccessorWithWeight(IndirectBrMBB, Succ);
2771 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2772 MVT::Other, getControlRoot(),
2773 getValue(I.getAddress())));
2776 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2777 if (DAG.getTarget().Options.TrapUnreachable)
2778 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2781 void SelectionDAGBuilder::visitFSub(const User &I) {
2782 // -0.0 - X --> fneg
2783 Type *Ty = I.getType();
2784 if (isa<Constant>(I.getOperand(0)) &&
2785 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2786 SDValue Op2 = getValue(I.getOperand(1));
2787 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2788 Op2.getValueType(), Op2));
2792 visitBinary(I, ISD::FSUB);
2795 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2796 SDValue Op1 = getValue(I.getOperand(0));
2797 SDValue Op2 = getValue(I.getOperand(1));
2802 if (const OverflowingBinaryOperator *OFBinOp =
2803 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2804 nuw = OFBinOp->hasNoUnsignedWrap();
2805 nsw = OFBinOp->hasNoSignedWrap();
2807 if (const PossiblyExactOperator *ExactOp =
2808 dyn_cast<const PossiblyExactOperator>(&I))
2809 exact = ExactOp->isExact();
2811 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2812 Op1, Op2, nuw, nsw, exact);
2813 setValue(&I, BinNodeValue);
2816 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2817 SDValue Op1 = getValue(I.getOperand(0));
2818 SDValue Op2 = getValue(I.getOperand(1));
2821 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2823 // Coerce the shift amount to the right type if we can.
2824 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2825 unsigned ShiftSize = ShiftTy.getSizeInBits();
2826 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2827 SDLoc DL = getCurSDLoc();
2829 // If the operand is smaller than the shift count type, promote it.
2830 if (ShiftSize > Op2Size)
2831 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2833 // If the operand is larger than the shift count type but the shift
2834 // count type has enough bits to represent any shift value, truncate
2835 // it now. This is a common case and it exposes the truncate to
2836 // optimization early.
2837 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2838 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2839 // Otherwise we'll need to temporarily settle for some other convenient
2840 // type. Type legalization will make adjustments once the shiftee is split.
2842 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2849 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2851 if (const OverflowingBinaryOperator *OFBinOp =
2852 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2853 nuw = OFBinOp->hasNoUnsignedWrap();
2854 nsw = OFBinOp->hasNoSignedWrap();
2856 if (const PossiblyExactOperator *ExactOp =
2857 dyn_cast<const PossiblyExactOperator>(&I))
2858 exact = ExactOp->isExact();
2861 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2866 void SelectionDAGBuilder::visitSDiv(const User &I) {
2867 SDValue Op1 = getValue(I.getOperand(0));
2868 SDValue Op2 = getValue(I.getOperand(1));
2870 // Turn exact SDivs into multiplications.
2871 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2873 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2874 !isa<ConstantSDNode>(Op1) &&
2875 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2876 setValue(&I, DAG.getTargetLoweringInfo()
2877 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2879 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2883 void SelectionDAGBuilder::visitICmp(const User &I) {
2884 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2885 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2886 predicate = IC->getPredicate();
2887 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2888 predicate = ICmpInst::Predicate(IC->getPredicate());
2889 SDValue Op1 = getValue(I.getOperand(0));
2890 SDValue Op2 = getValue(I.getOperand(1));
2891 ISD::CondCode Opcode = getICmpCondCode(predicate);
2893 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2894 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2897 void SelectionDAGBuilder::visitFCmp(const User &I) {
2898 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2899 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2900 predicate = FC->getPredicate();
2901 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2902 predicate = FCmpInst::Predicate(FC->getPredicate());
2903 SDValue Op1 = getValue(I.getOperand(0));
2904 SDValue Op2 = getValue(I.getOperand(1));
2905 ISD::CondCode Condition = getFCmpCondCode(predicate);
2906 if (TM.Options.NoNaNsFPMath)
2907 Condition = getFCmpCodeWithoutNaN(Condition);
2908 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2909 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2912 void SelectionDAGBuilder::visitSelect(const User &I) {
2913 SmallVector<EVT, 4> ValueVTs;
2914 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2915 unsigned NumValues = ValueVTs.size();
2916 if (NumValues == 0) return;
2918 SmallVector<SDValue, 4> Values(NumValues);
2919 SDValue Cond = getValue(I.getOperand(0));
2920 SDValue TrueVal = getValue(I.getOperand(1));
2921 SDValue FalseVal = getValue(I.getOperand(2));
2922 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2923 ISD::VSELECT : ISD::SELECT;
2925 for (unsigned i = 0; i != NumValues; ++i)
2926 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2927 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2929 SDValue(TrueVal.getNode(),
2930 TrueVal.getResNo() + i),
2931 SDValue(FalseVal.getNode(),
2932 FalseVal.getResNo() + i));
2934 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2935 DAG.getVTList(ValueVTs), Values));
2938 void SelectionDAGBuilder::visitTrunc(const User &I) {
2939 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2940 SDValue N = getValue(I.getOperand(0));
2941 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2942 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2945 void SelectionDAGBuilder::visitZExt(const User &I) {
2946 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2947 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2948 SDValue N = getValue(I.getOperand(0));
2949 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2950 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2953 void SelectionDAGBuilder::visitSExt(const User &I) {
2954 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2955 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2956 SDValue N = getValue(I.getOperand(0));
2957 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2958 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2961 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2962 // FPTrunc is never a no-op cast, no need to check
2963 SDValue N = getValue(I.getOperand(0));
2964 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2965 EVT DestVT = TLI.getValueType(I.getType());
2966 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2967 DAG.getTargetConstant(0, TLI.getPointerTy())));
2970 void SelectionDAGBuilder::visitFPExt(const User &I) {
2971 // FPExt is never a no-op cast, no need to check
2972 SDValue N = getValue(I.getOperand(0));
2973 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2974 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2977 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2978 // FPToUI is never a no-op cast, no need to check
2979 SDValue N = getValue(I.getOperand(0));
2980 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2981 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2984 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2985 // FPToSI is never a no-op cast, no need to check
2986 SDValue N = getValue(I.getOperand(0));
2987 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2988 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2991 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2992 // UIToFP is never a no-op cast, no need to check
2993 SDValue N = getValue(I.getOperand(0));
2994 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2995 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2998 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2999 // SIToFP is never a no-op cast, no need to check
3000 SDValue N = getValue(I.getOperand(0));
3001 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3002 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3005 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3006 // What to do depends on the size of the integer and the size of the pointer.
3007 // We can either truncate, zero extend, or no-op, accordingly.
3008 SDValue N = getValue(I.getOperand(0));
3009 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3010 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3013 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3014 // What to do depends on the size of the integer and the size of the pointer.
3015 // We can either truncate, zero extend, or no-op, accordingly.
3016 SDValue N = getValue(I.getOperand(0));
3017 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3018 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3021 void SelectionDAGBuilder::visitBitCast(const User &I) {
3022 SDValue N = getValue(I.getOperand(0));
3023 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3025 // BitCast assures us that source and destination are the same size so this is
3026 // either a BITCAST or a no-op.
3027 if (DestVT != N.getValueType())
3028 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3029 DestVT, N)); // convert types.
3030 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3031 // might fold any kind of constant expression to an integer constant and that
3032 // is not what we are looking for. Only regcognize a bitcast of a genuine
3033 // constant integer as an opaque constant.
3034 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3035 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3038 setValue(&I, N); // noop cast.
3041 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3042 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3043 const Value *SV = I.getOperand(0);
3044 SDValue N = getValue(SV);
3045 EVT DestVT = TLI.getValueType(I.getType());
3047 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3048 unsigned DestAS = I.getType()->getPointerAddressSpace();
3050 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3051 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3056 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3058 SDValue InVec = getValue(I.getOperand(0));
3059 SDValue InVal = getValue(I.getOperand(1));
3060 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3061 getCurSDLoc(), TLI.getVectorIdxTy());
3062 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3063 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3066 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3067 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3068 SDValue InVec = getValue(I.getOperand(0));
3069 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3070 getCurSDLoc(), TLI.getVectorIdxTy());
3071 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3072 TLI.getValueType(I.getType()), InVec, InIdx));
3075 // Utility for visitShuffleVector - Return true if every element in Mask,
3076 // beginning from position Pos and ending in Pos+Size, falls within the
3077 // specified sequential range [L, L+Pos). or is undef.
3078 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3079 unsigned Pos, unsigned Size, int Low) {
3080 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3081 if (Mask[i] >= 0 && Mask[i] != Low)
3086 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3087 SDValue Src1 = getValue(I.getOperand(0));
3088 SDValue Src2 = getValue(I.getOperand(1));
3090 SmallVector<int, 8> Mask;
3091 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3092 unsigned MaskNumElts = Mask.size();
3094 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3095 EVT VT = TLI.getValueType(I.getType());
3096 EVT SrcVT = Src1.getValueType();
3097 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3099 if (SrcNumElts == MaskNumElts) {
3100 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3105 // Normalize the shuffle vector since mask and vector length don't match.
3106 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3107 // Mask is longer than the source vectors and is a multiple of the source
3108 // vectors. We can use concatenate vector to make the mask and vectors
3110 if (SrcNumElts*2 == MaskNumElts) {
3111 // First check for Src1 in low and Src2 in high
3112 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3113 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3114 // The shuffle is concatenating two vectors together.
3115 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3119 // Then check for Src2 in low and Src1 in high
3120 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3121 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3122 // The shuffle is concatenating two vectors together.
3123 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3129 // Pad both vectors with undefs to make them the same length as the mask.
3130 unsigned NumConcat = MaskNumElts / SrcNumElts;
3131 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3132 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3133 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3135 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3136 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3140 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3141 getCurSDLoc(), VT, MOps1);
3142 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3143 getCurSDLoc(), VT, MOps2);
3145 // Readjust mask for new input vector length.
3146 SmallVector<int, 8> MappedOps;
3147 for (unsigned i = 0; i != MaskNumElts; ++i) {
3149 if (Idx >= (int)SrcNumElts)
3150 Idx -= SrcNumElts - MaskNumElts;
3151 MappedOps.push_back(Idx);
3154 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3159 if (SrcNumElts > MaskNumElts) {
3160 // Analyze the access pattern of the vector to see if we can extract
3161 // two subvectors and do the shuffle. The analysis is done by calculating
3162 // the range of elements the mask access on both vectors.
3163 int MinRange[2] = { static_cast<int>(SrcNumElts),
3164 static_cast<int>(SrcNumElts)};
3165 int MaxRange[2] = {-1, -1};
3167 for (unsigned i = 0; i != MaskNumElts; ++i) {
3173 if (Idx >= (int)SrcNumElts) {
3177 if (Idx > MaxRange[Input])
3178 MaxRange[Input] = Idx;
3179 if (Idx < MinRange[Input])
3180 MinRange[Input] = Idx;
3183 // Check if the access is smaller than the vector size and can we find
3184 // a reasonable extract index.
3185 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3187 int StartIdx[2]; // StartIdx to extract from
3188 for (unsigned Input = 0; Input < 2; ++Input) {
3189 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3190 RangeUse[Input] = 0; // Unused
3191 StartIdx[Input] = 0;
3195 // Find a good start index that is a multiple of the mask length. Then
3196 // see if the rest of the elements are in range.
3197 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3198 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3199 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3200 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3203 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3204 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3207 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3208 // Extract appropriate subvector and generate a vector shuffle
3209 for (unsigned Input = 0; Input < 2; ++Input) {
3210 SDValue &Src = Input == 0 ? Src1 : Src2;
3211 if (RangeUse[Input] == 0)
3212 Src = DAG.getUNDEF(VT);
3215 ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3216 DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
3219 // Calculate new mask.
3220 SmallVector<int, 8> MappedOps;
3221 for (unsigned i = 0; i != MaskNumElts; ++i) {
3224 if (Idx < (int)SrcNumElts)
3227 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3229 MappedOps.push_back(Idx);
3232 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3238 // We can't use either concat vectors or extract subvectors so fall back to
3239 // replacing the shuffle with extract and build vector.
3240 // to insert and build vector.
3241 EVT EltVT = VT.getVectorElementType();
3242 EVT IdxVT = TLI.getVectorIdxTy();
3243 SmallVector<SDValue,8> Ops;
3244 for (unsigned i = 0; i != MaskNumElts; ++i) {
3249 Res = DAG.getUNDEF(EltVT);
3251 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3252 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3254 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3255 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3261 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
3264 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3265 const Value *Op0 = I.getOperand(0);
3266 const Value *Op1 = I.getOperand(1);
3267 Type *AggTy = I.getType();
3268 Type *ValTy = Op1->getType();
3269 bool IntoUndef = isa<UndefValue>(Op0);
3270 bool FromUndef = isa<UndefValue>(Op1);
3272 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275 SmallVector<EVT, 4> AggValueVTs;
3276 ComputeValueVTs(TLI, AggTy, AggValueVTs);
3277 SmallVector<EVT, 4> ValValueVTs;
3278 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3280 unsigned NumAggValues = AggValueVTs.size();
3281 unsigned NumValValues = ValValueVTs.size();
3282 SmallVector<SDValue, 4> Values(NumAggValues);
3284 // Ignore an insertvalue that produces an empty object
3285 if (!NumAggValues) {
3286 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3290 SDValue Agg = getValue(Op0);
3292 // Copy the beginning value(s) from the original aggregate.
3293 for (; i != LinearIndex; ++i)
3294 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3295 SDValue(Agg.getNode(), Agg.getResNo() + i);
3296 // Copy values from the inserted value(s).
3298 SDValue Val = getValue(Op1);
3299 for (; i != LinearIndex + NumValValues; ++i)
3300 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3301 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3303 // Copy remaining value(s) from the original aggregate.
3304 for (; i != NumAggValues; ++i)
3305 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3306 SDValue(Agg.getNode(), Agg.getResNo() + i);
3308 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3309 DAG.getVTList(AggValueVTs), Values));
3312 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3313 const Value *Op0 = I.getOperand(0);
3314 Type *AggTy = Op0->getType();
3315 Type *ValTy = I.getType();
3316 bool OutOfUndef = isa<UndefValue>(Op0);
3318 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3320 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3321 SmallVector<EVT, 4> ValValueVTs;
3322 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3324 unsigned NumValValues = ValValueVTs.size();
3326 // Ignore a extractvalue that produces an empty object
3327 if (!NumValValues) {
3328 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3332 SmallVector<SDValue, 4> Values(NumValValues);
3334 SDValue Agg = getValue(Op0);
3335 // Copy out the selected value(s).
3336 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3337 Values[i - LinearIndex] =
3339 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3340 SDValue(Agg.getNode(), Agg.getResNo() + i);
3342 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3343 DAG.getVTList(ValValueVTs), Values));
3346 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3347 Value *Op0 = I.getOperand(0);
3348 // Note that the pointer operand may be a vector of pointers. Take the scalar
3349 // element which holds a pointer.
3350 Type *Ty = Op0->getType()->getScalarType();
3351 unsigned AS = Ty->getPointerAddressSpace();
3352 SDValue N = getValue(Op0);
3354 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3356 const Value *Idx = *OI;
3357 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3358 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3361 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3362 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3363 DAG.getConstant(Offset, N.getValueType()));
3366 Ty = StTy->getElementType(Field);
3368 Ty = cast<SequentialType>(Ty)->getElementType();
3370 // If this is a constant subscript, handle it quickly.
3371 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3372 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3373 if (CI->isZero()) continue;
3375 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3377 EVT PTy = TLI.getPointerTy(AS);
3378 unsigned PtrBits = PTy.getSizeInBits();
3380 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3381 DAG.getConstant(Offs, MVT::i64));
3383 OffsVal = DAG.getConstant(Offs, PTy);
3385 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3390 // N = N + Idx * ElementSize;
3392 APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
3393 SDValue IdxN = getValue(Idx);
3395 // If the index is smaller or larger than intptr_t, truncate or extend
3397 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3399 // If this is a multiply by a power of two, turn it into a shl
3400 // immediately. This is a very common case.
3401 if (ElementSize != 1) {
3402 if (ElementSize.isPowerOf2()) {
3403 unsigned Amt = ElementSize.logBase2();
3404 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3405 N.getValueType(), IdxN,
3406 DAG.getConstant(Amt, IdxN.getValueType()));
3408 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3409 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3410 N.getValueType(), IdxN, Scale);
3414 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3415 N.getValueType(), N, IdxN);
3422 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3423 // If this is a fixed sized alloca in the entry block of the function,
3424 // allocate it statically on the stack.
3425 if (FuncInfo.StaticAllocaMap.count(&I))
3426 return; // getValue will auto-populate this.
3428 Type *Ty = I.getAllocatedType();
3429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3430 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
3432 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3435 SDValue AllocSize = getValue(I.getArraySize());
3437 EVT IntPtr = TLI.getPointerTy();
3438 if (AllocSize.getValueType() != IntPtr)
3439 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3441 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3443 DAG.getConstant(TySize, IntPtr));
3445 // Handle alignment. If the requested alignment is less than or equal to
3446 // the stack alignment, ignore it. If the size is greater than or equal to
3447 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3448 unsigned StackAlign =
3449 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3450 if (Align <= StackAlign)
3453 // Round the size of the allocation up to the stack alignment size
3454 // by add SA-1 to the size.
3455 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3456 AllocSize.getValueType(), AllocSize,
3457 DAG.getIntPtrConstant(StackAlign-1));
3459 // Mask out the low bits for alignment purposes.
3460 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3461 AllocSize.getValueType(), AllocSize,
3462 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3464 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3465 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3466 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
3468 DAG.setRoot(DSA.getValue(1));
3470 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3473 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3475 return visitAtomicLoad(I);
3477 const Value *SV = I.getOperand(0);
3478 SDValue Ptr = getValue(SV);
3480 Type *Ty = I.getType();
3482 bool isVolatile = I.isVolatile();
3483 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3484 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3485 unsigned Alignment = I.getAlignment();
3488 I.getAAMetadata(AAInfo);
3489 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3491 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3492 SmallVector<EVT, 4> ValueVTs;
3493 SmallVector<uint64_t, 4> Offsets;
3494 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3495 unsigned NumValues = ValueVTs.size();
3500 bool ConstantMemory = false;
3501 if (isVolatile || NumValues > MaxParallelChains)
3502 // Serialize volatile loads with other side effects.
3504 else if (AA->pointsToConstantMemory(
3505 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
3506 // Do not serialize (non-volatile) loads of constant memory with anything.
3507 Root = DAG.getEntryNode();
3508 ConstantMemory = true;
3510 // Do not serialize non-volatile loads against each other.
3511 Root = DAG.getRoot();
3515 Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3517 SmallVector<SDValue, 4> Values(NumValues);
3518 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3520 EVT PtrVT = Ptr.getValueType();
3521 unsigned ChainI = 0;
3522 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3523 // Serializing loads here may result in excessive register pressure, and
3524 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3525 // could recover a bit by hoisting nodes upward in the chain by recognizing
3526 // they are side-effect free or do not alias. The optimizer should really
3527 // avoid this case by converting large object/array copies to llvm.memcpy
3528 // (MaxParallelChains should always remain as failsafe).
3529 if (ChainI == MaxParallelChains) {
3530 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3531 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3532 makeArrayRef(Chains.data(), ChainI));
3536 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3538 DAG.getConstant(Offsets[i], PtrVT));
3539 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3540 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3541 isNonTemporal, isInvariant, Alignment, AAInfo,
3545 Chains[ChainI] = L.getValue(1);
3548 if (!ConstantMemory) {
3549 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3550 makeArrayRef(Chains.data(), ChainI));
3554 PendingLoads.push_back(Chain);
3557 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3558 DAG.getVTList(ValueVTs), Values));
3561 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3563 return visitAtomicStore(I);
3565 const Value *SrcV = I.getOperand(0);
3566 const Value *PtrV = I.getOperand(1);
3568 SmallVector<EVT, 4> ValueVTs;
3569 SmallVector<uint64_t, 4> Offsets;
3570 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
3571 ValueVTs, &Offsets);
3572 unsigned NumValues = ValueVTs.size();
3576 // Get the lowered operands. Note that we do this after
3577 // checking if NumResults is zero, because with zero results
3578 // the operands won't have values in the map.
3579 SDValue Src = getValue(SrcV);
3580 SDValue Ptr = getValue(PtrV);
3582 SDValue Root = getRoot();
3583 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3585 EVT PtrVT = Ptr.getValueType();
3586 bool isVolatile = I.isVolatile();
3587 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3588 unsigned Alignment = I.getAlignment();
3591 I.getAAMetadata(AAInfo);
3593 unsigned ChainI = 0;
3594 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3595 // See visitLoad comments.
3596 if (ChainI == MaxParallelChains) {
3597 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3598 makeArrayRef(Chains.data(), ChainI));
3602 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3603 DAG.getConstant(Offsets[i], PtrVT));
3604 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3605 SDValue(Src.getNode(), Src.getResNo() + i),
3606 Add, MachinePointerInfo(PtrV, Offsets[i]),
3607 isVolatile, isNonTemporal, Alignment, AAInfo);
3608 Chains[ChainI] = St;
3611 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3612 makeArrayRef(Chains.data(), ChainI));
3613 DAG.setRoot(StoreNode);
3616 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3617 SDLoc dl = getCurSDLoc();
3618 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3619 AtomicOrdering FailureOrder = I.getFailureOrdering();
3620 SynchronizationScope Scope = I.getSynchScope();
3622 SDValue InChain = getRoot();
3624 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3625 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3626 SDValue L = DAG.getAtomicCmpSwap(
3627 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3628 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3629 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3630 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3632 SDValue OutChain = L.getValue(2);
3635 DAG.setRoot(OutChain);
3638 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3639 SDLoc dl = getCurSDLoc();
3641 switch (I.getOperation()) {
3642 default: llvm_unreachable("Unknown atomicrmw operation");
3643 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3644 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3645 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3646 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3647 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3648 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3649 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3650 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3651 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3652 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3653 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3655 AtomicOrdering Order = I.getOrdering();
3656 SynchronizationScope Scope = I.getSynchScope();
3658 SDValue InChain = getRoot();
3661 DAG.getAtomic(NT, dl,
3662 getValue(I.getValOperand()).getSimpleValueType(),
3664 getValue(I.getPointerOperand()),
3665 getValue(I.getValOperand()),
3666 I.getPointerOperand(),
3667 /* Alignment=*/ 0, Order, Scope);
3669 SDValue OutChain = L.getValue(1);
3672 DAG.setRoot(OutChain);
3675 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3676 SDLoc dl = getCurSDLoc();
3677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3680 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3681 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3682 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3685 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3686 SDLoc dl = getCurSDLoc();
3687 AtomicOrdering Order = I.getOrdering();
3688 SynchronizationScope Scope = I.getSynchScope();
3690 SDValue InChain = getRoot();
3692 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3693 EVT VT = TLI.getValueType(I.getType());
3695 if (I.getAlignment() < VT.getSizeInBits() / 8)
3696 report_fatal_error("Cannot generate unaligned atomic load");
3698 MachineMemOperand *MMO =
3699 DAG.getMachineFunction().
3700 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3701 MachineMemOperand::MOVolatile |
3702 MachineMemOperand::MOLoad,
3704 I.getAlignment() ? I.getAlignment() :
3705 DAG.getEVTAlignment(VT));
3707 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3709 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3710 getValue(I.getPointerOperand()), MMO,