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/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/GCMetadata.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/StackMaps.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/Statepoint.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetFrameLowering.h"
59 #include "llvm/Target/TargetInstrInfo.h"
60 #include "llvm/Target/TargetIntrinsicInfo.h"
61 #include "llvm/Target/TargetLowering.h"
62 #include "llvm/Target/TargetOptions.h"
63 #include "llvm/Target/TargetSelectionDAGInfo.h"
64 #include "llvm/Target/TargetSubtargetInfo.h"
68 #define DEBUG_TYPE "isel"
70 /// LimitFloatPrecision - Generate low-precision inline sequences for
71 /// some float libcalls (6, 8 or 12 bits).
72 static unsigned LimitFloatPrecision;
74 static cl::opt<unsigned, true>
75 LimitFPPrecision("limit-float-precision",
76 cl::desc("Generate low-precision inline sequences "
77 "for some float libcalls"),
78 cl::location(LimitFloatPrecision),
81 // Limit the width of DAG chains. This is important in general to prevent
82 // prevent DAG-based analysis from blowing up. For example, alias analysis and
83 // load clustering may not complete in reasonable time. It is difficult to
84 // recognize and avoid this situation within each individual analysis, and
85 // future analyses are likely to have the same behavior. Limiting DAG width is
86 // the safe approach, and will be especially important with global DAGs.
88 // MaxParallelChains default is arbitrarily high to avoid affecting
89 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
90 // sequence over this should have been converted to llvm.memcpy by the
91 // frontend. It easy to induce this behavior with .ll code such as:
92 // %buffer = alloca [4096 x i8]
93 // %data = load [4096 x i8]* %argPtr
94 // store [4096 x i8] %data, [4096 x i8]* %buffer
95 static const unsigned MaxParallelChains = 64;
97 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
98 const SDValue *Parts, unsigned NumParts,
99 MVT PartVT, EVT ValueVT, const Value *V);
101 /// getCopyFromParts - Create a value that contains the specified legal parts
102 /// combined into the value they represent. If the parts combine to a type
103 /// larger then ValueVT then AssertOp can be used to specify whether the extra
104 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
105 /// (ISD::AssertSext).
106 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
107 const SDValue *Parts,
108 unsigned NumParts, MVT PartVT, EVT ValueVT,
110 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
111 if (ValueVT.isVector())
112 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
115 assert(NumParts > 0 && "No parts to assemble!");
116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
117 SDValue Val = Parts[0];
120 // Assemble the value from multiple parts.
121 if (ValueVT.isInteger()) {
122 unsigned PartBits = PartVT.getSizeInBits();
123 unsigned ValueBits = ValueVT.getSizeInBits();
125 // Assemble the power of 2 part.
126 unsigned RoundParts = NumParts & (NumParts - 1) ?
127 1 << Log2_32(NumParts) : NumParts;
128 unsigned RoundBits = PartBits * RoundParts;
129 EVT RoundVT = RoundBits == ValueBits ?
130 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
133 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
135 if (RoundParts > 2) {
136 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
138 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
139 RoundParts / 2, PartVT, HalfVT, V);
141 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
142 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
145 if (TLI.isBigEndian())
148 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
150 if (RoundParts < NumParts) {
151 // Assemble the trailing non-power-of-2 part.
152 unsigned OddParts = NumParts - RoundParts;
153 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
154 Hi = getCopyFromParts(DAG, DL,
155 Parts + RoundParts, OddParts, PartVT, OddVT, V);
157 // Combine the round and odd parts.
159 if (TLI.isBigEndian())
161 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
162 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
163 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
164 DAG.getConstant(Lo.getValueType().getSizeInBits(),
165 TLI.getPointerTy()));
166 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
167 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
169 } else if (PartVT.isFloatingPoint()) {
170 // FP split into multiple FP parts (for ppcf128)
171 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
174 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
175 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
176 if (TLI.hasBigEndianPartOrdering(ValueVT))
178 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
180 // FP split into integer parts (soft fp)
181 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
182 !PartVT.isVector() && "Unexpected split");
183 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
184 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
188 // There is now one part, held in Val. Correct it to match ValueVT.
189 EVT PartEVT = Val.getValueType();
191 if (PartEVT == ValueVT)
194 if (PartEVT.isInteger() && ValueVT.isInteger()) {
195 if (ValueVT.bitsLT(PartEVT)) {
196 // For a truncate, see if we have any information to
197 // indicate whether the truncated bits will always be
198 // zero or sign-extension.
199 if (AssertOp != ISD::DELETED_NODE)
200 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
201 DAG.getValueType(ValueVT));
202 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
204 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
207 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
208 // FP_ROUND's are always exact here.
209 if (ValueVT.bitsLT(Val.getValueType()))
210 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
211 DAG.getTargetConstant(1, TLI.getPointerTy()));
213 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
216 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
217 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
219 llvm_unreachable("Unknown mismatch!");
222 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
223 const Twine &ErrMsg) {
224 const Instruction *I = dyn_cast_or_null<Instruction>(V);
226 return Ctx.emitError(ErrMsg);
228 const char *AsmError = ", possible invalid constraint for vector type";
229 if (const CallInst *CI = dyn_cast<CallInst>(I))
230 if (isa<InlineAsm>(CI->getCalledValue()))
231 return Ctx.emitError(I, ErrMsg + AsmError);
233 return Ctx.emitError(I, ErrMsg);
236 /// getCopyFromPartsVector - Create a value that contains the specified legal
237 /// parts combined into the value they represent. If the parts combine to a
238 /// type larger then ValueVT then AssertOp can be used to specify whether the
239 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
240 /// ValueVT (ISD::AssertSext).
241 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
242 const SDValue *Parts, unsigned NumParts,
243 MVT PartVT, EVT ValueVT, const Value *V) {
244 assert(ValueVT.isVector() && "Not a vector value");
245 assert(NumParts > 0 && "No parts to assemble!");
246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
247 SDValue Val = Parts[0];
249 // Handle a multi-element vector.
253 unsigned NumIntermediates;
255 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
256 NumIntermediates, RegisterVT);
257 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
258 NumParts = NumRegs; // Silence a compiler warning.
259 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
260 assert(RegisterVT == Parts[0].getSimpleValueType() &&
261 "Part type doesn't match part!");
263 // Assemble the parts into intermediate operands.
264 SmallVector<SDValue, 8> Ops(NumIntermediates);
265 if (NumIntermediates == NumParts) {
266 // If the register was not expanded, truncate or copy the value,
268 for (unsigned i = 0; i != NumParts; ++i)
269 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
270 PartVT, IntermediateVT, V);
271 } else if (NumParts > 0) {
272 // If the intermediate type was expanded, build the intermediate
273 // operands from the parts.
274 assert(NumParts % NumIntermediates == 0 &&
275 "Must expand into a divisible number of parts!");
276 unsigned Factor = NumParts / NumIntermediates;
277 for (unsigned i = 0; i != NumIntermediates; ++i)
278 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
279 PartVT, IntermediateVT, V);
282 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
283 // intermediate operands.
284 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
289 // There is now one part, held in Val. Correct it to match ValueVT.
290 EVT PartEVT = Val.getValueType();
292 if (PartEVT == ValueVT)
295 if (PartEVT.isVector()) {
296 // If the element type of the source/dest vectors are the same, but the
297 // parts vector has more elements than the value vector, then we have a
298 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
300 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
301 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
302 "Cannot narrow, it would be a lossy transformation");
303 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
304 DAG.getConstant(0, TLI.getVectorIdxTy()));
307 // Vector/Vector bitcast.
308 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
309 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
311 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
312 "Cannot handle this kind of promotion");
313 // Promoted vector extract
314 bool Smaller = ValueVT.bitsLE(PartEVT);
315 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
320 // Trivial bitcast if the types are the same size and the destination
321 // vector type is legal.
322 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
323 TLI.isTypeLegal(ValueVT))
324 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
326 // Handle cases such as i8 -> <1 x i1>
327 if (ValueVT.getVectorNumElements() != 1) {
328 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
329 "non-trivial scalar-to-vector conversion");
330 return DAG.getUNDEF(ValueVT);
333 if (ValueVT.getVectorNumElements() == 1 &&
334 ValueVT.getVectorElementType() != PartEVT) {
335 bool Smaller = ValueVT.bitsLE(PartEVT);
336 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
337 DL, ValueVT.getScalarType(), Val);
340 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
343 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
344 SDValue Val, SDValue *Parts, unsigned NumParts,
345 MVT PartVT, const Value *V);
347 /// getCopyToParts - Create a series of nodes that contain the specified value
348 /// split into legal parts. If the parts contain more bits than Val, then, for
349 /// integers, ExtendKind can be used to specify how to generate the extra bits.
350 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
351 SDValue Val, SDValue *Parts, unsigned NumParts,
352 MVT PartVT, const Value *V,
353 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
354 EVT ValueVT = Val.getValueType();
356 // Handle the vector case separately.
357 if (ValueVT.isVector())
358 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
361 unsigned PartBits = PartVT.getSizeInBits();
362 unsigned OrigNumParts = NumParts;
363 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
368 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
369 EVT PartEVT = PartVT;
370 if (PartEVT == ValueVT) {
371 assert(NumParts == 1 && "No-op copy with multiple parts!");
376 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
377 // If the parts cover more bits than the value has, promote the value.
378 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
379 assert(NumParts == 1 && "Do not know what to promote to!");
380 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
382 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
383 ValueVT.isInteger() &&
384 "Unknown mismatch!");
385 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
386 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
387 if (PartVT == MVT::x86mmx)
388 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
390 } else if (PartBits == ValueVT.getSizeInBits()) {
391 // Different types of the same size.
392 assert(NumParts == 1 && PartEVT != ValueVT);
393 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
394 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
395 // If the parts cover less bits than value has, truncate the value.
396 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
397 ValueVT.isInteger() &&
398 "Unknown mismatch!");
399 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
400 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
401 if (PartVT == MVT::x86mmx)
402 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
405 // The value may have changed - recompute ValueVT.
406 ValueVT = Val.getValueType();
407 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
408 "Failed to tile the value with PartVT!");
411 if (PartEVT != ValueVT)
412 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
413 "scalar-to-vector conversion failed");
419 // Expand the value into multiple parts.
420 if (NumParts & (NumParts - 1)) {
421 // The number of parts is not a power of 2. Split off and copy the tail.
422 assert(PartVT.isInteger() && ValueVT.isInteger() &&
423 "Do not know what to expand to!");
424 unsigned RoundParts = 1 << Log2_32(NumParts);
425 unsigned RoundBits = RoundParts * PartBits;
426 unsigned OddParts = NumParts - RoundParts;
427 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
428 DAG.getIntPtrConstant(RoundBits));
429 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
431 if (TLI.isBigEndian())
432 // The odd parts were reversed by getCopyToParts - unreverse them.
433 std::reverse(Parts + RoundParts, Parts + NumParts);
435 NumParts = RoundParts;
436 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
437 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
440 // The number of parts is a power of 2. Repeatedly bisect the value using
442 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
443 EVT::getIntegerVT(*DAG.getContext(),
444 ValueVT.getSizeInBits()),
447 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
448 for (unsigned i = 0; i < NumParts; i += StepSize) {
449 unsigned ThisBits = StepSize * PartBits / 2;
450 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
451 SDValue &Part0 = Parts[i];
452 SDValue &Part1 = Parts[i+StepSize/2];
454 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(1));
456 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
457 ThisVT, Part0, DAG.getIntPtrConstant(0));
459 if (ThisBits == PartBits && ThisVT != PartVT) {
460 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
461 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
466 if (TLI.isBigEndian())
467 std::reverse(Parts, Parts + OrigNumParts);
471 /// getCopyToPartsVector - Create a series of nodes that contain the specified
472 /// value split into legal parts.
473 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
474 SDValue Val, SDValue *Parts, unsigned NumParts,
475 MVT PartVT, const Value *V) {
476 EVT ValueVT = Val.getValueType();
477 assert(ValueVT.isVector() && "Not a vector");
478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
481 EVT PartEVT = PartVT;
482 if (PartEVT == ValueVT) {
484 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
485 // Bitconvert vector->vector case.
486 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
487 } else if (PartVT.isVector() &&
488 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
489 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
490 EVT ElementVT = PartVT.getVectorElementType();
491 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
493 SmallVector<SDValue, 16> Ops;
494 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
495 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
496 ElementVT, Val, DAG.getConstant(i,
497 TLI.getVectorIdxTy())));
499 for (unsigned i = ValueVT.getVectorNumElements(),
500 e = PartVT.getVectorNumElements(); i != e; ++i)
501 Ops.push_back(DAG.getUNDEF(ElementVT));
503 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
505 // FIXME: Use CONCAT for 2x -> 4x.
507 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
508 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
509 } else if (PartVT.isVector() &&
510 PartEVT.getVectorElementType().bitsGE(
511 ValueVT.getVectorElementType()) &&
512 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
514 // Promoted vector extract
515 bool Smaller = PartEVT.bitsLE(ValueVT);
516 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
519 // Vector -> scalar conversion.
520 assert(ValueVT.getVectorNumElements() == 1 &&
521 "Only trivial vector-to-scalar conversions should get here!");
522 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
523 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
525 bool Smaller = ValueVT.bitsLE(PartVT);
526 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
534 // Handle a multi-element vector.
537 unsigned NumIntermediates;
538 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
540 NumIntermediates, RegisterVT);
541 unsigned NumElements = ValueVT.getVectorNumElements();
543 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
544 NumParts = NumRegs; // Silence a compiler warning.
545 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
547 // Split the vector into intermediate operands.
548 SmallVector<SDValue, 8> Ops(NumIntermediates);
549 for (unsigned i = 0; i != NumIntermediates; ++i) {
550 if (IntermediateVT.isVector())
551 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
553 DAG.getConstant(i * (NumElements / NumIntermediates),
554 TLI.getVectorIdxTy()));
556 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
558 DAG.getConstant(i, TLI.getVectorIdxTy()));
561 // Split the intermediate operands into legal parts.
562 if (NumParts == NumIntermediates) {
563 // If the register was not expanded, promote or copy the value,
565 for (unsigned i = 0; i != NumParts; ++i)
566 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
567 } else if (NumParts > 0) {
568 // If the intermediate type was expanded, split each the value into
570 assert(NumIntermediates != 0 && "division by zero");
571 assert(NumParts % NumIntermediates == 0 &&
572 "Must expand into a divisible number of parts!");
573 unsigned Factor = NumParts / NumIntermediates;
574 for (unsigned i = 0; i != NumIntermediates; ++i)
575 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
580 /// RegsForValue - This struct represents the registers (physical or virtual)
581 /// that a particular set of values is assigned, and the type information
582 /// about the value. The most common situation is to represent one value at a
583 /// time, but struct or array values are handled element-wise as multiple
584 /// values. The splitting of aggregates is performed recursively, so that we
585 /// never have aggregate-typed registers. The values at this point do not
586 /// necessarily have legal types, so each value may require one or more
587 /// registers of some legal type.
589 struct RegsForValue {
590 /// ValueVTs - The value types of the values, which may not be legal, and
591 /// may need be promoted or synthesized from one or more registers.
593 SmallVector<EVT, 4> ValueVTs;
595 /// RegVTs - The value types of the registers. This is the same size as
596 /// ValueVTs and it records, for each value, what the type of the assigned
597 /// register or registers are. (Individual values are never synthesized
598 /// from more than one type of register.)
600 /// With virtual registers, the contents of RegVTs is redundant with TLI's
601 /// getRegisterType member function, however when with physical registers
602 /// it is necessary to have a separate record of the types.
604 SmallVector<MVT, 4> RegVTs;
606 /// Regs - This list holds the registers assigned to the values.
607 /// Each legal or promoted value requires one register, and each
608 /// expanded value requires multiple registers.
610 SmallVector<unsigned, 4> Regs;
614 RegsForValue(const SmallVector<unsigned, 4> ®s,
615 MVT regvt, EVT valuevt)
616 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
618 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
619 unsigned Reg, Type *Ty) {
620 ComputeValueVTs(tli, Ty, ValueVTs);
622 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
623 EVT ValueVT = ValueVTs[Value];
624 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
625 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
626 for (unsigned i = 0; i != NumRegs; ++i)
627 Regs.push_back(Reg + i);
628 RegVTs.push_back(RegisterVT);
633 /// append - Add the specified values to this one.
634 void append(const RegsForValue &RHS) {
635 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
636 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
637 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
640 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
641 /// this value and returns the result as a ValueVTs value. This uses
642 /// Chain/Flag as the input and updates them for the output Chain/Flag.
643 /// If the Flag pointer is NULL, no flag is used.
644 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
646 SDValue &Chain, SDValue *Flag,
647 const Value *V = nullptr) const;
649 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
650 /// specified value into the registers specified by this object. This uses
651 /// Chain/Flag as the input and updates them for the output Chain/Flag.
652 /// If the Flag pointer is NULL, no flag is used.
654 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
655 SDValue *Flag, const Value *V,
656 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
658 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
659 /// operand list. This adds the code marker, matching input operand index
660 /// (if applicable), and includes the number of values added into it.
661 void AddInlineAsmOperands(unsigned Kind,
662 bool HasMatching, unsigned MatchingIdx,
664 std::vector<SDValue> &Ops) const;
668 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
669 /// this value and returns the result as a ValueVT value. This uses
670 /// Chain/Flag as the input and updates them for the output Chain/Flag.
671 /// If the Flag pointer is NULL, no flag is used.
672 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
673 FunctionLoweringInfo &FuncInfo,
675 SDValue &Chain, SDValue *Flag,
676 const Value *V) const {
677 // A Value with type {} or [0 x %t] needs no registers.
678 if (ValueVTs.empty())
681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
683 // Assemble the legal parts into the final values.
684 SmallVector<SDValue, 4> Values(ValueVTs.size());
685 SmallVector<SDValue, 8> Parts;
686 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
687 // Copy the legal parts from the registers.
688 EVT ValueVT = ValueVTs[Value];
689 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
690 MVT RegisterVT = RegVTs[Value];
692 Parts.resize(NumRegs);
693 for (unsigned i = 0; i != NumRegs; ++i) {
696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
698 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
699 *Flag = P.getValue(2);
702 Chain = P.getValue(1);
705 // If the source register was virtual and if we know something about it,
706 // add an assert node.
707 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
708 !RegisterVT.isInteger() || RegisterVT.isVector())
711 const FunctionLoweringInfo::LiveOutInfo *LOI =
712 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
716 unsigned RegSize = RegisterVT.getSizeInBits();
717 unsigned NumSignBits = LOI->NumSignBits;
718 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
720 if (NumZeroBits == RegSize) {
721 // The current value is a zero.
722 // Explicitly express that as it would be easier for
723 // optimizations to kick in.
724 Parts[i] = DAG.getConstant(0, RegisterVT);
728 // FIXME: We capture more information than the dag can represent. For
729 // now, just use the tightest assertzext/assertsext possible.
731 EVT FromVT(MVT::Other);
732 if (NumSignBits == RegSize)
733 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
734 else if (NumZeroBits >= RegSize-1)
735 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
736 else if (NumSignBits > RegSize-8)
737 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
738 else if (NumZeroBits >= RegSize-8)
739 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
740 else if (NumSignBits > RegSize-16)
741 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
742 else if (NumZeroBits >= RegSize-16)
743 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
744 else if (NumSignBits > RegSize-32)
745 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
746 else if (NumZeroBits >= RegSize-32)
747 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
751 // Add an assertion node.
752 assert(FromVT != MVT::Other);
753 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
754 RegisterVT, P, DAG.getValueType(FromVT));
757 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
758 NumRegs, RegisterVT, ValueVT, V);
763 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
766 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
767 /// specified value into the registers specified by this object. This uses
768 /// Chain/Flag as the input and updates them for the output Chain/Flag.
769 /// If the Flag pointer is NULL, no flag is used.
770 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
771 SDValue &Chain, SDValue *Flag, const Value *V,
772 ISD::NodeType PreferredExtendType) const {
773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
774 ISD::NodeType ExtendKind = PreferredExtendType;
776 // Get the list of the values's legal parts.
777 unsigned NumRegs = Regs.size();
778 SmallVector<SDValue, 8> Parts(NumRegs);
779 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
780 EVT ValueVT = ValueVTs[Value];
781 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
782 MVT RegisterVT = RegVTs[Value];
784 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
785 ExtendKind = ISD::ZERO_EXTEND;
787 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
788 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
792 // Copy the parts into the registers.
793 SmallVector<SDValue, 8> Chains(NumRegs);
794 for (unsigned i = 0; i != NumRegs; ++i) {
797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
799 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
800 *Flag = Part.getValue(1);
803 Chains[i] = Part.getValue(0);
806 if (NumRegs == 1 || Flag)
807 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
808 // flagged to it. That is the CopyToReg nodes and the user are considered
809 // a single scheduling unit. If we create a TokenFactor and return it as
810 // chain, then the TokenFactor is both a predecessor (operand) of the
811 // user as well as a successor (the TF operands are flagged to the user).
812 // c1, f1 = CopyToReg
813 // c2, f2 = CopyToReg
814 // c3 = TokenFactor c1, c2
817 Chain = Chains[NumRegs-1];
819 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
822 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
823 /// operand list. This adds the code marker and includes the number of
824 /// values added into it.
825 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
826 unsigned MatchingIdx,
828 std::vector<SDValue> &Ops) const {
829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
831 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
833 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
834 else if (!Regs.empty() &&
835 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
836 // Put the register class of the virtual registers in the flag word. That
837 // way, later passes can recompute register class constraints for inline
838 // assembly as well as normal instructions.
839 // Don't do this for tied operands that can use the regclass information
841 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
842 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
843 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
846 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
849 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
850 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
851 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
852 MVT RegisterVT = RegVTs[Value];
853 for (unsigned i = 0; i != NumRegs; ++i) {
854 assert(Reg < Regs.size() && "Mismatch in # registers expected");
855 unsigned TheReg = Regs[Reg++];
856 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
858 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
859 // If we clobbered the stack pointer, MFI should know about it.
860 assert(DAG.getMachineFunction().getFrameInfo()->
861 hasInlineAsmWithSPAdjust());
867 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
868 const TargetLibraryInfo *li) {
872 DL = DAG.getTarget().getDataLayout();
873 Context = DAG.getContext();
874 LPadToCallSiteMap.clear();
877 /// clear - Clear out the current SelectionDAG and the associated
878 /// state and prepare this SelectionDAGBuilder object to be used
879 /// for a new block. This doesn't clear out information about
880 /// additional blocks that are needed to complete switch lowering
881 /// or PHI node updating; that information is cleared out as it is
883 void SelectionDAGBuilder::clear() {
885 UnusedArgNodeMap.clear();
886 PendingLoads.clear();
887 PendingExports.clear();
890 SDNodeOrder = LowestSDNodeOrder;
891 StatepointLowering.clear();
894 /// clearDanglingDebugInfo - Clear the dangling debug information
895 /// map. This function is separated from the clear so that debug
896 /// information that is dangling in a basic block can be properly
897 /// resolved in a different basic block. This allows the
898 /// SelectionDAG to resolve dangling debug information attached
900 void SelectionDAGBuilder::clearDanglingDebugInfo() {
901 DanglingDebugInfoMap.clear();
904 /// getRoot - Return the current virtual root of the Selection DAG,
905 /// flushing any PendingLoad items. This must be done before emitting
906 /// a store or any other node that may need to be ordered after any
907 /// prior load instructions.
909 SDValue SelectionDAGBuilder::getRoot() {
910 if (PendingLoads.empty())
911 return DAG.getRoot();
913 if (PendingLoads.size() == 1) {
914 SDValue Root = PendingLoads[0];
916 PendingLoads.clear();
920 // Otherwise, we have to make a token factor node.
921 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
923 PendingLoads.clear();
928 /// getControlRoot - Similar to getRoot, but instead of flushing all the
929 /// PendingLoad items, flush all the PendingExports items. It is necessary
930 /// to do this before emitting a terminator instruction.
932 SDValue SelectionDAGBuilder::getControlRoot() {
933 SDValue Root = DAG.getRoot();
935 if (PendingExports.empty())
938 // Turn all of the CopyToReg chains into one factored node.
939 if (Root.getOpcode() != ISD::EntryToken) {
940 unsigned i = 0, e = PendingExports.size();
941 for (; i != e; ++i) {
942 assert(PendingExports[i].getNode()->getNumOperands() > 1);
943 if (PendingExports[i].getNode()->getOperand(0) == Root)
944 break; // Don't add the root if we already indirectly depend on it.
948 PendingExports.push_back(Root);
951 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
953 PendingExports.clear();
958 void SelectionDAGBuilder::visit(const Instruction &I) {
959 // Set up outgoing PHI node register values before emitting the terminator.
960 if (isa<TerminatorInst>(&I))
961 HandlePHINodesInSuccessorBlocks(I.getParent());
967 visit(I.getOpcode(), I);
969 if (!isa<TerminatorInst>(&I) && !HasTailCall)
970 CopyToExportRegsIfNeeded(&I);
975 void SelectionDAGBuilder::visitPHI(const PHINode &) {
976 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
979 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
980 // Note: this doesn't use InstVisitor, because it has to work with
981 // ConstantExpr's in addition to instructions.
983 default: llvm_unreachable("Unknown instruction type encountered!");
984 // Build the switch statement using the Instruction.def file.
985 #define HANDLE_INST(NUM, OPCODE, CLASS) \
986 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
987 #include "llvm/IR/Instruction.def"
991 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
992 // generate the debug data structures now that we've seen its definition.
993 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
995 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
997 const DbgValueInst *DI = DDI.getDI();
998 DebugLoc dl = DDI.getdl();
999 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1000 MDNode *Variable = DI->getVariable();
1001 MDNode *Expr = DI->getExpression();
1002 uint64_t Offset = DI->getOffset();
1003 // A dbg.value for an alloca is always indirect.
1004 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1006 if (Val.getNode()) {
1007 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1009 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1010 IsIndirect, Offset, dl, DbgSDNodeOrder);
1011 DAG.AddDbgValue(SDV, Val.getNode(), false);
1014 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1015 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1019 /// getCopyFromRegs - If there was virtual register allocated for the value V
1020 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1021 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1022 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 res = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1031 resolveDanglingDebugInfo(V, res);
1037 /// getValue - Return an SDValue for the given Value.
1038 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1039 // If we already have an SDValue for this value, use it. It's important
1040 // to do this first, so that we don't create a CopyFromReg if we already
1041 // have a regular SDValue.
1042 SDValue &N = NodeMap[V];
1043 if (N.getNode()) return N;
1045 // If there's a virtual register allocated and initialized for this
1047 SDValue copyFromReg = getCopyFromRegs(V, V->getType());
1048 if (copyFromReg.getNode()) {
1052 // Otherwise create a new SDValue and remember it.
1053 SDValue Val = getValueImpl(V);
1055 resolveDanglingDebugInfo(V, Val);
1059 /// getNonRegisterValue - Return an SDValue for the given Value, but
1060 /// don't look in FuncInfo.ValueMap for a virtual register.
1061 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1062 // If we already have an SDValue for this value, use it.
1063 SDValue &N = NodeMap[V];
1064 if (N.getNode()) return N;
1066 // Otherwise create a new SDValue and remember it.
1067 SDValue Val = getValueImpl(V);
1069 resolveDanglingDebugInfo(V, Val);
1073 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1074 /// Create an SDValue for the given value.
1075 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1076 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1078 if (const Constant *C = dyn_cast<Constant>(V)) {
1079 EVT VT = TLI.getValueType(V->getType(), true);
1081 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1082 return DAG.getConstant(*CI, VT);
1084 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1085 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1087 if (isa<ConstantPointerNull>(C)) {
1088 unsigned AS = V->getType()->getPointerAddressSpace();
1089 return DAG.getConstant(0, TLI.getPointerTy(AS));
1092 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1093 return DAG.getConstantFP(*CFP, VT);
1095 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1096 return DAG.getUNDEF(VT);
1098 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1099 visit(CE->getOpcode(), *CE);
1100 SDValue N1 = NodeMap[V];
1101 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1105 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1106 SmallVector<SDValue, 4> Constants;
1107 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1109 SDNode *Val = getValue(*OI).getNode();
1110 // If the operand is an empty aggregate, there are no values.
1112 // Add each leaf value from the operand to the Constants list
1113 // to form a flattened list of all the values.
1114 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1115 Constants.push_back(SDValue(Val, i));
1118 return DAG.getMergeValues(Constants, getCurSDLoc());
1121 if (const ConstantDataSequential *CDS =
1122 dyn_cast<ConstantDataSequential>(C)) {
1123 SmallVector<SDValue, 4> Ops;
1124 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1125 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1126 // Add each leaf value from the operand to the Constants list
1127 // to form a flattened list of all the values.
1128 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1129 Ops.push_back(SDValue(Val, i));
1132 if (isa<ArrayType>(CDS->getType()))
1133 return DAG.getMergeValues(Ops, getCurSDLoc());
1134 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1138 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1139 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1140 "Unknown struct or array constant!");
1142 SmallVector<EVT, 4> ValueVTs;
1143 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1144 unsigned NumElts = ValueVTs.size();
1146 return SDValue(); // empty struct
1147 SmallVector<SDValue, 4> Constants(NumElts);
1148 for (unsigned i = 0; i != NumElts; ++i) {
1149 EVT EltVT = ValueVTs[i];
1150 if (isa<UndefValue>(C))
1151 Constants[i] = DAG.getUNDEF(EltVT);
1152 else if (EltVT.isFloatingPoint())
1153 Constants[i] = DAG.getConstantFP(0, EltVT);
1155 Constants[i] = DAG.getConstant(0, EltVT);
1158 return DAG.getMergeValues(Constants, getCurSDLoc());
1161 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1162 return DAG.getBlockAddress(BA, VT);
1164 VectorType *VecTy = cast<VectorType>(V->getType());
1165 unsigned NumElements = VecTy->getNumElements();
1167 // Now that we know the number and type of the elements, get that number of
1168 // elements into the Ops array based on what kind of constant it is.
1169 SmallVector<SDValue, 16> Ops;
1170 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1171 for (unsigned i = 0; i != NumElements; ++i)
1172 Ops.push_back(getValue(CV->getOperand(i)));
1174 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1175 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1178 if (EltVT.isFloatingPoint())
1179 Op = DAG.getConstantFP(0, EltVT);
1181 Op = DAG.getConstant(0, EltVT);
1182 Ops.assign(NumElements, Op);
1185 // Create a BUILD_VECTOR node.
1186 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1189 // If this is a static alloca, generate it as the frameindex instead of
1191 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1192 DenseMap<const AllocaInst*, int>::iterator SI =
1193 FuncInfo.StaticAllocaMap.find(AI);
1194 if (SI != FuncInfo.StaticAllocaMap.end())
1195 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1198 // If this is an instruction which fast-isel has deferred, select it now.
1199 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1200 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1201 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1202 SDValue Chain = DAG.getEntryNode();
1203 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1206 llvm_unreachable("Can't get register for value!");
1209 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1211 SDValue Chain = getControlRoot();
1212 SmallVector<ISD::OutputArg, 8> Outs;
1213 SmallVector<SDValue, 8> OutVals;
1215 if (!FuncInfo.CanLowerReturn) {
1216 unsigned DemoteReg = FuncInfo.DemoteRegister;
1217 const Function *F = I.getParent()->getParent();
1219 // Emit a store of the return value through the virtual register.
1220 // Leave Outs empty so that LowerReturn won't try to load return
1221 // registers the usual way.
1222 SmallVector<EVT, 1> PtrValueVTs;
1223 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1226 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1227 SDValue RetOp = getValue(I.getOperand(0));
1229 SmallVector<EVT, 4> ValueVTs;
1230 SmallVector<uint64_t, 4> Offsets;
1231 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1232 unsigned NumValues = ValueVTs.size();
1234 SmallVector<SDValue, 4> Chains(NumValues);
1235 for (unsigned i = 0; i != NumValues; ++i) {
1236 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1237 RetPtr.getValueType(), RetPtr,
1238 DAG.getIntPtrConstant(Offsets[i]));
1240 DAG.getStore(Chain, getCurSDLoc(),
1241 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1242 // FIXME: better loc info would be nice.
1243 Add, MachinePointerInfo(), false, false, 0);
1246 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1247 MVT::Other, Chains);
1248 } else if (I.getNumOperands() != 0) {
1249 SmallVector<EVT, 4> ValueVTs;
1250 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1251 unsigned NumValues = ValueVTs.size();
1253 SDValue RetOp = getValue(I.getOperand(0));
1255 const Function *F = I.getParent()->getParent();
1257 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1258 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1260 ExtendKind = ISD::SIGN_EXTEND;
1261 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1263 ExtendKind = ISD::ZERO_EXTEND;
1265 LLVMContext &Context = F->getContext();
1266 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1269 for (unsigned j = 0; j != NumValues; ++j) {
1270 EVT VT = ValueVTs[j];
1272 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1273 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
1275 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1276 MVT PartVT = TLI.getRegisterType(Context, VT);
1277 SmallVector<SDValue, 4> Parts(NumParts);
1278 getCopyToParts(DAG, getCurSDLoc(),
1279 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1280 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1282 // 'inreg' on function refers to return value
1283 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1287 // Propagate extension type if any
1288 if (ExtendKind == ISD::SIGN_EXTEND)
1290 else if (ExtendKind == ISD::ZERO_EXTEND)
1293 for (unsigned i = 0; i < NumParts; ++i) {
1294 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1295 VT, /*isfixed=*/true, 0, 0));
1296 OutVals.push_back(Parts[i]);
1302 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1303 CallingConv::ID CallConv =
1304 DAG.getMachineFunction().getFunction()->getCallingConv();
1305 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1306 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1308 // Verify that the target's LowerReturn behaved as expected.
1309 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1310 "LowerReturn didn't return a valid chain!");
1312 // Update the DAG with the new chain value resulting from return lowering.
1316 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1317 /// created for it, emit nodes to copy the value into the virtual
1319 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1321 if (V->getType()->isEmptyTy())
1324 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1325 if (VMI != FuncInfo.ValueMap.end()) {
1326 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1327 CopyValueToVirtualRegister(V, VMI->second);
1331 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1332 /// the current basic block, add it to ValueMap now so that we'll get a
1334 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1335 // No need to export constants.
1336 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1338 // Already exported?
1339 if (FuncInfo.isExportedInst(V)) return;
1341 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1342 CopyValueToVirtualRegister(V, Reg);
1345 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1346 const BasicBlock *FromBB) {
1347 // The operands of the setcc have to be in this block. We don't know
1348 // how to export them from some other block.
1349 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1350 // Can export from current BB.
1351 if (VI->getParent() == FromBB)
1354 // Is already exported, noop.
1355 return FuncInfo.isExportedInst(V);
1358 // If this is an argument, we can export it if the BB is the entry block or
1359 // if it is already exported.
1360 if (isa<Argument>(V)) {
1361 if (FromBB == &FromBB->getParent()->getEntryBlock())
1364 // Otherwise, can only export this if it is already exported.
1365 return FuncInfo.isExportedInst(V);
1368 // Otherwise, constants can always be exported.
1372 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1373 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1374 const MachineBasicBlock *Dst) const {
1375 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1378 const BasicBlock *SrcBB = Src->getBasicBlock();
1379 const BasicBlock *DstBB = Dst->getBasicBlock();
1380 return BPI->getEdgeWeight(SrcBB, DstBB);
1383 void SelectionDAGBuilder::
1384 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1385 uint32_t Weight /* = 0 */) {
1387 Weight = getEdgeWeight(Src, Dst);
1388 Src->addSuccessor(Dst, Weight);
1392 static bool InBlock(const Value *V, const BasicBlock *BB) {
1393 if (const Instruction *I = dyn_cast<Instruction>(V))
1394 return I->getParent() == BB;
1398 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1399 /// This function emits a branch and is used at the leaves of an OR or an
1400 /// AND operator tree.
1403 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1404 MachineBasicBlock *TBB,
1405 MachineBasicBlock *FBB,
1406 MachineBasicBlock *CurBB,
1407 MachineBasicBlock *SwitchBB,
1410 const BasicBlock *BB = CurBB->getBasicBlock();
1412 // If the leaf of the tree is a comparison, merge the condition into
1414 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1415 // The operands of the cmp have to be in this block. We don't know
1416 // how to export them from some other block. If this is the first block
1417 // of the sequence, no exporting is needed.
1418 if (CurBB == SwitchBB ||
1419 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1420 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1421 ISD::CondCode Condition;
1422 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1423 Condition = getICmpCondCode(IC->getPredicate());
1424 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1425 Condition = getFCmpCondCode(FC->getPredicate());
1426 if (TM.Options.NoNaNsFPMath)
1427 Condition = getFCmpCodeWithoutNaN(Condition);
1429 (void)Condition; // silence warning.
1430 llvm_unreachable("Unknown compare instruction");
1433 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1434 TBB, FBB, CurBB, TWeight, FWeight);
1435 SwitchCases.push_back(CB);
1440 // Create a CaseBlock record representing this branch.
1441 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1442 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1443 SwitchCases.push_back(CB);
1446 /// Scale down both weights to fit into uint32_t.
1447 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1448 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1449 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1450 NewTrue = NewTrue / Scale;
1451 NewFalse = NewFalse / Scale;
1454 /// FindMergedConditions - If Cond is an expression like
1455 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1456 MachineBasicBlock *TBB,
1457 MachineBasicBlock *FBB,
1458 MachineBasicBlock *CurBB,
1459 MachineBasicBlock *SwitchBB,
1460 unsigned Opc, uint32_t TWeight,
1462 // If this node is not part of the or/and tree, emit it as a branch.
1463 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1464 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1465 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1466 BOp->getParent() != CurBB->getBasicBlock() ||
1467 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1468 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1469 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1474 // Create TmpBB after CurBB.
1475 MachineFunction::iterator BBI = CurBB;
1476 MachineFunction &MF = DAG.getMachineFunction();
1477 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1478 CurBB->getParent()->insert(++BBI, TmpBB);
1480 if (Opc == Instruction::Or) {
1481 // Codegen X | Y as:
1490 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1491 // The requirement is that
1492 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1493 // = TrueProb for orignal BB.
1494 // Assuming the orignal weights are A and B, one choice is to set BB1's
1495 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1497 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1498 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1499 // TmpBB, but the math is more complicated.
1501 uint64_t NewTrueWeight = TWeight;
1502 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1503 ScaleWeights(NewTrueWeight, NewFalseWeight);
1504 // Emit the LHS condition.
1505 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1506 NewTrueWeight, NewFalseWeight);
1508 NewTrueWeight = TWeight;
1509 NewFalseWeight = 2 * (uint64_t)FWeight;
1510 ScaleWeights(NewTrueWeight, NewFalseWeight);
1511 // Emit the RHS condition into TmpBB.
1512 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1513 NewTrueWeight, NewFalseWeight);
1515 assert(Opc == Instruction::And && "Unknown merge op!");
1516 // Codegen X & Y as:
1524 // This requires creation of TmpBB after CurBB.
1526 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1527 // The requirement is that
1528 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1529 // = FalseProb for orignal BB.
1530 // Assuming the orignal weights are A and B, one choice is to set BB1's
1531 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1533 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1535 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1536 uint64_t NewFalseWeight = FWeight;
1537 ScaleWeights(NewTrueWeight, NewFalseWeight);
1538 // Emit the LHS condition.
1539 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1540 NewTrueWeight, NewFalseWeight);
1542 NewTrueWeight = 2 * (uint64_t)TWeight;
1543 NewFalseWeight = FWeight;
1544 ScaleWeights(NewTrueWeight, NewFalseWeight);
1545 // Emit the RHS condition into TmpBB.
1546 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1547 NewTrueWeight, NewFalseWeight);
1551 /// If the set of cases should be emitted as a series of branches, return true.
1552 /// If we should emit this as a bunch of and/or'd together conditions, return
1555 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1556 if (Cases.size() != 2) return true;
1558 // If this is two comparisons of the same values or'd or and'd together, they
1559 // will get folded into a single comparison, so don't emit two blocks.
1560 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1561 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1562 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1563 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1567 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1568 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1569 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1570 Cases[0].CC == Cases[1].CC &&
1571 isa<Constant>(Cases[0].CmpRHS) &&
1572 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1573 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1575 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1582 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1583 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1585 // Update machine-CFG edges.
1586 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1588 if (I.isUnconditional()) {
1589 // Update machine-CFG edges.
1590 BrMBB->addSuccessor(Succ0MBB);
1592 // If this is not a fall-through branch or optimizations are switched off,
1594 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1595 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1596 MVT::Other, getControlRoot(),
1597 DAG.getBasicBlock(Succ0MBB)));
1602 // If this condition is one of the special cases we handle, do special stuff
1604 const Value *CondVal = I.getCondition();
1605 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1607 // If this is a series of conditions that are or'd or and'd together, emit
1608 // this as a sequence of branches instead of setcc's with and/or operations.
1609 // As long as jumps are not expensive, this should improve performance.
1610 // For example, instead of something like:
1623 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1624 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1625 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1626 BOp->getOpcode() == Instruction::Or)) {
1627 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1628 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1629 getEdgeWeight(BrMBB, Succ1MBB));
1630 // If the compares in later blocks need to use values not currently
1631 // exported from this block, export them now. This block should always
1632 // be the first entry.
1633 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1635 // Allow some cases to be rejected.
1636 if (ShouldEmitAsBranches(SwitchCases)) {
1637 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1638 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1639 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1642 // Emit the branch for this block.
1643 visitSwitchCase(SwitchCases[0], BrMBB);
1644 SwitchCases.erase(SwitchCases.begin());
1648 // Okay, we decided not to do this, remove any inserted MBB's and clear
1650 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1651 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1653 SwitchCases.clear();
1657 // Create a CaseBlock record representing this branch.
1658 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1659 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1661 // Use visitSwitchCase to actually insert the fast branch sequence for this
1663 visitSwitchCase(CB, BrMBB);
1666 /// visitSwitchCase - Emits the necessary code to represent a single node in
1667 /// the binary search tree resulting from lowering a switch instruction.
1668 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1669 MachineBasicBlock *SwitchBB) {
1671 SDValue CondLHS = getValue(CB.CmpLHS);
1672 SDLoc dl = getCurSDLoc();
1674 // Build the setcc now.
1676 // Fold "(X == true)" to X and "(X == false)" to !X to
1677 // handle common cases produced by branch lowering.
1678 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1679 CB.CC == ISD::SETEQ)
1681 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1682 CB.CC == ISD::SETEQ) {
1683 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1684 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1686 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1688 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1690 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1691 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1693 SDValue CmpOp = getValue(CB.CmpMHS);
1694 EVT VT = CmpOp.getValueType();
1696 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1697 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1700 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1701 VT, CmpOp, DAG.getConstant(Low, VT));
1702 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1703 DAG.getConstant(High-Low, VT), ISD::SETULE);
1707 // Update successor info
1708 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1709 // TrueBB and FalseBB are always different unless the incoming IR is
1710 // degenerate. This only happens when running llc on weird IR.
1711 if (CB.TrueBB != CB.FalseBB)
1712 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1714 // If the lhs block is the next block, invert the condition so that we can
1715 // fall through to the lhs instead of the rhs block.
1716 if (CB.TrueBB == NextBlock(SwitchBB)) {
1717 std::swap(CB.TrueBB, CB.FalseBB);
1718 SDValue True = DAG.getConstant(1, Cond.getValueType());
1719 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1722 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1723 MVT::Other, getControlRoot(), Cond,
1724 DAG.getBasicBlock(CB.TrueBB));
1726 // Insert the false branch. Do this even if it's a fall through branch,
1727 // this makes it easier to do DAG optimizations which require inverting
1728 // the branch condition.
1729 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1730 DAG.getBasicBlock(CB.FalseBB));
1732 DAG.setRoot(BrCond);
1735 /// visitJumpTable - Emit JumpTable node in the current MBB
1736 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1737 // Emit the code for the jump table
1738 assert(JT.Reg != -1U && "Should lower JT Header first!");
1739 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1740 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1742 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1743 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1744 MVT::Other, Index.getValue(1),
1746 DAG.setRoot(BrJumpTable);
1749 /// visitJumpTableHeader - This function emits necessary code to produce index
1750 /// in the JumpTable from switch case.
1751 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1752 JumpTableHeader &JTH,
1753 MachineBasicBlock *SwitchBB) {
1754 // Subtract the lowest switch case value from the value being switched on and
1755 // conditional branch to default mbb if the result is greater than the
1756 // difference between smallest and largest cases.
1757 SDValue SwitchOp = getValue(JTH.SValue);
1758 EVT VT = SwitchOp.getValueType();
1759 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1760 DAG.getConstant(JTH.First, VT));
1762 // The SDNode we just created, which holds the value being switched on minus
1763 // the smallest case value, needs to be copied to a virtual register so it
1764 // can be used as an index into the jump table in a subsequent basic block.
1765 // This value may be smaller or larger than the target's pointer type, and
1766 // therefore require extension or truncating.
1767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1768 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1770 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1771 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1772 JumpTableReg, SwitchOp);
1773 JT.Reg = JumpTableReg;
1775 // Emit the range check for the jump table, and branch to the default block
1776 // for the switch statement if the value being switched on exceeds the largest
1777 // case in the switch.
1779 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1780 Sub.getValueType()),
1781 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1783 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1784 MVT::Other, CopyTo, CMP,
1785 DAG.getBasicBlock(JT.Default));
1787 // Avoid emitting unnecessary branches to the next block.
1788 if (JT.MBB != NextBlock(SwitchBB))
1789 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1790 DAG.getBasicBlock(JT.MBB));
1792 DAG.setRoot(BrCond);
1795 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1796 /// tail spliced into a stack protector check success bb.
1798 /// For a high level explanation of how this fits into the stack protector
1799 /// generation see the comment on the declaration of class
1800 /// StackProtectorDescriptor.
1801 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1802 MachineBasicBlock *ParentBB) {
1804 // First create the loads to the guard/stack slot for the comparison.
1805 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1806 EVT PtrTy = TLI.getPointerTy();
1808 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1809 int FI = MFI->getStackProtectorIndex();
1811 const Value *IRGuard = SPD.getGuard();
1812 SDValue GuardPtr = getValue(IRGuard);
1813 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1816 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1820 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1821 // guard value from the virtual register holding the value. Otherwise, emit a
1822 // volatile load to retrieve the stack guard value.
1823 unsigned GuardReg = SPD.getGuardReg();
1825 if (GuardReg && TLI.useLoadStackGuardNode())
1826 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1829 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1830 GuardPtr, MachinePointerInfo(IRGuard, 0),
1831 true, false, false, Align);
1833 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1835 MachinePointerInfo::getFixedStack(FI),
1836 true, false, false, Align);
1838 // Perform the comparison via a subtract/getsetcc.
1839 EVT VT = Guard.getValueType();
1840 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1843 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1844 Sub.getValueType()),
1845 Sub, DAG.getConstant(0, VT), ISD::SETNE);
1847 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1848 // branch to failure MBB.
1849 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1850 MVT::Other, StackSlot.getOperand(0),
1851 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1852 // Otherwise branch to success MBB.
1853 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1855 DAG.getBasicBlock(SPD.getSuccessMBB()));
1860 /// Codegen the failure basic block for a stack protector check.
1862 /// A failure stack protector machine basic block consists simply of a call to
1863 /// __stack_chk_fail().
1865 /// For a high level explanation of how this fits into the stack protector
1866 /// generation see the comment on the declaration of class
1867 /// StackProtectorDescriptor.
1869 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1870 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1872 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1873 nullptr, 0, false, getCurSDLoc(), false, false).second;
1877 /// visitBitTestHeader - This function emits necessary code to produce value
1878 /// suitable for "bit tests"
1879 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1880 MachineBasicBlock *SwitchBB) {
1881 // Subtract the minimum value
1882 SDValue SwitchOp = getValue(B.SValue);
1883 EVT VT = SwitchOp.getValueType();
1884 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1885 DAG.getConstant(B.First, VT));
1888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1890 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1891 Sub.getValueType()),
1892 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1894 // Determine the type of the test operands.
1895 bool UsePtrType = false;
1896 if (!TLI.isTypeLegal(VT))
1899 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1900 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1901 // Switch table case range are encoded into series of masks.
1902 // Just use pointer type, it's guaranteed to fit.
1908 VT = TLI.getPointerTy();
1909 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1912 B.RegVT = VT.getSimpleVT();
1913 B.Reg = FuncInfo.CreateReg(B.RegVT);
1914 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1917 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1919 addSuccessorWithWeight(SwitchBB, B.Default);
1920 addSuccessorWithWeight(SwitchBB, MBB);
1922 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1923 MVT::Other, CopyTo, RangeCmp,
1924 DAG.getBasicBlock(B.Default));
1926 // Avoid emitting unnecessary branches to the next block.
1927 if (MBB != NextBlock(SwitchBB))
1928 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1929 DAG.getBasicBlock(MBB));
1931 DAG.setRoot(BrRange);
1934 /// visitBitTestCase - this function produces one "bit test"
1935 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1936 MachineBasicBlock* NextMBB,
1937 uint32_t BranchWeightToNext,
1940 MachineBasicBlock *SwitchBB) {
1942 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1945 unsigned PopCount = countPopulation(B.Mask);
1946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1947 if (PopCount == 1) {
1948 // Testing for a single bit; just compare the shift count with what it
1949 // would need to be to shift a 1 bit in that position.
1951 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1952 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1953 } else if (PopCount == BB.Range) {
1954 // There is only one zero bit in the range, test for it directly.
1956 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1957 DAG.getConstant(countTrailingOnes(B.Mask), VT), ISD::SETNE);
1959 // Make desired shift
1960 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1961 DAG.getConstant(1, VT), ShiftOp);
1963 // Emit bit tests and jumps
1964 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1965 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1966 Cmp = DAG.getSetCC(getCurSDLoc(),
1967 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1968 DAG.getConstant(0, VT), ISD::SETNE);
1971 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1972 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1973 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1974 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1976 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1977 MVT::Other, getControlRoot(),
1978 Cmp, DAG.getBasicBlock(B.TargetBB));
1980 // Avoid emitting unnecessary branches to the next block.
1981 if (NextMBB != NextBlock(SwitchBB))
1982 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1983 DAG.getBasicBlock(NextMBB));
1988 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1989 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1991 // Retrieve successors.
1992 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1993 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1995 const Value *Callee(I.getCalledValue());
1996 const Function *Fn = dyn_cast<Function>(Callee);
1997 if (isa<InlineAsm>(Callee))
1999 else if (Fn && Fn->isIntrinsic()) {
2000 switch (Fn->getIntrinsicID()) {
2002 llvm_unreachable("Cannot invoke this intrinsic");
2003 case Intrinsic::donothing:
2004 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2006 case Intrinsic::experimental_patchpoint_void:
2007 case Intrinsic::experimental_patchpoint_i64:
2008 visitPatchpoint(&I, LandingPad);
2010 case Intrinsic::experimental_gc_statepoint:
2011 LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
2015 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2017 // If the value of the invoke is used outside of its defining block, make it
2018 // available as a virtual register.
2019 // We already took care of the exported value for the statepoint instruction
2020 // during call to the LowerStatepoint.
2021 if (!isStatepoint(I)) {
2022 CopyToExportRegsIfNeeded(&I);
2025 // Update successor info
2026 addSuccessorWithWeight(InvokeMBB, Return);
2027 addSuccessorWithWeight(InvokeMBB, LandingPad);
2029 // Drop into normal successor.
2030 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2031 MVT::Other, getControlRoot(),
2032 DAG.getBasicBlock(Return)));
2035 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2036 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2039 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2040 assert(FuncInfo.MBB->isLandingPad() &&
2041 "Call to landingpad not in landing pad!");
2043 MachineBasicBlock *MBB = FuncInfo.MBB;
2044 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2045 AddLandingPadInfo(LP, MMI, MBB);
2047 // If there aren't registers to copy the values into (e.g., during SjLj
2048 // exceptions), then don't bother to create these DAG nodes.
2049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2050 if (TLI.getExceptionPointerRegister() == 0 &&
2051 TLI.getExceptionSelectorRegister() == 0)
2054 SmallVector<EVT, 2> ValueVTs;
2055 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2056 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2058 // Get the two live-in registers as SDValues. The physregs have already been
2059 // copied into virtual registers.
2061 if (FuncInfo.ExceptionPointerVirtReg) {
2062 Ops[0] = DAG.getZExtOrTrunc(
2063 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2064 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2065 getCurSDLoc(), ValueVTs[0]);
2067 Ops[0] = DAG.getConstant(0, TLI.getPointerTy());
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);
2081 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
2082 MachineBasicBlock *LPadBB) {
2083 SDValue Chain = getControlRoot();
2085 // Get the typeid that we will dispatch on later.
2086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2087 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
2088 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
2089 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
2090 SDValue Sel = DAG.getConstant(TypeID, TLI.getPointerTy());
2091 Chain = DAG.getCopyToReg(Chain, getCurSDLoc(), VReg, Sel);
2093 // Branch to the main landing pad block.
2094 MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
2095 ClauseMBB->addSuccessor(LPadBB);
2096 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, Chain,
2097 DAG.getBasicBlock(LPadBB)));
2101 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2102 /// small case ranges).
2103 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2104 CaseRecVector& WorkList,
2106 MachineBasicBlock *Default,
2107 MachineBasicBlock *SwitchBB) {
2108 // Size is the number of Cases represented by this range.
2109 size_t Size = CR.Range.second - CR.Range.first;
2113 // Get the MachineFunction which holds the current MBB. This is used when
2114 // inserting any additional MBBs necessary to represent the switch.
2115 MachineFunction *CurMF = FuncInfo.MF;
2117 // Figure out which block is immediately after the current one.
2118 MachineBasicBlock *NextMBB = nullptr;
2119 MachineFunction::iterator BBI = CR.CaseBB;
2120 if (++BBI != FuncInfo.MF->end())
2123 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2124 // If any two of the cases has the same destination, and if one value
2125 // is the same as the other, but has one bit unset that the other has set,
2126 // use bit manipulation to do two compares at once. For example:
2127 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2128 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2129 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2130 if (Size == 2 && CR.CaseBB == SwitchBB) {
2131 Case &Small = *CR.Range.first;
2132 Case &Big = *(CR.Range.second-1);
2134 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2135 const APInt& SmallValue = Small.Low->getValue();
2136 const APInt& BigValue = Big.Low->getValue();
2138 // Check that there is only one bit different.
2139 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2140 (SmallValue | BigValue) == BigValue) {
2141 // Isolate the common bit.
2142 APInt CommonBit = BigValue & ~SmallValue;
2143 assert((SmallValue | CommonBit) == BigValue &&
2144 CommonBit.countPopulation() == 1 && "Not a common bit?");
2146 SDValue CondLHS = getValue(SV);
2147 EVT VT = CondLHS.getValueType();
2148 SDLoc DL = getCurSDLoc();
2150 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2151 DAG.getConstant(CommonBit, VT));
2152 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2153 Or, DAG.getConstant(BigValue, VT),
2156 // Update successor info.
2157 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2158 addSuccessorWithWeight(SwitchBB, Small.BB,
2159 Small.ExtraWeight + Big.ExtraWeight);
2160 addSuccessorWithWeight(SwitchBB, Default,
2161 // The default destination is the first successor in IR.
2162 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2164 // Insert the true branch.
2165 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2166 getControlRoot(), Cond,
2167 DAG.getBasicBlock(Small.BB));
2169 // Insert the false branch.
2170 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2171 DAG.getBasicBlock(Default));
2173 DAG.setRoot(BrCond);
2179 // Order cases by weight so the most likely case will be checked first.
2180 uint32_t UnhandledWeights = 0;
2182 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2183 uint32_t IWeight = I->ExtraWeight;
2184 UnhandledWeights += IWeight;
2185 for (CaseItr J = CR.Range.first; J < I; ++J) {
2186 uint32_t JWeight = J->ExtraWeight;
2187 if (IWeight > JWeight)
2192 // Rearrange the case blocks so that the last one falls through if possible.
2193 Case &BackCase = *(CR.Range.second-1);
2194 if (Size > 1 && NextMBB && Default != NextMBB && BackCase.BB != NextMBB) {
2195 // The last case block won't fall through into 'NextMBB' if we emit the
2196 // branches in this order. See if rearranging a case value would help.
2197 // We start at the bottom as it's the case with the least weight.
2198 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2199 if (I->BB == NextMBB) {
2200 std::swap(*I, BackCase);
2205 // Create a CaseBlock record representing a conditional branch to
2206 // the Case's target mbb if the value being switched on SV is equal
2208 MachineBasicBlock *CurBlock = CR.CaseBB;
2209 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2210 MachineBasicBlock *FallThrough;
2212 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2213 CurMF->insert(BBI, FallThrough);
2215 // Put SV in a virtual register to make it available from the new blocks.
2216 ExportFromCurrentBlock(SV);
2218 // If the last case doesn't match, go to the default block.
2219 FallThrough = Default;
2222 const Value *RHS, *LHS, *MHS;
2224 if (I->High == I->Low) {
2225 // This is just small small case range :) containing exactly 1 case
2227 LHS = SV; RHS = I->High; MHS = nullptr;
2230 LHS = I->Low; MHS = SV; RHS = I->High;
2233 // The false weight should be sum of all un-handled cases.
2234 UnhandledWeights -= I->ExtraWeight;
2235 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2237 /* trueweight */ I->ExtraWeight,
2238 /* falseweight */ UnhandledWeights);
2240 // If emitting the first comparison, just call visitSwitchCase to emit the
2241 // code into the current block. Otherwise, push the CaseBlock onto the
2242 // vector to be later processed by SDISel, and insert the node's MBB
2243 // before the next MBB.
2244 if (CurBlock == SwitchBB)
2245 visitSwitchCase(CB, SwitchBB);
2247 SwitchCases.push_back(CB);
2249 CurBlock = FallThrough;
2255 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2256 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2257 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2260 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2261 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2262 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2263 return (LastExt - FirstExt + 1ULL);
2266 /// handleJTSwitchCase - Emit jumptable for current switch case range
2267 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2268 CaseRecVector &WorkList,
2270 MachineBasicBlock *Default,
2271 MachineBasicBlock *SwitchBB) {
2272 Case& FrontCase = *CR.Range.first;
2273 Case& BackCase = *(CR.Range.second-1);
2275 const APInt &First = FrontCase.Low->getValue();
2276 const APInt &Last = BackCase.High->getValue();
2278 APInt TSize(First.getBitWidth(), 0);
2279 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2283 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2286 APInt Range = ComputeRange(First, Last);
2287 // The density is TSize / Range. Require at least 40%.
2288 // It should not be possible for IntTSize to saturate for sane code, but make
2289 // sure we handle Range saturation correctly.
2290 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2291 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2292 if (IntTSize * 10 < IntRange * 4)
2295 DEBUG(dbgs() << "Lowering jump table\n"
2296 << "First entry: " << First << ". Last entry: " << Last << '\n'
2297 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2299 // Get the MachineFunction which holds the current MBB. This is used when
2300 // inserting any additional MBBs necessary to represent the switch.
2301 MachineFunction *CurMF = FuncInfo.MF;
2303 // Figure out which block is immediately after the current one.
2304 MachineFunction::iterator BBI = CR.CaseBB;
2307 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2309 // Create a new basic block to hold the code for loading the address
2310 // of the jump table, and jumping to it. Update successor information;
2311 // we will either branch to the default case for the switch, or the jump
2313 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2314 CurMF->insert(BBI, JumpTableBB);
2316 addSuccessorWithWeight(CR.CaseBB, Default);
2317 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2319 // Build a vector of destination BBs, corresponding to each target
2320 // of the jump table. If the value of the jump table slot corresponds to
2321 // a case statement, push the case's BB onto the vector, otherwise, push
2323 std::vector<MachineBasicBlock*> DestBBs;
2325 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2326 const APInt &Low = I->Low->getValue();
2327 const APInt &High = I->High->getValue();
2329 if (Low.sle(TEI) && TEI.sle(High)) {
2330 DestBBs.push_back(I->BB);
2334 DestBBs.push_back(Default);
2338 // Calculate weight for each unique destination in CR.
2339 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2341 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2342 DestWeights[I->BB] += I->ExtraWeight;
2345 // Update successor info. Add one edge to each unique successor.
2346 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2347 for (MachineBasicBlock *DestBB : DestBBs) {
2348 if (!SuccsHandled[DestBB->getNumber()]) {
2349 SuccsHandled[DestBB->getNumber()] = true;
2350 auto I = DestWeights.find(DestBB);
2351 addSuccessorWithWeight(JumpTableBB, DestBB,
2352 I != DestWeights.end() ? I->second : 0);
2356 // Create a jump table index for this jump table.
2357 unsigned JTEncoding = TLI.getJumpTableEncoding();
2358 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2359 ->createJumpTableIndex(DestBBs);
2361 // Set the jump table information so that we can codegen it as a second
2362 // MachineBasicBlock
2363 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2364 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2365 if (CR.CaseBB == SwitchBB)
2366 visitJumpTableHeader(JT, JTH, SwitchBB);
2368 JTCases.push_back(JumpTableBlock(JTH, JT));
2372 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2374 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2375 CaseRecVector& WorkList,
2377 MachineBasicBlock* SwitchBB) {
2378 Case& FrontCase = *CR.Range.first;
2379 Case& BackCase = *(CR.Range.second-1);
2381 // Size is the number of Cases represented by this range.
2382 unsigned Size = CR.Range.second - CR.Range.first;
2384 const APInt &First = FrontCase.Low->getValue();
2385 const APInt &Last = BackCase.High->getValue();
2387 CaseItr Pivot = CR.Range.first + Size/2;
2389 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2390 // (heuristically) allow us to emit JumpTable's later.
2391 APInt TSize(First.getBitWidth(), 0);
2392 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2396 APInt LSize = FrontCase.size();
2397 APInt RSize = TSize-LSize;
2398 DEBUG(dbgs() << "Selecting best pivot: \n"
2399 << "First: " << First << ", Last: " << Last <<'\n'
2400 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2401 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2402 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2404 const APInt &LEnd = I->High->getValue();
2405 const APInt &RBegin = J->Low->getValue();
2406 APInt Range = ComputeRange(LEnd, RBegin);
2407 assert((Range - 2ULL).isNonNegative() &&
2408 "Invalid case distance");
2409 // Use volatile double here to avoid excess precision issues on some hosts,
2410 // e.g. that use 80-bit X87 registers.
2411 // Only consider the density of sub-ranges that actually have sufficient
2412 // entries to be lowered as a jump table.
2413 volatile double LDensity =
2414 LSize.ult(TLI.getMinimumJumpTableEntries())
2416 : LSize.roundToDouble() / (LEnd - First + 1ULL).roundToDouble();
2417 volatile double RDensity =
2418 RSize.ult(TLI.getMinimumJumpTableEntries())
2420 : RSize.roundToDouble() / (Last - RBegin + 1ULL).roundToDouble();
2421 volatile double Metric = Range.logBase2() * (LDensity + RDensity);
2422 // Should always split in some non-trivial place
2423 DEBUG(dbgs() <<"=>Step\n"
2424 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2425 << "LDensity: " << LDensity
2426 << ", RDensity: " << RDensity << '\n'
2427 << "Metric: " << Metric << '\n');
2428 if (FMetric < Metric) {
2431 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2438 if (FMetric == 0 || !areJTsAllowed(TLI))
2439 Pivot = CR.Range.first + Size/2;
2440 splitSwitchCase(CR, Pivot, WorkList, SV, SwitchBB);
2444 void SelectionDAGBuilder::splitSwitchCase(CaseRec &CR, CaseItr Pivot,
2445 CaseRecVector &WorkList,
2447 MachineBasicBlock *SwitchBB) {
2448 // Get the MachineFunction which holds the current MBB. This is used when
2449 // inserting any additional MBBs necessary to represent the switch.
2450 MachineFunction *CurMF = FuncInfo.MF;
2452 // Figure out which block is immediately after the current one.
2453 MachineFunction::iterator BBI = CR.CaseBB;
2456 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2458 CaseRange LHSR(CR.Range.first, Pivot);
2459 CaseRange RHSR(Pivot, CR.Range.second);
2460 const ConstantInt *C = Pivot->Low;
2461 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2463 // We know that we branch to the LHS if the Value being switched on is
2464 // less than the Pivot value, C. We use this to optimize our binary
2465 // tree a bit, by recognizing that if SV is greater than or equal to the
2466 // LHS's Case Value, and that Case Value is exactly one less than the
2467 // Pivot's Value, then we can branch directly to the LHS's Target,
2468 // rather than creating a leaf node for it.
2469 if ((LHSR.second - LHSR.first) == 1 && LHSR.first->High == CR.GE &&
2470 C->getValue() == (CR.GE->getValue() + 1LL)) {
2471 TrueBB = LHSR.first->BB;
2473 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2474 CurMF->insert(BBI, TrueBB);
2475 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2477 // Put SV in a virtual register to make it available from the new blocks.
2478 ExportFromCurrentBlock(SV);
2481 // Similar to the optimization above, if the Value being switched on is
2482 // known to be less than the Constant CR.LT, and the current Case Value
2483 // is CR.LT - 1, then we can branch directly to the target block for
2484 // the current Case Value, rather than emitting a RHS leaf node for it.
2485 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2486 RHSR.first->Low->getValue() == (CR.LT->getValue() - 1LL)) {
2487 FalseBB = RHSR.first->BB;
2489 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2490 CurMF->insert(BBI, FalseBB);
2491 WorkList.push_back(CaseRec(FalseBB, CR.LT, C, RHSR));
2493 // Put SV in a virtual register to make it available from the new blocks.
2494 ExportFromCurrentBlock(SV);
2497 // Create a CaseBlock record representing a conditional branch to
2498 // the LHS node if the value being switched on SV is less than C.
2499 // Otherwise, branch to LHS.
2500 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2502 if (CR.CaseBB == SwitchBB)
2503 visitSwitchCase(CB, SwitchBB);
2505 SwitchCases.push_back(CB);
2508 /// handleBitTestsSwitchCase - if current case range has few destination and
2509 /// range span less, than machine word bitwidth, encode case range into series
2510 /// of masks and emit bit tests with these masks.
2511 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2512 CaseRecVector& WorkList,
2514 MachineBasicBlock* Default,
2515 MachineBasicBlock* SwitchBB) {
2516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2517 EVT PTy = TLI.getPointerTy();
2518 unsigned IntPtrBits = PTy.getSizeInBits();
2520 Case& FrontCase = *CR.Range.first;
2521 Case& BackCase = *(CR.Range.second-1);
2523 // Get the MachineFunction which holds the current MBB. This is used when
2524 // inserting any additional MBBs necessary to represent the switch.
2525 MachineFunction *CurMF = FuncInfo.MF;
2527 // If target does not have legal shift left, do not emit bit tests at all.
2528 if (!TLI.isOperationLegal(ISD::SHL, PTy))
2532 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2533 // Single case counts one, case range - two.
2534 numCmps += (I->Low == I->High ? 1 : 2);
2537 // Count unique destinations
2538 SmallSet<MachineBasicBlock*, 4> Dests;
2539 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2540 Dests.insert(I->BB);
2541 if (Dests.size() > 3)
2542 // Don't bother the code below, if there are too much unique destinations
2545 DEBUG(dbgs() << "Total number of unique destinations: "
2546 << Dests.size() << '\n'
2547 << "Total number of comparisons: " << numCmps << '\n');
2549 // Compute span of values.
2550 const APInt& minValue = FrontCase.Low->getValue();
2551 const APInt& maxValue = BackCase.High->getValue();
2552 APInt cmpRange = maxValue - minValue;
2554 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2555 << "Low bound: " << minValue << '\n'
2556 << "High bound: " << maxValue << '\n');
2558 if (cmpRange.uge(IntPtrBits) ||
2559 (!(Dests.size() == 1 && numCmps >= 3) &&
2560 !(Dests.size() == 2 && numCmps >= 5) &&
2561 !(Dests.size() >= 3 && numCmps >= 6)))
2564 DEBUG(dbgs() << "Emitting bit tests\n");
2565 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2567 // Optimize the case where all the case values fit in a
2568 // word without having to subtract minValue. In this case,
2569 // we can optimize away the subtraction.
2570 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2571 cmpRange = maxValue;
2573 lowBound = minValue;
2576 CaseBitsVector CasesBits;
2577 unsigned i, count = 0;
2579 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2580 MachineBasicBlock* Dest = I->BB;
2581 for (i = 0; i < count; ++i)
2582 if (Dest == CasesBits[i].BB)
2586 assert((count < 3) && "Too much destinations to test!");
2587 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2591 const APInt& lowValue = I->Low->getValue();
2592 const APInt& highValue = I->High->getValue();
2594 uint64_t lo = (lowValue - lowBound).getZExtValue();
2595 uint64_t hi = (highValue - lowBound).getZExtValue();
2596 CasesBits[i].ExtraWeight += I->ExtraWeight;
2598 for (uint64_t j = lo; j <= hi; j++) {
2599 CasesBits[i].Mask |= 1ULL << j;
2600 CasesBits[i].Bits++;
2604 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2608 // Figure out which block is immediately after the current one.
2609 MachineFunction::iterator BBI = CR.CaseBB;
2612 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2614 DEBUG(dbgs() << "Cases:\n");
2615 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2616 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2617 << ", Bits: " << CasesBits[i].Bits
2618 << ", BB: " << CasesBits[i].BB << '\n');
2620 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2621 CurMF->insert(BBI, CaseBB);
2622 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2624 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2626 // Put SV in a virtual register to make it available from the new blocks.
2627 ExportFromCurrentBlock(SV);
2630 BitTestBlock BTB(lowBound, cmpRange, SV,
2631 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2632 CR.CaseBB, Default, std::move(BTC));
2634 if (CR.CaseBB == SwitchBB)
2635 visitBitTestHeader(BTB, SwitchBB);
2637 BitTestCases.push_back(std::move(BTB));
2642 void SelectionDAGBuilder::Clusterify(CaseVector &Cases, const SwitchInst *SI) {
2643 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2645 // Extract cases from the switch and sort them.
2646 typedef std::pair<const ConstantInt*, unsigned> CasePair;
2647 std::vector<CasePair> Sorted;
2648 Sorted.reserve(SI->getNumCases());
2649 for (auto I : SI->cases())
2650 Sorted.push_back(std::make_pair(I.getCaseValue(), I.getSuccessorIndex()));
2651 std::sort(Sorted.begin(), Sorted.end(), [](CasePair a, CasePair b) {
2652 return a.first->getValue().slt(b.first->getValue());
2655 // Merge adjacent cases with the same destination, build Cases vector.
2656 assert(Cases.empty() && "Cases should be empty before Clusterify;");
2657 Cases.reserve(SI->getNumCases());
2658 MachineBasicBlock *PreviousSucc = nullptr;
2659 for (CasePair &CP : Sorted) {
2660 const ConstantInt *CaseVal = CP.first;
2661 unsigned SuccIndex = CP.second;
2662 MachineBasicBlock *Succ = FuncInfo.MBBMap[SI->getSuccessor(SuccIndex)];
2663 uint32_t Weight = BPI ? BPI->getEdgeWeight(SI->getParent(), SuccIndex) : 0;
2665 if (PreviousSucc == Succ &&
2666 (CaseVal->getValue() - Cases.back().High->getValue()) == 1) {
2667 // If this case has the same successor and is a neighbour, merge it into
2668 // the previous cluster.
2669 Cases.back().High = CaseVal;
2670 Cases.back().ExtraWeight += Weight;
2672 Cases.push_back(Case(CaseVal, CaseVal, Succ, Weight));
2675 PreviousSucc = Succ;
2680 for (auto &I : Cases)
2681 // A range counts double, since it requires two compares.
2682 numCmps += I.Low != I.High ? 2 : 1;
2684 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2685 << ". Total compares: " << numCmps << '\n';
2689 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2690 MachineBasicBlock *Last) {
2692 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2693 if (JTCases[i].first.HeaderBB == First)
2694 JTCases[i].first.HeaderBB = Last;
2696 // Update BitTestCases.
2697 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2698 if (BitTestCases[i].Parent == First)
2699 BitTestCases[i].Parent = Last;
2702 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2703 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2705 // Create a vector of Cases, sorted so that we can efficiently create a binary
2706 // search tree from them.
2708 Clusterify(Cases, &SI);
2710 // Get the default destination MBB.
2711 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2713 if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
2715 // Replace an unreachable default destination with the most popular case
2717 DenseMap<const BasicBlock *, unsigned> Popularity;
2718 unsigned MaxPop = 0;
2719 const BasicBlock *MaxBB = nullptr;
2720 for (auto I : SI.cases()) {
2721 const BasicBlock *BB = I.getCaseSuccessor();
2722 if (++Popularity[BB] > MaxPop) {
2723 MaxPop = Popularity[BB];
2731 Default = FuncInfo.MBBMap[MaxBB];
2733 // Remove cases that were pointing to the destination that is now the default.
2734 Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
2735 [&](const Case &C) { return C.BB == Default; }),
2739 // If there is only the default destination, go there directly.
2740 if (Cases.empty()) {
2741 // Update machine-CFG edges.
2742 SwitchMBB->addSuccessor(Default);
2744 // If this is not a fall-through branch, emit the branch.
2745 if (Default != NextBlock(SwitchMBB)) {
2746 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2747 getControlRoot(), DAG.getBasicBlock(Default)));
2752 // Get the Value to be switched on.
2753 const Value *SV = SI.getCondition();
2755 // Push the initial CaseRec onto the worklist
2756 CaseRecVector WorkList;
2757 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2758 CaseRange(Cases.begin(),Cases.end())));
2760 while (!WorkList.empty()) {
2761 // Grab a record representing a case range to process off the worklist
2762 CaseRec CR = WorkList.back();
2763 WorkList.pop_back();
2765 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2768 // If the range has few cases (two or less) emit a series of specific
2770 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2773 // If the switch has more than N blocks, and is at least 40% dense, and the
2774 // target supports indirect branches, then emit a jump table rather than
2775 // lowering the switch to a binary tree of conditional branches.
2776 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2777 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2780 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2781 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2782 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2786 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2787 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2789 // Update machine-CFG edges with unique successors.
2790 SmallSet<BasicBlock*, 32> Done;
2791 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2792 BasicBlock *BB = I.getSuccessor(i);
2793 bool Inserted = Done.insert(BB).second;
2797 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2798 addSuccessorWithWeight(IndirectBrMBB, Succ);
2801 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2802 MVT::Other, getControlRoot(),
2803 getValue(I.getAddress())));
2806 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2807 if (DAG.getTarget().Options.TrapUnreachable)
2808 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2811 void SelectionDAGBuilder::visitFSub(const User &I) {
2812 // -0.0 - X --> fneg
2813 Type *Ty = I.getType();
2814 if (isa<Constant>(I.getOperand(0)) &&
2815 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2816 SDValue Op2 = getValue(I.getOperand(1));
2817 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2818 Op2.getValueType(), Op2));
2822 visitBinary(I, ISD::FSUB);
2825 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2826 SDValue Op1 = getValue(I.getOperand(0));
2827 SDValue Op2 = getValue(I.getOperand(1));
2832 if (const OverflowingBinaryOperator *OFBinOp =
2833 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2834 nuw = OFBinOp->hasNoUnsignedWrap();
2835 nsw = OFBinOp->hasNoSignedWrap();
2837 if (const PossiblyExactOperator *ExactOp =
2838 dyn_cast<const PossiblyExactOperator>(&I))
2839 exact = ExactOp->isExact();
2841 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2842 Op1, Op2, nuw, nsw, exact);
2843 setValue(&I, BinNodeValue);
2846 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2847 SDValue Op1 = getValue(I.getOperand(0));
2848 SDValue Op2 = getValue(I.getOperand(1));
2851 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2853 // Coerce the shift amount to the right type if we can.
2854 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2855 unsigned ShiftSize = ShiftTy.getSizeInBits();
2856 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2857 SDLoc DL = getCurSDLoc();
2859 // If the operand is smaller than the shift count type, promote it.
2860 if (ShiftSize > Op2Size)
2861 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2863 // If the operand is larger than the shift count type but the shift
2864 // count type has enough bits to represent any shift value, truncate
2865 // it now. This is a common case and it exposes the truncate to
2866 // optimization early.
2867 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2868 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2869 // Otherwise we'll need to temporarily settle for some other convenient
2870 // type. Type legalization will make adjustments once the shiftee is split.
2872 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2879 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2881 if (const OverflowingBinaryOperator *OFBinOp =
2882 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2883 nuw = OFBinOp->hasNoUnsignedWrap();
2884 nsw = OFBinOp->hasNoSignedWrap();
2886 if (const PossiblyExactOperator *ExactOp =
2887 dyn_cast<const PossiblyExactOperator>(&I))
2888 exact = ExactOp->isExact();
2891 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2896 void SelectionDAGBuilder::visitSDiv(const User &I) {
2897 SDValue Op1 = getValue(I.getOperand(0));
2898 SDValue Op2 = getValue(I.getOperand(1));
2900 // Turn exact SDivs into multiplications.
2901 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2903 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2904 !isa<ConstantSDNode>(Op1) &&
2905 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2906 setValue(&I, DAG.getTargetLoweringInfo()
2907 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2909 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2913 void SelectionDAGBuilder::visitICmp(const User &I) {
2914 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2915 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2916 predicate = IC->getPredicate();
2917 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2918 predicate = ICmpInst::Predicate(IC->getPredicate());
2919 SDValue Op1 = getValue(I.getOperand(0));
2920 SDValue Op2 = getValue(I.getOperand(1));
2921 ISD::CondCode Opcode = getICmpCondCode(predicate);
2923 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2924 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2927 void SelectionDAGBuilder::visitFCmp(const User &I) {
2928 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2929 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2930 predicate = FC->getPredicate();
2931 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2932 predicate = FCmpInst::Predicate(FC->getPredicate());
2933 SDValue Op1 = getValue(I.getOperand(0));
2934 SDValue Op2 = getValue(I.getOperand(1));
2935 ISD::CondCode Condition = getFCmpCondCode(predicate);
2936 if (TM.Options.NoNaNsFPMath)
2937 Condition = getFCmpCodeWithoutNaN(Condition);
2938 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2939 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2942 void SelectionDAGBuilder::visitSelect(const User &I) {
2943 SmallVector<EVT, 4> ValueVTs;
2944 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2945 unsigned NumValues = ValueVTs.size();
2946 if (NumValues == 0) return;
2948 SmallVector<SDValue, 4> Values(NumValues);
2949 SDValue Cond = getValue(I.getOperand(0));
2950 SDValue TrueVal = getValue(I.getOperand(1));
2951 SDValue FalseVal = getValue(I.getOperand(2));
2952 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2953 ISD::VSELECT : ISD::SELECT;
2955 for (unsigned i = 0; i != NumValues; ++i)
2956 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2957 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2959 SDValue(TrueVal.getNode(),
2960 TrueVal.getResNo() + i),
2961 SDValue(FalseVal.getNode(),
2962 FalseVal.getResNo() + i));
2964 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2965 DAG.getVTList(ValueVTs), Values));
2968 void SelectionDAGBuilder::visitTrunc(const User &I) {
2969 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2970 SDValue N = getValue(I.getOperand(0));
2971 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2972 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2975 void SelectionDAGBuilder::visitZExt(const User &I) {
2976 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2977 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2978 SDValue N = getValue(I.getOperand(0));
2979 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2980 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2983 void SelectionDAGBuilder::visitSExt(const User &I) {
2984 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2985 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2986 SDValue N = getValue(I.getOperand(0));
2987 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2988 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2991 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2992 // FPTrunc is never a no-op cast, no need to check
2993 SDValue N = getValue(I.getOperand(0));
2994 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2995 EVT DestVT = TLI.getValueType(I.getType());
2996 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2997 DAG.getTargetConstant(0, TLI.getPointerTy())));
3000 void SelectionDAGBuilder::visitFPExt(const User &I) {
3001 // FPExt is never a no-op cast, no need to check
3002 SDValue N = getValue(I.getOperand(0));
3003 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3004 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3007 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3008 // FPToUI is never a no-op cast, no need to check
3009 SDValue N = getValue(I.getOperand(0));
3010 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3011 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3014 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3015 // FPToSI is never a no-op cast, no need to check
3016 SDValue N = getValue(I.getOperand(0));
3017 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3018 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3021 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3022 // UIToFP is never a no-op cast, no need to check
3023 SDValue N = getValue(I.getOperand(0));
3024 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3025 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3028 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3029 // SIToFP is never a no-op cast, no need to check
3030 SDValue N = getValue(I.getOperand(0));
3031 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3032 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3035 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3036 // What to do depends on the size of the integer and the size of the pointer.
3037 // We can either truncate, zero extend, or no-op, accordingly.
3038 SDValue N = getValue(I.getOperand(0));
3039 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3040 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3043 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3044 // What to do depends on the size of the integer and the size of the pointer.
3045 // We can either truncate, zero extend, or no-op, accordingly.
3046 SDValue N = getValue(I.getOperand(0));
3047 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3048 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3051 void SelectionDAGBuilder::visitBitCast(const User &I) {
3052 SDValue N = getValue(I.getOperand(0));
3053 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3055 // BitCast assures us that source and destination are the same size so this is
3056 // either a BITCAST or a no-op.
3057 if (DestVT != N.getValueType())
3058 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3059 DestVT, N)); // convert types.
3060 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3061 // might fold any kind of constant expression to an integer constant and that
3062 // is not what we are looking for. Only regcognize a bitcast of a genuine
3063 // constant integer as an opaque constant.
3064 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3065 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3068 setValue(&I, N); // noop cast.
3071 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3073 const Value *SV = I.getOperand(0);
3074 SDValue N = getValue(SV);
3075 EVT DestVT = TLI.getValueType(I.getType());
3077 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3078 unsigned DestAS = I.getType()->getPointerAddressSpace();
3080 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3081 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3086 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3088 SDValue InVec = getValue(I.getOperand(0));
3089 SDValue InVal = getValue(I.getOperand(1));
3090 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3091 getCurSDLoc(), TLI.getVectorIdxTy());
3092 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3093 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3096 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3098 SDValue InVec = getValue(I.getOperand(0));
3099 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3100 getCurSDLoc(), TLI.getVectorIdxTy());
3101 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3102 TLI.getValueType(I.getType()), InVec, InIdx));
3105 // Utility for visitShuffleVector - Return true if every element in Mask,
3106 // beginning from position Pos and ending in Pos+Size, falls within the
3107 // specified sequential range [L, L+Pos). or is undef.
3108 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3109 unsigned Pos, unsigned Size, int Low) {
3110 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3111 if (Mask[i] >= 0 && Mask[i] != Low)
3116 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3117 SDValue Src1 = getValue(I.getOperand(0));
3118 SDValue Src2 = getValue(I.getOperand(1));
3120 SmallVector<int, 8> Mask;
3121 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3122 unsigned MaskNumElts = Mask.size();
3124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3125 EVT VT = TLI.getValueType(I.getType());
3126 EVT SrcVT = Src1.getValueType();
3127 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3129 if (SrcNumElts == MaskNumElts) {
3130 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3135 // Normalize the shuffle vector since mask and vector length don't match.
3136 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3137 // Mask is longer than the source vectors and is a multiple of the source
3138 // vectors. We can use concatenate vector to make the mask and vectors
3140 if (SrcNumElts*2 == MaskNumElts) {
3141 // First check for Src1 in low and Src2 in high
3142 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3143 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3144 // The shuffle is concatenating two vectors together.
3145 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3149 // Then check for Src2 in low and Src1 in high
3150 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3151 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3152 // The shuffle is concatenating two vectors together.
3153 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3159 // Pad both vectors with undefs to make them the same length as the mask.
3160 unsigned NumConcat = MaskNumElts / SrcNumElts;
3161 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3162 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3163 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3165 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3166 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3170 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3171 getCurSDLoc(), VT, MOps1);
3172 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3173 getCurSDLoc(), VT, MOps2);
3175 // Readjust mask for new input vector length.
3176 SmallVector<int, 8> MappedOps;
3177 for (unsigned i = 0; i != MaskNumElts; ++i) {
3179 if (Idx >= (int)SrcNumElts)
3180 Idx -= SrcNumElts - MaskNumElts;
3181 MappedOps.push_back(Idx);
3184 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3189 if (SrcNumElts > MaskNumElts) {
3190 // Analyze the access pattern of the vector to see if we can extract
3191 // two subvectors and do the shuffle. The analysis is done by calculating
3192 // the range of elements the mask access on both vectors.
3193 int MinRange[2] = { static_cast<int>(SrcNumElts),
3194 static_cast<int>(SrcNumElts)};
3195 int MaxRange[2] = {-1, -1};
3197 for (unsigned i = 0; i != MaskNumElts; ++i) {