xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 9cd7f88a35cbcaa51ca2c6eb02be31cca2a6d8cc)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/FunctionLoweringInfo.h"
41 #include "llvm/CodeGen/GCMetadata.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineJumpTableInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RuntimeLibcalls.h"
54 #include "llvm/CodeGen/SelectionDAG.h"
55 #include "llvm/CodeGen/SelectionDAGNodes.h"
56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 
125 #define DEBUG_TYPE "isel"
126 
127 /// LimitFloatPrecision - Generate low-precision inline sequences for
128 /// some float libcalls (6, 8 or 12 bits).
129 static unsigned LimitFloatPrecision;
130 
131 static cl::opt<unsigned, true>
132     LimitFPPrecision("limit-float-precision",
133                      cl::desc("Generate low-precision inline sequences "
134                               "for some float libcalls"),
135                      cl::location(LimitFloatPrecision), cl::Hidden,
136                      cl::init(0));
137 
138 static cl::opt<unsigned> SwitchPeelThreshold(
139     "switch-peel-threshold", cl::Hidden, cl::init(66),
140     cl::desc("Set the case probability threshold for peeling the case from a "
141              "switch statement. A value greater than 100 will void this "
142              "optimization"));
143 
144 // Limit the width of DAG chains. This is important in general to prevent
145 // DAG-based analysis from blowing up. For example, alias analysis and
146 // load clustering may not complete in reasonable time. It is difficult to
147 // recognize and avoid this situation within each individual analysis, and
148 // future analyses are likely to have the same behavior. Limiting DAG width is
149 // the safe approach and will be especially important with global DAGs.
150 //
151 // MaxParallelChains default is arbitrarily high to avoid affecting
152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
153 // sequence over this should have been converted to llvm.memcpy by the
154 // frontend. It is easy to induce this behavior with .ll code such as:
155 // %buffer = alloca [4096 x i8]
156 // %data = load [4096 x i8]* %argPtr
157 // store [4096 x i8] %data, [4096 x i8]* %buffer
158 static const unsigned MaxParallelChains = 64;
159 
160 // Return the calling convention if the Value passed requires ABI mangling as it
161 // is a parameter to a function or a return value from a function which is not
162 // an intrinsic.
163 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
164   if (auto *R = dyn_cast<ReturnInst>(V))
165     return R->getParent()->getParent()->getCallingConv();
166 
167   if (auto *CI = dyn_cast<CallInst>(V)) {
168     const bool IsInlineAsm = CI->isInlineAsm();
169     const bool IsIndirectFunctionCall =
170         !IsInlineAsm && !CI->getCalledFunction();
171 
172     // It is possible that the call instruction is an inline asm statement or an
173     // indirect function call in which case the return value of
174     // getCalledFunction() would be nullptr.
175     const bool IsInstrinsicCall =
176         !IsInlineAsm && !IsIndirectFunctionCall &&
177         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
178 
179     if (!IsInlineAsm && !IsInstrinsicCall)
180       return CI->getCallingConv();
181   }
182 
183   return None;
184 }
185 
186 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
187                                       const SDValue *Parts, unsigned NumParts,
188                                       MVT PartVT, EVT ValueVT, const Value *V,
189                                       Optional<CallingConv::ID> CC);
190 
191 /// getCopyFromParts - Create a value that contains the specified legal parts
192 /// combined into the value they represent.  If the parts combine to a type
193 /// larger than ValueVT then AssertOp can be used to specify whether the extra
194 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
195 /// (ISD::AssertSext).
196 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
197                                 const SDValue *Parts, unsigned NumParts,
198                                 MVT PartVT, EVT ValueVT, const Value *V,
199                                 Optional<CallingConv::ID> CC = None,
200                                 Optional<ISD::NodeType> AssertOp = None) {
201   if (ValueVT.isVector())
202     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
203                                   CC);
204 
205   assert(NumParts > 0 && "No parts to assemble!");
206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
207   SDValue Val = Parts[0];
208 
209   if (NumParts > 1) {
210     // Assemble the value from multiple parts.
211     if (ValueVT.isInteger()) {
212       unsigned PartBits = PartVT.getSizeInBits();
213       unsigned ValueBits = ValueVT.getSizeInBits();
214 
215       // Assemble the power of 2 part.
216       unsigned RoundParts = NumParts & (NumParts - 1) ?
217         1 << Log2_32(NumParts) : NumParts;
218       unsigned RoundBits = PartBits * RoundParts;
219       EVT RoundVT = RoundBits == ValueBits ?
220         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
221       SDValue Lo, Hi;
222 
223       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
224 
225       if (RoundParts > 2) {
226         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
227                               PartVT, HalfVT, V);
228         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
229                               RoundParts / 2, PartVT, HalfVT, V);
230       } else {
231         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
232         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
233       }
234 
235       if (DAG.getDataLayout().isBigEndian())
236         std::swap(Lo, Hi);
237 
238       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
239 
240       if (RoundParts < NumParts) {
241         // Assemble the trailing non-power-of-2 part.
242         unsigned OddParts = NumParts - RoundParts;
243         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
244         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
245                               OddVT, V, CC);
246 
247         // Combine the round and odd parts.
248         Lo = Val;
249         if (DAG.getDataLayout().isBigEndian())
250           std::swap(Lo, Hi);
251         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
252         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
253         Hi =
254             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
255                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
256                                         TLI.getPointerTy(DAG.getDataLayout())));
257         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
258         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
259       }
260     } else if (PartVT.isFloatingPoint()) {
261       // FP split into multiple FP parts (for ppcf128)
262       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
263              "Unexpected split");
264       SDValue Lo, Hi;
265       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
266       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
267       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
268         std::swap(Lo, Hi);
269       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
270     } else {
271       // FP split into integer parts (soft fp)
272       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
273              !PartVT.isVector() && "Unexpected split");
274       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
275       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
276     }
277   }
278 
279   // There is now one part, held in Val.  Correct it to match ValueVT.
280   // PartEVT is the type of the register class that holds the value.
281   // ValueVT is the type of the inline asm operation.
282   EVT PartEVT = Val.getValueType();
283 
284   if (PartEVT == ValueVT)
285     return Val;
286 
287   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
288       ValueVT.bitsLT(PartEVT)) {
289     // For an FP value in an integer part, we need to truncate to the right
290     // width first.
291     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
292     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
293   }
294 
295   // Handle types that have the same size.
296   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
297     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
298 
299   // Handle types with different sizes.
300   if (PartEVT.isInteger() && ValueVT.isInteger()) {
301     if (ValueVT.bitsLT(PartEVT)) {
302       // For a truncate, see if we have any information to
303       // indicate whether the truncated bits will always be
304       // zero or sign-extension.
305       if (AssertOp.hasValue())
306         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
307                           DAG.getValueType(ValueVT));
308       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
309     }
310     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
311   }
312 
313   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
314     // FP_ROUND's are always exact here.
315     if (ValueVT.bitsLT(Val.getValueType()))
316       return DAG.getNode(
317           ISD::FP_ROUND, DL, ValueVT, Val,
318           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
319 
320     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
321   }
322 
323   llvm_unreachable("Unknown mismatch!");
324 }
325 
326 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
327                                               const Twine &ErrMsg) {
328   const Instruction *I = dyn_cast_or_null<Instruction>(V);
329   if (!V)
330     return Ctx.emitError(ErrMsg);
331 
332   const char *AsmError = ", possible invalid constraint for vector type";
333   if (const CallInst *CI = dyn_cast<CallInst>(I))
334     if (isa<InlineAsm>(CI->getCalledValue()))
335       return Ctx.emitError(I, ErrMsg + AsmError);
336 
337   return Ctx.emitError(I, ErrMsg);
338 }
339 
340 /// getCopyFromPartsVector - Create a value that contains the specified legal
341 /// parts combined into the value they represent.  If the parts combine to a
342 /// type larger than ValueVT then AssertOp can be used to specify whether the
343 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
344 /// ValueVT (ISD::AssertSext).
345 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
346                                       const SDValue *Parts, unsigned NumParts,
347                                       MVT PartVT, EVT ValueVT, const Value *V,
348                                       Optional<CallingConv::ID> CallConv) {
349   assert(ValueVT.isVector() && "Not a vector value");
350   assert(NumParts > 0 && "No parts to assemble!");
351   const bool IsABIRegCopy = CallConv.hasValue();
352 
353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
354   SDValue Val = Parts[0];
355 
356   // Handle a multi-element vector.
357   if (NumParts > 1) {
358     EVT IntermediateVT;
359     MVT RegisterVT;
360     unsigned NumIntermediates;
361     unsigned NumRegs;
362 
363     if (IsABIRegCopy) {
364       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
365           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
366           NumIntermediates, RegisterVT);
367     } else {
368       NumRegs =
369           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
370                                      NumIntermediates, RegisterVT);
371     }
372 
373     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
374     NumParts = NumRegs; // Silence a compiler warning.
375     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
376     assert(RegisterVT.getSizeInBits() ==
377            Parts[0].getSimpleValueType().getSizeInBits() &&
378            "Part type sizes don't match!");
379 
380     // Assemble the parts into intermediate operands.
381     SmallVector<SDValue, 8> Ops(NumIntermediates);
382     if (NumIntermediates == NumParts) {
383       // If the register was not expanded, truncate or copy the value,
384       // as appropriate.
385       for (unsigned i = 0; i != NumParts; ++i)
386         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
387                                   PartVT, IntermediateVT, V);
388     } else if (NumParts > 0) {
389       // If the intermediate type was expanded, build the intermediate
390       // operands from the parts.
391       assert(NumParts % NumIntermediates == 0 &&
392              "Must expand into a divisible number of parts!");
393       unsigned Factor = NumParts / NumIntermediates;
394       for (unsigned i = 0; i != NumIntermediates; ++i)
395         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
396                                   PartVT, IntermediateVT, V);
397     }
398 
399     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
400     // intermediate operands.
401     EVT BuiltVectorTy =
402         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
403                          (IntermediateVT.isVector()
404                               ? IntermediateVT.getVectorNumElements() * NumParts
405                               : NumIntermediates));
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // If the element type of the source/dest vectors are the same, but the
419     // parts vector has more elements than the value vector, then we have a
420     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
421     // elements we want.
422     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
423       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
424              "Cannot narrow, it would be a lossy transformation");
425       return DAG.getNode(
426           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
427           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
428     }
429 
430     // Vector/Vector bitcast.
431     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
432       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
433 
434     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
435       "Cannot handle this kind of promotion");
436     // Promoted vector extract
437     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
438 
439   }
440 
441   // Trivial bitcast if the types are the same size and the destination
442   // vector type is legal.
443   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
444       TLI.isTypeLegal(ValueVT))
445     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
446 
447   if (ValueVT.getVectorNumElements() != 1) {
448      // Certain ABIs require that vectors are passed as integers. For vectors
449      // are the same size, this is an obvious bitcast.
450      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
451        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
452      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
453        // Bitcast Val back the original type and extract the corresponding
454        // vector we want.
455        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
456        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
457                                            ValueVT.getVectorElementType(), Elts);
458        Val = DAG.getBitcast(WiderVecType, Val);
459        return DAG.getNode(
460            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
461            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
462      }
463 
464      diagnosePossiblyInvalidConstraint(
465          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
466      return DAG.getUNDEF(ValueVT);
467   }
468 
469   // Handle cases such as i8 -> <1 x i1>
470   EVT ValueSVT = ValueVT.getVectorElementType();
471   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
472     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
473                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
474 
475   return DAG.getBuildVector(ValueVT, DL, Val);
476 }
477 
478 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
479                                  SDValue Val, SDValue *Parts, unsigned NumParts,
480                                  MVT PartVT, const Value *V,
481                                  Optional<CallingConv::ID> CallConv);
482 
483 /// getCopyToParts - Create a series of nodes that contain the specified value
484 /// split into legal parts.  If the parts contain more bits than Val, then, for
485 /// integers, ExtendKind can be used to specify how to generate the extra bits.
486 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
487                            SDValue *Parts, unsigned NumParts, MVT PartVT,
488                            const Value *V,
489                            Optional<CallingConv::ID> CallConv = None,
490                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
491   EVT ValueVT = Val.getValueType();
492 
493   // Handle the vector case separately.
494   if (ValueVT.isVector())
495     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
496                                 CallConv);
497 
498   unsigned PartBits = PartVT.getSizeInBits();
499   unsigned OrigNumParts = NumParts;
500   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
501          "Copying to an illegal type!");
502 
503   if (NumParts == 0)
504     return;
505 
506   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
507   EVT PartEVT = PartVT;
508   if (PartEVT == ValueVT) {
509     assert(NumParts == 1 && "No-op copy with multiple parts!");
510     Parts[0] = Val;
511     return;
512   }
513 
514   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
515     // If the parts cover more bits than the value has, promote the value.
516     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
517       assert(NumParts == 1 && "Do not know what to promote to!");
518       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
519     } else {
520       if (ValueVT.isFloatingPoint()) {
521         // FP values need to be bitcast, then extended if they are being put
522         // into a larger container.
523         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
524         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
525       }
526       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
527              ValueVT.isInteger() &&
528              "Unknown mismatch!");
529       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
530       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
531       if (PartVT == MVT::x86mmx)
532         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533     }
534   } else if (PartBits == ValueVT.getSizeInBits()) {
535     // Different types of the same size.
536     assert(NumParts == 1 && PartEVT != ValueVT);
537     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
538   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
539     // If the parts cover less bits than value has, truncate the value.
540     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
541            ValueVT.isInteger() &&
542            "Unknown mismatch!");
543     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
544     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
545     if (PartVT == MVT::x86mmx)
546       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547   }
548 
549   // The value may have changed - recompute ValueVT.
550   ValueVT = Val.getValueType();
551   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
552          "Failed to tile the value with PartVT!");
553 
554   if (NumParts == 1) {
555     if (PartEVT != ValueVT) {
556       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
557                                         "scalar-to-vector conversion failed");
558       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559     }
560 
561     Parts[0] = Val;
562     return;
563   }
564 
565   // Expand the value into multiple parts.
566   if (NumParts & (NumParts - 1)) {
567     // The number of parts is not a power of 2.  Split off and copy the tail.
568     assert(PartVT.isInteger() && ValueVT.isInteger() &&
569            "Do not know what to expand to!");
570     unsigned RoundParts = 1 << Log2_32(NumParts);
571     unsigned RoundBits = RoundParts * PartBits;
572     unsigned OddParts = NumParts - RoundParts;
573     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
574                                  DAG.getIntPtrConstant(RoundBits, DL));
575     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
576                    CallConv);
577 
578     if (DAG.getDataLayout().isBigEndian())
579       // The odd parts were reversed by getCopyToParts - unreverse them.
580       std::reverse(Parts + RoundParts, Parts + NumParts);
581 
582     NumParts = RoundParts;
583     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
584     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
585   }
586 
587   // The number of parts is a power of 2.  Repeatedly bisect the value using
588   // EXTRACT_ELEMENT.
589   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
590                          EVT::getIntegerVT(*DAG.getContext(),
591                                            ValueVT.getSizeInBits()),
592                          Val);
593 
594   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
595     for (unsigned i = 0; i < NumParts; i += StepSize) {
596       unsigned ThisBits = StepSize * PartBits / 2;
597       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
598       SDValue &Part0 = Parts[i];
599       SDValue &Part1 = Parts[i+StepSize/2];
600 
601       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
602                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
603       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
605 
606       if (ThisBits == PartBits && ThisVT != PartVT) {
607         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
608         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
609       }
610     }
611   }
612 
613   if (DAG.getDataLayout().isBigEndian())
614     std::reverse(Parts, Parts + OrigNumParts);
615 }
616 
617 /// getCopyToPartsVector - Create a series of nodes that contain the specified
618 /// value split into legal parts.
619 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
620                                  SDValue Val, SDValue *Parts, unsigned NumParts,
621                                  MVT PartVT, const Value *V,
622                                  Optional<CallingConv::ID> CallConv) {
623   EVT ValueVT = Val.getValueType();
624   assert(ValueVT.isVector() && "Not a vector");
625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
626   const bool IsABIRegCopy = CallConv.hasValue();
627 
628   if (NumParts == 1) {
629     EVT PartEVT = PartVT;
630     if (PartEVT == ValueVT) {
631       // Nothing to do.
632     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
633       // Bitconvert vector->vector case.
634       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
635     } else if (PartVT.isVector() &&
636                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
637                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
638       EVT ElementVT = PartVT.getVectorElementType();
639       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
640       // undef elements.
641       SmallVector<SDValue, 16> Ops;
642       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
643         Ops.push_back(DAG.getNode(
644             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
645             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
646 
647       for (unsigned i = ValueVT.getVectorNumElements(),
648            e = PartVT.getVectorNumElements(); i != e; ++i)
649         Ops.push_back(DAG.getUNDEF(ElementVT));
650 
651       Val = DAG.getBuildVector(PartVT, DL, Ops);
652 
653       // FIXME: Use CONCAT for 2x -> 4x.
654 
655       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
656       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
657     } else if (PartVT.isVector() &&
658                PartEVT.getVectorElementType().bitsGE(
659                  ValueVT.getVectorElementType()) &&
660                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
661 
662       // Promoted vector extract
663       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
664     } else {
665       if (ValueVT.getVectorNumElements() == 1) {
666         Val = DAG.getNode(
667             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
668             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
669       } else {
670         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
671                "lossy conversion of vector to scalar type");
672         EVT IntermediateType =
673             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
674         Val = DAG.getBitcast(IntermediateType, Val);
675         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676       }
677     }
678 
679     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
680     Parts[0] = Val;
681     return;
682   }
683 
684   // Handle a multi-element vector.
685   EVT IntermediateVT;
686   MVT RegisterVT;
687   unsigned NumIntermediates;
688   unsigned NumRegs;
689   if (IsABIRegCopy) {
690     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
691         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
692         NumIntermediates, RegisterVT);
693   } else {
694     NumRegs =
695         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
696                                    NumIntermediates, RegisterVT);
697   }
698   unsigned NumElements = ValueVT.getVectorNumElements();
699 
700   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
701   NumParts = NumRegs; // Silence a compiler warning.
702   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
703 
704   // Convert the vector to the appropiate type if necessary.
705   unsigned DestVectorNoElts =
706       NumIntermediates *
707       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
708   EVT BuiltVectorTy = EVT::getVectorVT(
709       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
710   if (Val.getValueType() != BuiltVectorTy)
711     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
712 
713   // Split the vector into intermediate operands.
714   SmallVector<SDValue, 8> Ops(NumIntermediates);
715   for (unsigned i = 0; i != NumIntermediates; ++i) {
716     if (IntermediateVT.isVector())
717       Ops[i] =
718           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
719                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
720                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
721     else
722       Ops[i] = DAG.getNode(
723           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
724           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
725   }
726 
727   // Split the intermediate operands into legal parts.
728   if (NumParts == NumIntermediates) {
729     // If the register was not expanded, promote or copy the value,
730     // as appropriate.
731     for (unsigned i = 0; i != NumParts; ++i)
732       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
733   } else if (NumParts > 0) {
734     // If the intermediate type was expanded, split each the value into
735     // legal parts.
736     assert(NumIntermediates != 0 && "division by zero");
737     assert(NumParts % NumIntermediates == 0 &&
738            "Must expand into a divisible number of parts!");
739     unsigned Factor = NumParts / NumIntermediates;
740     for (unsigned i = 0; i != NumIntermediates; ++i)
741       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
742                      CallConv);
743   }
744 }
745 
746 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
747                            EVT valuevt, Optional<CallingConv::ID> CC)
748     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
749       RegCount(1, regs.size()), CallConv(CC) {}
750 
751 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
752                            const DataLayout &DL, unsigned Reg, Type *Ty,
753                            Optional<CallingConv::ID> CC) {
754   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
755 
756   CallConv = CC;
757 
758   for (EVT ValueVT : ValueVTs) {
759     unsigned NumRegs =
760         isABIMangled()
761             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
762             : TLI.getNumRegisters(Context, ValueVT);
763     MVT RegisterVT =
764         isABIMangled()
765             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
766             : TLI.getRegisterType(Context, ValueVT);
767     for (unsigned i = 0; i != NumRegs; ++i)
768       Regs.push_back(Reg + i);
769     RegVTs.push_back(RegisterVT);
770     RegCount.push_back(NumRegs);
771     Reg += NumRegs;
772   }
773 }
774 
775 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
776                                       FunctionLoweringInfo &FuncInfo,
777                                       const SDLoc &dl, SDValue &Chain,
778                                       SDValue *Flag, const Value *V) const {
779   // A Value with type {} or [0 x %t] needs no registers.
780   if (ValueVTs.empty())
781     return SDValue();
782 
783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
784 
785   // Assemble the legal parts into the final values.
786   SmallVector<SDValue, 4> Values(ValueVTs.size());
787   SmallVector<SDValue, 8> Parts;
788   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
789     // Copy the legal parts from the registers.
790     EVT ValueVT = ValueVTs[Value];
791     unsigned NumRegs = RegCount[Value];
792     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
793                                           *DAG.getContext(),
794                                           CallConv.getValue(), RegVTs[Value])
795                                     : RegVTs[Value];
796 
797     Parts.resize(NumRegs);
798     for (unsigned i = 0; i != NumRegs; ++i) {
799       SDValue P;
800       if (!Flag) {
801         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
802       } else {
803         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
804         *Flag = P.getValue(2);
805       }
806 
807       Chain = P.getValue(1);
808       Parts[i] = P;
809 
810       // If the source register was virtual and if we know something about it,
811       // add an assert node.
812       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
813           !RegisterVT.isInteger() || RegisterVT.isVector())
814         continue;
815 
816       const FunctionLoweringInfo::LiveOutInfo *LOI =
817         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
818       if (!LOI)
819         continue;
820 
821       unsigned RegSize = RegisterVT.getSizeInBits();
822       unsigned NumSignBits = LOI->NumSignBits;
823       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
824 
825       if (NumZeroBits == RegSize) {
826         // The current value is a zero.
827         // Explicitly express that as it would be easier for
828         // optimizations to kick in.
829         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
830         continue;
831       }
832 
833       // FIXME: We capture more information than the dag can represent.  For
834       // now, just use the tightest assertzext/assertsext possible.
835       bool isSExt;
836       EVT FromVT(MVT::Other);
837       if (NumZeroBits) {
838         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
839         isSExt = false;
840       } else if (NumSignBits > 1) {
841         FromVT =
842             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
843         isSExt = true;
844       } else {
845         continue;
846       }
847       // Add an assertion node.
848       assert(FromVT != MVT::Other);
849       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
850                              RegisterVT, P, DAG.getValueType(FromVT));
851     }
852 
853     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
854                                      RegisterVT, ValueVT, V, CallConv);
855     Part += NumRegs;
856     Parts.clear();
857   }
858 
859   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
860 }
861 
862 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
863                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
864                                  const Value *V,
865                                  ISD::NodeType PreferredExtendType) const {
866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
867   ISD::NodeType ExtendKind = PreferredExtendType;
868 
869   // Get the list of the values's legal parts.
870   unsigned NumRegs = Regs.size();
871   SmallVector<SDValue, 8> Parts(NumRegs);
872   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
873     unsigned NumParts = RegCount[Value];
874 
875     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
876                                           *DAG.getContext(),
877                                           CallConv.getValue(), RegVTs[Value])
878                                     : RegVTs[Value];
879 
880     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
881       ExtendKind = ISD::ZERO_EXTEND;
882 
883     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
884                    NumParts, RegisterVT, V, CallConv, ExtendKind);
885     Part += NumParts;
886   }
887 
888   // Copy the parts into the registers.
889   SmallVector<SDValue, 8> Chains(NumRegs);
890   for (unsigned i = 0; i != NumRegs; ++i) {
891     SDValue Part;
892     if (!Flag) {
893       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
894     } else {
895       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
896       *Flag = Part.getValue(1);
897     }
898 
899     Chains[i] = Part.getValue(0);
900   }
901 
902   if (NumRegs == 1 || Flag)
903     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
904     // flagged to it. That is the CopyToReg nodes and the user are considered
905     // a single scheduling unit. If we create a TokenFactor and return it as
906     // chain, then the TokenFactor is both a predecessor (operand) of the
907     // user as well as a successor (the TF operands are flagged to the user).
908     // c1, f1 = CopyToReg
909     // c2, f2 = CopyToReg
910     // c3     = TokenFactor c1, c2
911     // ...
912     //        = op c3, ..., f2
913     Chain = Chains[NumRegs-1];
914   else
915     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
916 }
917 
918 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
919                                         unsigned MatchingIdx, const SDLoc &dl,
920                                         SelectionDAG &DAG,
921                                         std::vector<SDValue> &Ops) const {
922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
923 
924   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
925   if (HasMatching)
926     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
927   else if (!Regs.empty() &&
928            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
929     // Put the register class of the virtual registers in the flag word.  That
930     // way, later passes can recompute register class constraints for inline
931     // assembly as well as normal instructions.
932     // Don't do this for tied operands that can use the regclass information
933     // from the def.
934     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
935     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
936     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
937   }
938 
939   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
940   Ops.push_back(Res);
941 
942   if (Code == InlineAsm::Kind_Clobber) {
943     // Clobbers should always have a 1:1 mapping with registers, and may
944     // reference registers that have illegal (e.g. vector) types. Hence, we
945     // shouldn't try to apply any sort of splitting logic to them.
946     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
947            "No 1:1 mapping from clobbers to regs?");
948     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
949     (void)SP;
950     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
951       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
952       assert(
953           (Regs[I] != SP ||
954            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
955           "If we clobbered the stack pointer, MFI should know about it.");
956     }
957     return;
958   }
959 
960   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
961     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
962     MVT RegisterVT = RegVTs[Value];
963     for (unsigned i = 0; i != NumRegs; ++i) {
964       assert(Reg < Regs.size() && "Mismatch in # registers expected");
965       unsigned TheReg = Regs[Reg++];
966       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
967     }
968   }
969 }
970 
971 SmallVector<std::pair<unsigned, unsigned>, 4>
972 RegsForValue::getRegsAndSizes() const {
973   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
974   unsigned I = 0;
975   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
976     unsigned RegCount = std::get<0>(CountAndVT);
977     MVT RegisterVT = std::get<1>(CountAndVT);
978     unsigned RegisterSize = RegisterVT.getSizeInBits();
979     for (unsigned E = I + RegCount; I != E; ++I)
980       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
981   }
982   return OutVec;
983 }
984 
985 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
986                                const TargetLibraryInfo *li) {
987   AA = aa;
988   GFI = gfi;
989   LibInfo = li;
990   DL = &DAG.getDataLayout();
991   Context = DAG.getContext();
992   LPadToCallSiteMap.clear();
993 }
994 
995 void SelectionDAGBuilder::clear() {
996   NodeMap.clear();
997   UnusedArgNodeMap.clear();
998   PendingLoads.clear();
999   PendingExports.clear();
1000   CurInst = nullptr;
1001   HasTailCall = false;
1002   SDNodeOrder = LowestSDNodeOrder;
1003   StatepointLowering.clear();
1004 }
1005 
1006 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1007   DanglingDebugInfoMap.clear();
1008 }
1009 
1010 SDValue SelectionDAGBuilder::getRoot() {
1011   if (PendingLoads.empty())
1012     return DAG.getRoot();
1013 
1014   if (PendingLoads.size() == 1) {
1015     SDValue Root = PendingLoads[0];
1016     DAG.setRoot(Root);
1017     PendingLoads.clear();
1018     return Root;
1019   }
1020 
1021   // Otherwise, we have to make a token factor node.
1022   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1023                              PendingLoads);
1024   PendingLoads.clear();
1025   DAG.setRoot(Root);
1026   return Root;
1027 }
1028 
1029 SDValue SelectionDAGBuilder::getControlRoot() {
1030   SDValue Root = DAG.getRoot();
1031 
1032   if (PendingExports.empty())
1033     return Root;
1034 
1035   // Turn all of the CopyToReg chains into one factored node.
1036   if (Root.getOpcode() != ISD::EntryToken) {
1037     unsigned i = 0, e = PendingExports.size();
1038     for (; i != e; ++i) {
1039       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1040       if (PendingExports[i].getNode()->getOperand(0) == Root)
1041         break;  // Don't add the root if we already indirectly depend on it.
1042     }
1043 
1044     if (i == e)
1045       PendingExports.push_back(Root);
1046   }
1047 
1048   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1049                      PendingExports);
1050   PendingExports.clear();
1051   DAG.setRoot(Root);
1052   return Root;
1053 }
1054 
1055 void SelectionDAGBuilder::visit(const Instruction &I) {
1056   // Set up outgoing PHI node register values before emitting the terminator.
1057   if (isa<TerminatorInst>(&I)) {
1058     HandlePHINodesInSuccessorBlocks(I.getParent());
1059   }
1060 
1061   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1062   if (!isa<DbgInfoIntrinsic>(I))
1063     ++SDNodeOrder;
1064 
1065   CurInst = &I;
1066 
1067   visit(I.getOpcode(), I);
1068 
1069   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1070     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1071     // maps to this instruction.
1072     // TODO: We could handle all flags (nsw, etc) here.
1073     // TODO: If an IR instruction maps to >1 node, only the final node will have
1074     //       flags set.
1075     if (SDNode *Node = getNodeForIRValue(&I)) {
1076       SDNodeFlags IncomingFlags;
1077       IncomingFlags.copyFMF(*FPMO);
1078       if (!Node->getFlags().isDefined())
1079         Node->setFlags(IncomingFlags);
1080       else
1081         Node->intersectFlagsWith(IncomingFlags);
1082     }
1083   }
1084 
1085   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1086       !isStatepoint(&I)) // statepoints handle their exports internally
1087     CopyToExportRegsIfNeeded(&I);
1088 
1089   CurInst = nullptr;
1090 }
1091 
1092 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1093   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1094 }
1095 
1096 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1097   // Note: this doesn't use InstVisitor, because it has to work with
1098   // ConstantExpr's in addition to instructions.
1099   switch (Opcode) {
1100   default: llvm_unreachable("Unknown instruction type encountered!");
1101     // Build the switch statement using the Instruction.def file.
1102 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1103     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1104 #include "llvm/IR/Instruction.def"
1105   }
1106 }
1107 
1108 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1109                                                 const DIExpression *Expr) {
1110   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1111     const DbgValueInst *DI = DDI.getDI();
1112     DIVariable *DanglingVariable = DI->getVariable();
1113     DIExpression *DanglingExpr = DI->getExpression();
1114     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1115       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1116       return true;
1117     }
1118     return false;
1119   };
1120 
1121   for (auto &DDIMI : DanglingDebugInfoMap) {
1122     DanglingDebugInfoVector &DDIV = DDIMI.second;
1123     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1124   }
1125 }
1126 
1127 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1128 // generate the debug data structures now that we've seen its definition.
1129 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1130                                                    SDValue Val) {
1131   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1132   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1133     return;
1134 
1135   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1136   for (auto &DDI : DDIV) {
1137     const DbgValueInst *DI = DDI.getDI();
1138     assert(DI && "Ill-formed DanglingDebugInfo");
1139     DebugLoc dl = DDI.getdl();
1140     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1141     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1142     DILocalVariable *Variable = DI->getVariable();
1143     DIExpression *Expr = DI->getExpression();
1144     assert(Variable->isValidLocationForIntrinsic(dl) &&
1145            "Expected inlined-at fields to agree");
1146     SDDbgValue *SDV;
1147     if (Val.getNode()) {
1148       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1149         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1150                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1151         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1152         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1153         // inserted after the definition of Val when emitting the instructions
1154         // after ISel. An alternative could be to teach
1155         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1156         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1157                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1158                    << ValSDNodeOrder << "\n");
1159         SDV = getDbgValue(Val, Variable, Expr, dl,
1160                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1161         DAG.AddDbgValue(SDV, Val.getNode(), false);
1162       } else
1163         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1164                           << "in EmitFuncArgumentDbgValue\n");
1165     } else
1166       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1167   }
1168   DDIV.clear();
1169 }
1170 
1171 /// getCopyFromRegs - If there was virtual register allocated for the value V
1172 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1173 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1174   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1175   SDValue Result;
1176 
1177   if (It != FuncInfo.ValueMap.end()) {
1178     unsigned InReg = It->second;
1179 
1180     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1181                      DAG.getDataLayout(), InReg, Ty, getABIRegCopyCC(V));
1182     SDValue Chain = DAG.getEntryNode();
1183     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1184                                  V);
1185     resolveDanglingDebugInfo(V, Result);
1186   }
1187 
1188   return Result;
1189 }
1190 
1191 /// getValue - Return an SDValue for the given Value.
1192 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1193   // If we already have an SDValue for this value, use it. It's important
1194   // to do this first, so that we don't create a CopyFromReg if we already
1195   // have a regular SDValue.
1196   SDValue &N = NodeMap[V];
1197   if (N.getNode()) return N;
1198 
1199   // If there's a virtual register allocated and initialized for this
1200   // value, use it.
1201   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1202     return copyFromReg;
1203 
1204   // Otherwise create a new SDValue and remember it.
1205   SDValue Val = getValueImpl(V);
1206   NodeMap[V] = Val;
1207   resolveDanglingDebugInfo(V, Val);
1208   return Val;
1209 }
1210 
1211 // Return true if SDValue exists for the given Value
1212 bool SelectionDAGBuilder::findValue(const Value *V) const {
1213   return (NodeMap.find(V) != NodeMap.end()) ||
1214     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1215 }
1216 
1217 /// getNonRegisterValue - Return an SDValue for the given Value, but
1218 /// don't look in FuncInfo.ValueMap for a virtual register.
1219 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1220   // If we already have an SDValue for this value, use it.
1221   SDValue &N = NodeMap[V];
1222   if (N.getNode()) {
1223     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1224       // Remove the debug location from the node as the node is about to be used
1225       // in a location which may differ from the original debug location.  This
1226       // is relevant to Constant and ConstantFP nodes because they can appear
1227       // as constant expressions inside PHI nodes.
1228       N->setDebugLoc(DebugLoc());
1229     }
1230     return N;
1231   }
1232 
1233   // Otherwise create a new SDValue and remember it.
1234   SDValue Val = getValueImpl(V);
1235   NodeMap[V] = Val;
1236   resolveDanglingDebugInfo(V, Val);
1237   return Val;
1238 }
1239 
1240 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1241 /// Create an SDValue for the given value.
1242 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1244 
1245   if (const Constant *C = dyn_cast<Constant>(V)) {
1246     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1247 
1248     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1249       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1250 
1251     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1252       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1253 
1254     if (isa<ConstantPointerNull>(C)) {
1255       unsigned AS = V->getType()->getPointerAddressSpace();
1256       return DAG.getConstant(0, getCurSDLoc(),
1257                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1258     }
1259 
1260     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1261       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1262 
1263     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1264       return DAG.getUNDEF(VT);
1265 
1266     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1267       visit(CE->getOpcode(), *CE);
1268       SDValue N1 = NodeMap[V];
1269       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1270       return N1;
1271     }
1272 
1273     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1274       SmallVector<SDValue, 4> Constants;
1275       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1276            OI != OE; ++OI) {
1277         SDNode *Val = getValue(*OI).getNode();
1278         // If the operand is an empty aggregate, there are no values.
1279         if (!Val) continue;
1280         // Add each leaf value from the operand to the Constants list
1281         // to form a flattened list of all the values.
1282         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1283           Constants.push_back(SDValue(Val, i));
1284       }
1285 
1286       return DAG.getMergeValues(Constants, getCurSDLoc());
1287     }
1288 
1289     if (const ConstantDataSequential *CDS =
1290           dyn_cast<ConstantDataSequential>(C)) {
1291       SmallVector<SDValue, 4> Ops;
1292       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1293         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1294         // Add each leaf value from the operand to the Constants list
1295         // to form a flattened list of all the values.
1296         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1297           Ops.push_back(SDValue(Val, i));
1298       }
1299 
1300       if (isa<ArrayType>(CDS->getType()))
1301         return DAG.getMergeValues(Ops, getCurSDLoc());
1302       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1303     }
1304 
1305     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1306       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1307              "Unknown struct or array constant!");
1308 
1309       SmallVector<EVT, 4> ValueVTs;
1310       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1311       unsigned NumElts = ValueVTs.size();
1312       if (NumElts == 0)
1313         return SDValue(); // empty struct
1314       SmallVector<SDValue, 4> Constants(NumElts);
1315       for (unsigned i = 0; i != NumElts; ++i) {
1316         EVT EltVT = ValueVTs[i];
1317         if (isa<UndefValue>(C))
1318           Constants[i] = DAG.getUNDEF(EltVT);
1319         else if (EltVT.isFloatingPoint())
1320           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1321         else
1322           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1323       }
1324 
1325       return DAG.getMergeValues(Constants, getCurSDLoc());
1326     }
1327 
1328     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1329       return DAG.getBlockAddress(BA, VT);
1330 
1331     VectorType *VecTy = cast<VectorType>(V->getType());
1332     unsigned NumElements = VecTy->getNumElements();
1333 
1334     // Now that we know the number and type of the elements, get that number of
1335     // elements into the Ops array based on what kind of constant it is.
1336     SmallVector<SDValue, 16> Ops;
1337     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1338       for (unsigned i = 0; i != NumElements; ++i)
1339         Ops.push_back(getValue(CV->getOperand(i)));
1340     } else {
1341       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1342       EVT EltVT =
1343           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1344 
1345       SDValue Op;
1346       if (EltVT.isFloatingPoint())
1347         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1348       else
1349         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1350       Ops.assign(NumElements, Op);
1351     }
1352 
1353     // Create a BUILD_VECTOR node.
1354     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1355   }
1356 
1357   // If this is a static alloca, generate it as the frameindex instead of
1358   // computation.
1359   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1360     DenseMap<const AllocaInst*, int>::iterator SI =
1361       FuncInfo.StaticAllocaMap.find(AI);
1362     if (SI != FuncInfo.StaticAllocaMap.end())
1363       return DAG.getFrameIndex(SI->second,
1364                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1365   }
1366 
1367   // If this is an instruction which fast-isel has deferred, select it now.
1368   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1369     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1370 
1371     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1372                      Inst->getType(), getABIRegCopyCC(V));
1373     SDValue Chain = DAG.getEntryNode();
1374     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1375   }
1376 
1377   llvm_unreachable("Can't get register for value!");
1378 }
1379 
1380 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1381   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1382   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1383   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1384   bool IsSEH = isAsynchronousEHPersonality(Pers);
1385   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1386   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1387   if (!IsSEH)
1388     CatchPadMBB->setIsEHScopeEntry();
1389   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1390   if (IsMSVCCXX || IsCoreCLR)
1391     CatchPadMBB->setIsEHFuncletEntry();
1392   // Wasm does not need catchpads anymore
1393   if (!IsWasmCXX)
1394     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1395                             getControlRoot()));
1396 }
1397 
1398 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1399   // Update machine-CFG edge.
1400   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1401   FuncInfo.MBB->addSuccessor(TargetMBB);
1402 
1403   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1404   bool IsSEH = isAsynchronousEHPersonality(Pers);
1405   if (IsSEH) {
1406     // If this is not a fall-through branch or optimizations are switched off,
1407     // emit the branch.
1408     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1409         TM.getOptLevel() == CodeGenOpt::None)
1410       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1411                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1412     return;
1413   }
1414 
1415   // Figure out the funclet membership for the catchret's successor.
1416   // This will be used by the FuncletLayout pass to determine how to order the
1417   // BB's.
1418   // A 'catchret' returns to the outer scope's color.
1419   Value *ParentPad = I.getCatchSwitchParentPad();
1420   const BasicBlock *SuccessorColor;
1421   if (isa<ConstantTokenNone>(ParentPad))
1422     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1423   else
1424     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1425   assert(SuccessorColor && "No parent funclet for catchret!");
1426   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1427   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1428 
1429   // Create the terminator node.
1430   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1431                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1432                             DAG.getBasicBlock(SuccessorColorMBB));
1433   DAG.setRoot(Ret);
1434 }
1435 
1436 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1437   // Don't emit any special code for the cleanuppad instruction. It just marks
1438   // the start of an EH scope/funclet.
1439   FuncInfo.MBB->setIsEHScopeEntry();
1440   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1441   if (Pers != EHPersonality::Wasm_CXX) {
1442     FuncInfo.MBB->setIsEHFuncletEntry();
1443     FuncInfo.MBB->setIsCleanupFuncletEntry();
1444   }
1445 }
1446 
1447 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1448 /// many places it could ultimately go. In the IR, we have a single unwind
1449 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1450 /// This function skips over imaginary basic blocks that hold catchswitch
1451 /// instructions, and finds all the "real" machine
1452 /// basic block destinations. As those destinations may not be successors of
1453 /// EHPadBB, here we also calculate the edge probability to those destinations.
1454 /// The passed-in Prob is the edge probability to EHPadBB.
1455 static void findUnwindDestinations(
1456     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1457     BranchProbability Prob,
1458     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1459         &UnwindDests) {
1460   EHPersonality Personality =
1461     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1462   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1463   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1464   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1465   bool IsSEH = isAsynchronousEHPersonality(Personality);
1466 
1467   while (EHPadBB) {
1468     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1469     BasicBlock *NewEHPadBB = nullptr;
1470     if (isa<LandingPadInst>(Pad)) {
1471       // Stop on landingpads. They are not funclets.
1472       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1473       break;
1474     } else if (isa<CleanupPadInst>(Pad)) {
1475       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1476       // personalities.
1477       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1478       UnwindDests.back().first->setIsEHScopeEntry();
1479       if (!IsWasmCXX)
1480         UnwindDests.back().first->setIsEHFuncletEntry();
1481       break;
1482     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1483       // Add the catchpad handlers to the possible destinations.
1484       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1485         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1486         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1487         if (IsMSVCCXX || IsCoreCLR)
1488           UnwindDests.back().first->setIsEHFuncletEntry();
1489         if (!IsSEH)
1490           UnwindDests.back().first->setIsEHScopeEntry();
1491       }
1492       NewEHPadBB = CatchSwitch->getUnwindDest();
1493     } else {
1494       continue;
1495     }
1496 
1497     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1498     if (BPI && NewEHPadBB)
1499       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1500     EHPadBB = NewEHPadBB;
1501   }
1502 }
1503 
1504 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1505   // Update successor info.
1506   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1507   auto UnwindDest = I.getUnwindDest();
1508   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1509   BranchProbability UnwindDestProb =
1510       (BPI && UnwindDest)
1511           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1512           : BranchProbability::getZero();
1513   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1514   for (auto &UnwindDest : UnwindDests) {
1515     UnwindDest.first->setIsEHPad();
1516     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1517   }
1518   FuncInfo.MBB->normalizeSuccProbs();
1519 
1520   // Create the terminator node.
1521   SDValue Ret =
1522       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1523   DAG.setRoot(Ret);
1524 }
1525 
1526 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1527   report_fatal_error("visitCatchSwitch not yet implemented!");
1528 }
1529 
1530 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1532   auto &DL = DAG.getDataLayout();
1533   SDValue Chain = getControlRoot();
1534   SmallVector<ISD::OutputArg, 8> Outs;
1535   SmallVector<SDValue, 8> OutVals;
1536 
1537   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1538   // lower
1539   //
1540   //   %val = call <ty> @llvm.experimental.deoptimize()
1541   //   ret <ty> %val
1542   //
1543   // differently.
1544   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1545     LowerDeoptimizingReturn();
1546     return;
1547   }
1548 
1549   if (!FuncInfo.CanLowerReturn) {
1550     unsigned DemoteReg = FuncInfo.DemoteRegister;
1551     const Function *F = I.getParent()->getParent();
1552 
1553     // Emit a store of the return value through the virtual register.
1554     // Leave Outs empty so that LowerReturn won't try to load return
1555     // registers the usual way.
1556     SmallVector<EVT, 1> PtrValueVTs;
1557     ComputeValueVTs(TLI, DL,
1558                     F->getReturnType()->getPointerTo(
1559                         DAG.getDataLayout().getAllocaAddrSpace()),
1560                     PtrValueVTs);
1561 
1562     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1563                                         DemoteReg, PtrValueVTs[0]);
1564     SDValue RetOp = getValue(I.getOperand(0));
1565 
1566     SmallVector<EVT, 4> ValueVTs;
1567     SmallVector<uint64_t, 4> Offsets;
1568     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1569     unsigned NumValues = ValueVTs.size();
1570 
1571     SmallVector<SDValue, 4> Chains(NumValues);
1572     for (unsigned i = 0; i != NumValues; ++i) {
1573       // An aggregate return value cannot wrap around the address space, so
1574       // offsets to its parts don't wrap either.
1575       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1576       Chains[i] = DAG.getStore(
1577           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1578           // FIXME: better loc info would be nice.
1579           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1580     }
1581 
1582     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1583                         MVT::Other, Chains);
1584   } else if (I.getNumOperands() != 0) {
1585     SmallVector<EVT, 4> ValueVTs;
1586     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1587     unsigned NumValues = ValueVTs.size();
1588     if (NumValues) {
1589       SDValue RetOp = getValue(I.getOperand(0));
1590 
1591       const Function *F = I.getParent()->getParent();
1592 
1593       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1594       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1595                                           Attribute::SExt))
1596         ExtendKind = ISD::SIGN_EXTEND;
1597       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1598                                                Attribute::ZExt))
1599         ExtendKind = ISD::ZERO_EXTEND;
1600 
1601       LLVMContext &Context = F->getContext();
1602       bool RetInReg = F->getAttributes().hasAttribute(
1603           AttributeList::ReturnIndex, Attribute::InReg);
1604 
1605       for (unsigned j = 0; j != NumValues; ++j) {
1606         EVT VT = ValueVTs[j];
1607 
1608         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1609           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1610 
1611         CallingConv::ID CC = F->getCallingConv();
1612 
1613         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1614         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1615         SmallVector<SDValue, 4> Parts(NumParts);
1616         getCopyToParts(DAG, getCurSDLoc(),
1617                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1618                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1619 
1620         // 'inreg' on function refers to return value
1621         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1622         if (RetInReg)
1623           Flags.setInReg();
1624 
1625         // Propagate extension type if any
1626         if (ExtendKind == ISD::SIGN_EXTEND)
1627           Flags.setSExt();
1628         else if (ExtendKind == ISD::ZERO_EXTEND)
1629           Flags.setZExt();
1630 
1631         for (unsigned i = 0; i < NumParts; ++i) {
1632           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1633                                         VT, /*isfixed=*/true, 0, 0));
1634           OutVals.push_back(Parts[i]);
1635         }
1636       }
1637     }
1638   }
1639 
1640   // Push in swifterror virtual register as the last element of Outs. This makes
1641   // sure swifterror virtual register will be returned in the swifterror
1642   // physical register.
1643   const Function *F = I.getParent()->getParent();
1644   if (TLI.supportSwiftError() &&
1645       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1646     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1647     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1648     Flags.setSwiftError();
1649     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1650                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1651                                   true /*isfixed*/, 1 /*origidx*/,
1652                                   0 /*partOffs*/));
1653     // Create SDNode for the swifterror virtual register.
1654     OutVals.push_back(
1655         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1656                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1657                         EVT(TLI.getPointerTy(DL))));
1658   }
1659 
1660   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1661   CallingConv::ID CallConv =
1662     DAG.getMachineFunction().getFunction().getCallingConv();
1663   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1664       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1665 
1666   // Verify that the target's LowerReturn behaved as expected.
1667   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1668          "LowerReturn didn't return a valid chain!");
1669 
1670   // Update the DAG with the new chain value resulting from return lowering.
1671   DAG.setRoot(Chain);
1672 }
1673 
1674 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1675 /// created for it, emit nodes to copy the value into the virtual
1676 /// registers.
1677 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1678   // Skip empty types
1679   if (V->getType()->isEmptyTy())
1680     return;
1681 
1682   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1683   if (VMI != FuncInfo.ValueMap.end()) {
1684     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1685     CopyValueToVirtualRegister(V, VMI->second);
1686   }
1687 }
1688 
1689 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1690 /// the current basic block, add it to ValueMap now so that we'll get a
1691 /// CopyTo/FromReg.
1692 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1693   // No need to export constants.
1694   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1695 
1696   // Already exported?
1697   if (FuncInfo.isExportedInst(V)) return;
1698 
1699   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1700   CopyValueToVirtualRegister(V, Reg);
1701 }
1702 
1703 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1704                                                      const BasicBlock *FromBB) {
1705   // The operands of the setcc have to be in this block.  We don't know
1706   // how to export them from some other block.
1707   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1708     // Can export from current BB.
1709     if (VI->getParent() == FromBB)
1710       return true;
1711 
1712     // Is already exported, noop.
1713     return FuncInfo.isExportedInst(V);
1714   }
1715 
1716   // If this is an argument, we can export it if the BB is the entry block or
1717   // if it is already exported.
1718   if (isa<Argument>(V)) {
1719     if (FromBB == &FromBB->getParent()->getEntryBlock())
1720       return true;
1721 
1722     // Otherwise, can only export this if it is already exported.
1723     return FuncInfo.isExportedInst(V);
1724   }
1725 
1726   // Otherwise, constants can always be exported.
1727   return true;
1728 }
1729 
1730 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1731 BranchProbability
1732 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1733                                         const MachineBasicBlock *Dst) const {
1734   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1735   const BasicBlock *SrcBB = Src->getBasicBlock();
1736   const BasicBlock *DstBB = Dst->getBasicBlock();
1737   if (!BPI) {
1738     // If BPI is not available, set the default probability as 1 / N, where N is
1739     // the number of successors.
1740     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1741     return BranchProbability(1, SuccSize);
1742   }
1743   return BPI->getEdgeProbability(SrcBB, DstBB);
1744 }
1745 
1746 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1747                                                MachineBasicBlock *Dst,
1748                                                BranchProbability Prob) {
1749   if (!FuncInfo.BPI)
1750     Src->addSuccessorWithoutProb(Dst);
1751   else {
1752     if (Prob.isUnknown())
1753       Prob = getEdgeProbability(Src, Dst);
1754     Src->addSuccessor(Dst, Prob);
1755   }
1756 }
1757 
1758 static bool InBlock(const Value *V, const BasicBlock *BB) {
1759   if (const Instruction *I = dyn_cast<Instruction>(V))
1760     return I->getParent() == BB;
1761   return true;
1762 }
1763 
1764 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1765 /// This function emits a branch and is used at the leaves of an OR or an
1766 /// AND operator tree.
1767 void
1768 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1769                                                   MachineBasicBlock *TBB,
1770                                                   MachineBasicBlock *FBB,
1771                                                   MachineBasicBlock *CurBB,
1772                                                   MachineBasicBlock *SwitchBB,
1773                                                   BranchProbability TProb,
1774                                                   BranchProbability FProb,
1775                                                   bool InvertCond) {
1776   const BasicBlock *BB = CurBB->getBasicBlock();
1777 
1778   // If the leaf of the tree is a comparison, merge the condition into
1779   // the caseblock.
1780   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1781     // The operands of the cmp have to be in this block.  We don't know
1782     // how to export them from some other block.  If this is the first block
1783     // of the sequence, no exporting is needed.
1784     if (CurBB == SwitchBB ||
1785         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1786          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1787       ISD::CondCode Condition;
1788       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1789         ICmpInst::Predicate Pred =
1790             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1791         Condition = getICmpCondCode(Pred);
1792       } else {
1793         const FCmpInst *FC = cast<FCmpInst>(Cond);
1794         FCmpInst::Predicate Pred =
1795             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1796         Condition = getFCmpCondCode(Pred);
1797         if (TM.Options.NoNaNsFPMath)
1798           Condition = getFCmpCodeWithoutNaN(Condition);
1799       }
1800 
1801       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1802                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1803       SwitchCases.push_back(CB);
1804       return;
1805     }
1806   }
1807 
1808   // Create a CaseBlock record representing this branch.
1809   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1810   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1811                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1812   SwitchCases.push_back(CB);
1813 }
1814 
1815 /// FindMergedConditions - If Cond is an expression like
1816 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1817                                                MachineBasicBlock *TBB,
1818                                                MachineBasicBlock *FBB,
1819                                                MachineBasicBlock *CurBB,
1820                                                MachineBasicBlock *SwitchBB,
1821                                                Instruction::BinaryOps Opc,
1822                                                BranchProbability TProb,
1823                                                BranchProbability FProb,
1824                                                bool InvertCond) {
1825   // Skip over not part of the tree and remember to invert op and operands at
1826   // next level.
1827   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1828     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1829     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1830       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1831                            !InvertCond);
1832       return;
1833     }
1834   }
1835 
1836   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1837   // Compute the effective opcode for Cond, taking into account whether it needs
1838   // to be inverted, e.g.
1839   //   and (not (or A, B)), C
1840   // gets lowered as
1841   //   and (and (not A, not B), C)
1842   unsigned BOpc = 0;
1843   if (BOp) {
1844     BOpc = BOp->getOpcode();
1845     if (InvertCond) {
1846       if (BOpc == Instruction::And)
1847         BOpc = Instruction::Or;
1848       else if (BOpc == Instruction::Or)
1849         BOpc = Instruction::And;
1850     }
1851   }
1852 
1853   // If this node is not part of the or/and tree, emit it as a branch.
1854   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1855       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1856       BOp->getParent() != CurBB->getBasicBlock() ||
1857       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1858       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1859     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1860                                  TProb, FProb, InvertCond);
1861     return;
1862   }
1863 
1864   //  Create TmpBB after CurBB.
1865   MachineFunction::iterator BBI(CurBB);
1866   MachineFunction &MF = DAG.getMachineFunction();
1867   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1868   CurBB->getParent()->insert(++BBI, TmpBB);
1869 
1870   if (Opc == Instruction::Or) {
1871     // Codegen X | Y as:
1872     // BB1:
1873     //   jmp_if_X TBB
1874     //   jmp TmpBB
1875     // TmpBB:
1876     //   jmp_if_Y TBB
1877     //   jmp FBB
1878     //
1879 
1880     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1881     // The requirement is that
1882     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1883     //     = TrueProb for original BB.
1884     // Assuming the original probabilities are A and B, one choice is to set
1885     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1886     // A/(1+B) and 2B/(1+B). This choice assumes that
1887     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1888     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1889     // TmpBB, but the math is more complicated.
1890 
1891     auto NewTrueProb = TProb / 2;
1892     auto NewFalseProb = TProb / 2 + FProb;
1893     // Emit the LHS condition.
1894     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1895                          NewTrueProb, NewFalseProb, InvertCond);
1896 
1897     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1898     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1899     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1900     // Emit the RHS condition into TmpBB.
1901     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1902                          Probs[0], Probs[1], InvertCond);
1903   } else {
1904     assert(Opc == Instruction::And && "Unknown merge op!");
1905     // Codegen X & Y as:
1906     // BB1:
1907     //   jmp_if_X TmpBB
1908     //   jmp FBB
1909     // TmpBB:
1910     //   jmp_if_Y TBB
1911     //   jmp FBB
1912     //
1913     //  This requires creation of TmpBB after CurBB.
1914 
1915     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1916     // The requirement is that
1917     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1918     //     = FalseProb for original BB.
1919     // Assuming the original probabilities are A and B, one choice is to set
1920     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1921     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1922     // TrueProb for BB1 * FalseProb for TmpBB.
1923 
1924     auto NewTrueProb = TProb + FProb / 2;
1925     auto NewFalseProb = FProb / 2;
1926     // Emit the LHS condition.
1927     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1928                          NewTrueProb, NewFalseProb, InvertCond);
1929 
1930     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1931     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1932     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1933     // Emit the RHS condition into TmpBB.
1934     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1935                          Probs[0], Probs[1], InvertCond);
1936   }
1937 }
1938 
1939 /// If the set of cases should be emitted as a series of branches, return true.
1940 /// If we should emit this as a bunch of and/or'd together conditions, return
1941 /// false.
1942 bool
1943 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1944   if (Cases.size() != 2) return true;
1945 
1946   // If this is two comparisons of the same values or'd or and'd together, they
1947   // will get folded into a single comparison, so don't emit two blocks.
1948   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1949        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1950       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1951        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1952     return false;
1953   }
1954 
1955   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1956   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1957   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1958       Cases[0].CC == Cases[1].CC &&
1959       isa<Constant>(Cases[0].CmpRHS) &&
1960       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1961     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1962       return false;
1963     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1964       return false;
1965   }
1966 
1967   return true;
1968 }
1969 
1970 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1971   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1972 
1973   // Update machine-CFG edges.
1974   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1975 
1976   if (I.isUnconditional()) {
1977     // Update machine-CFG edges.
1978     BrMBB->addSuccessor(Succ0MBB);
1979 
1980     // If this is not a fall-through branch or optimizations are switched off,
1981     // emit the branch.
1982     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1983       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1984                               MVT::Other, getControlRoot(),
1985                               DAG.getBasicBlock(Succ0MBB)));
1986 
1987     return;
1988   }
1989 
1990   // If this condition is one of the special cases we handle, do special stuff
1991   // now.
1992   const Value *CondVal = I.getCondition();
1993   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1994 
1995   // If this is a series of conditions that are or'd or and'd together, emit
1996   // this as a sequence of branches instead of setcc's with and/or operations.
1997   // As long as jumps are not expensive, this should improve performance.
1998   // For example, instead of something like:
1999   //     cmp A, B
2000   //     C = seteq
2001   //     cmp D, E
2002   //     F = setle
2003   //     or C, F
2004   //     jnz foo
2005   // Emit:
2006   //     cmp A, B
2007   //     je foo
2008   //     cmp D, E
2009   //     jle foo
2010   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2011     Instruction::BinaryOps Opcode = BOp->getOpcode();
2012     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2013         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2014         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2015       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2016                            Opcode,
2017                            getEdgeProbability(BrMBB, Succ0MBB),
2018                            getEdgeProbability(BrMBB, Succ1MBB),
2019                            /*InvertCond=*/false);
2020       // If the compares in later blocks need to use values not currently
2021       // exported from this block, export them now.  This block should always
2022       // be the first entry.
2023       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2024 
2025       // Allow some cases to be rejected.
2026       if (ShouldEmitAsBranches(SwitchCases)) {
2027         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2028           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2029           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2030         }
2031 
2032         // Emit the branch for this block.
2033         visitSwitchCase(SwitchCases[0], BrMBB);
2034         SwitchCases.erase(SwitchCases.begin());
2035         return;
2036       }
2037 
2038       // Okay, we decided not to do this, remove any inserted MBB's and clear
2039       // SwitchCases.
2040       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2041         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2042 
2043       SwitchCases.clear();
2044     }
2045   }
2046 
2047   // Create a CaseBlock record representing this branch.
2048   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2049                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2050 
2051   // Use visitSwitchCase to actually insert the fast branch sequence for this
2052   // cond branch.
2053   visitSwitchCase(CB, BrMBB);
2054 }
2055 
2056 /// visitSwitchCase - Emits the necessary code to represent a single node in
2057 /// the binary search tree resulting from lowering a switch instruction.
2058 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2059                                           MachineBasicBlock *SwitchBB) {
2060   SDValue Cond;
2061   SDValue CondLHS = getValue(CB.CmpLHS);
2062   SDLoc dl = CB.DL;
2063 
2064   // Build the setcc now.
2065   if (!CB.CmpMHS) {
2066     // Fold "(X == true)" to X and "(X == false)" to !X to
2067     // handle common cases produced by branch lowering.
2068     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2069         CB.CC == ISD::SETEQ)
2070       Cond = CondLHS;
2071     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2072              CB.CC == ISD::SETEQ) {
2073       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2074       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2075     } else
2076       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2077   } else {
2078     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2079 
2080     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2081     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2082 
2083     SDValue CmpOp = getValue(CB.CmpMHS);
2084     EVT VT = CmpOp.getValueType();
2085 
2086     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2087       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2088                           ISD::SETLE);
2089     } else {
2090       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2091                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2092       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2093                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2094     }
2095   }
2096 
2097   // Update successor info
2098   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2099   // TrueBB and FalseBB are always different unless the incoming IR is
2100   // degenerate. This only happens when running llc on weird IR.
2101   if (CB.TrueBB != CB.FalseBB)
2102     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2103   SwitchBB->normalizeSuccProbs();
2104 
2105   // If the lhs block is the next block, invert the condition so that we can
2106   // fall through to the lhs instead of the rhs block.
2107   if (CB.TrueBB == NextBlock(SwitchBB)) {
2108     std::swap(CB.TrueBB, CB.FalseBB);
2109     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2110     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2111   }
2112 
2113   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2114                                MVT::Other, getControlRoot(), Cond,
2115                                DAG.getBasicBlock(CB.TrueBB));
2116 
2117   // Insert the false branch. Do this even if it's a fall through branch,
2118   // this makes it easier to do DAG optimizations which require inverting
2119   // the branch condition.
2120   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2121                        DAG.getBasicBlock(CB.FalseBB));
2122 
2123   DAG.setRoot(BrCond);
2124 }
2125 
2126 /// visitJumpTable - Emit JumpTable node in the current MBB
2127 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2128   // Emit the code for the jump table
2129   assert(JT.Reg != -1U && "Should lower JT Header first!");
2130   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2131   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2132                                      JT.Reg, PTy);
2133   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2134   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2135                                     MVT::Other, Index.getValue(1),
2136                                     Table, Index);
2137   DAG.setRoot(BrJumpTable);
2138 }
2139 
2140 /// visitJumpTableHeader - This function emits necessary code to produce index
2141 /// in the JumpTable from switch case.
2142 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2143                                                JumpTableHeader &JTH,
2144                                                MachineBasicBlock *SwitchBB) {
2145   SDLoc dl = getCurSDLoc();
2146 
2147   // Subtract the lowest switch case value from the value being switched on and
2148   // conditional branch to default mbb if the result is greater than the
2149   // difference between smallest and largest cases.
2150   SDValue SwitchOp = getValue(JTH.SValue);
2151   EVT VT = SwitchOp.getValueType();
2152   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2153                             DAG.getConstant(JTH.First, dl, VT));
2154 
2155   // The SDNode we just created, which holds the value being switched on minus
2156   // the smallest case value, needs to be copied to a virtual register so it
2157   // can be used as an index into the jump table in a subsequent basic block.
2158   // This value may be smaller or larger than the target's pointer type, and
2159   // therefore require extension or truncating.
2160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2161   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2162 
2163   unsigned JumpTableReg =
2164       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2165   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2166                                     JumpTableReg, SwitchOp);
2167   JT.Reg = JumpTableReg;
2168 
2169   // Emit the range check for the jump table, and branch to the default block
2170   // for the switch statement if the value being switched on exceeds the largest
2171   // case in the switch.
2172   SDValue CMP = DAG.getSetCC(
2173       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2174                                  Sub.getValueType()),
2175       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2176 
2177   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2178                                MVT::Other, CopyTo, CMP,
2179                                DAG.getBasicBlock(JT.Default));
2180 
2181   // Avoid emitting unnecessary branches to the next block.
2182   if (JT.MBB != NextBlock(SwitchBB))
2183     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2184                          DAG.getBasicBlock(JT.MBB));
2185 
2186   DAG.setRoot(BrCond);
2187 }
2188 
2189 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2190 /// variable if there exists one.
2191 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2192                                  SDValue &Chain) {
2193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2194   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2195   MachineFunction &MF = DAG.getMachineFunction();
2196   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2197   MachineSDNode *Node =
2198       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2199   if (Global) {
2200     MachinePointerInfo MPInfo(Global);
2201     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2202                  MachineMemOperand::MODereferenceable;
2203     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2204         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2205     DAG.setNodeMemRefs(Node, {MemRef});
2206   }
2207   return SDValue(Node, 0);
2208 }
2209 
2210 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2211 /// tail spliced into a stack protector check success bb.
2212 ///
2213 /// For a high level explanation of how this fits into the stack protector
2214 /// generation see the comment on the declaration of class
2215 /// StackProtectorDescriptor.
2216 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2217                                                   MachineBasicBlock *ParentBB) {
2218 
2219   // First create the loads to the guard/stack slot for the comparison.
2220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2221   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2222 
2223   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2224   int FI = MFI.getStackProtectorIndex();
2225 
2226   SDValue Guard;
2227   SDLoc dl = getCurSDLoc();
2228   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2229   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2230   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2231 
2232   // Generate code to load the content of the guard slot.
2233   SDValue GuardVal = DAG.getLoad(
2234       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2235       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2236       MachineMemOperand::MOVolatile);
2237 
2238   if (TLI.useStackGuardXorFP())
2239     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2240 
2241   // Retrieve guard check function, nullptr if instrumentation is inlined.
2242   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2243     // The target provides a guard check function to validate the guard value.
2244     // Generate a call to that function with the content of the guard slot as
2245     // argument.
2246     auto *Fn = cast<Function>(GuardCheck);
2247     FunctionType *FnTy = Fn->getFunctionType();
2248     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2249 
2250     TargetLowering::ArgListTy Args;
2251     TargetLowering::ArgListEntry Entry;
2252     Entry.Node = GuardVal;
2253     Entry.Ty = FnTy->getParamType(0);
2254     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2255       Entry.IsInReg = true;
2256     Args.push_back(Entry);
2257 
2258     TargetLowering::CallLoweringInfo CLI(DAG);
2259     CLI.setDebugLoc(getCurSDLoc())
2260       .setChain(DAG.getEntryNode())
2261       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2262                  getValue(GuardCheck), std::move(Args));
2263 
2264     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2265     DAG.setRoot(Result.second);
2266     return;
2267   }
2268 
2269   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2270   // Otherwise, emit a volatile load to retrieve the stack guard value.
2271   SDValue Chain = DAG.getEntryNode();
2272   if (TLI.useLoadStackGuardNode()) {
2273     Guard = getLoadStackGuard(DAG, dl, Chain);
2274   } else {
2275     const Value *IRGuard = TLI.getSDagStackGuard(M);
2276     SDValue GuardPtr = getValue(IRGuard);
2277 
2278     Guard =
2279         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2280                     Align, MachineMemOperand::MOVolatile);
2281   }
2282 
2283   // Perform the comparison via a subtract/getsetcc.
2284   EVT VT = Guard.getValueType();
2285   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2286 
2287   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2288                                                         *DAG.getContext(),
2289                                                         Sub.getValueType()),
2290                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2291 
2292   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2293   // branch to failure MBB.
2294   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2295                                MVT::Other, GuardVal.getOperand(0),
2296                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2297   // Otherwise branch to success MBB.
2298   SDValue Br = DAG.getNode(ISD::BR, dl,
2299                            MVT::Other, BrCond,
2300                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2301 
2302   DAG.setRoot(Br);
2303 }
2304 
2305 /// Codegen the failure basic block for a stack protector check.
2306 ///
2307 /// A failure stack protector machine basic block consists simply of a call to
2308 /// __stack_chk_fail().
2309 ///
2310 /// For a high level explanation of how this fits into the stack protector
2311 /// generation see the comment on the declaration of class
2312 /// StackProtectorDescriptor.
2313 void
2314 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2316   SDValue Chain =
2317       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2318                       None, false, getCurSDLoc(), false, false).second;
2319   DAG.setRoot(Chain);
2320 }
2321 
2322 /// visitBitTestHeader - This function emits necessary code to produce value
2323 /// suitable for "bit tests"
2324 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2325                                              MachineBasicBlock *SwitchBB) {
2326   SDLoc dl = getCurSDLoc();
2327 
2328   // Subtract the minimum value
2329   SDValue SwitchOp = getValue(B.SValue);
2330   EVT VT = SwitchOp.getValueType();
2331   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2332                             DAG.getConstant(B.First, dl, VT));
2333 
2334   // Check range
2335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2336   SDValue RangeCmp = DAG.getSetCC(
2337       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2338                                  Sub.getValueType()),
2339       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2340 
2341   // Determine the type of the test operands.
2342   bool UsePtrType = false;
2343   if (!TLI.isTypeLegal(VT))
2344     UsePtrType = true;
2345   else {
2346     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2347       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2348         // Switch table case range are encoded into series of masks.
2349         // Just use pointer type, it's guaranteed to fit.
2350         UsePtrType = true;
2351         break;
2352       }
2353   }
2354   if (UsePtrType) {
2355     VT = TLI.getPointerTy(DAG.getDataLayout());
2356     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2357   }
2358 
2359   B.RegVT = VT.getSimpleVT();
2360   B.Reg = FuncInfo.CreateReg(B.RegVT);
2361   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2362 
2363   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2364 
2365   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2366   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2367   SwitchBB->normalizeSuccProbs();
2368 
2369   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2370                                 MVT::Other, CopyTo, RangeCmp,
2371                                 DAG.getBasicBlock(B.Default));
2372 
2373   // Avoid emitting unnecessary branches to the next block.
2374   if (MBB != NextBlock(SwitchBB))
2375     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2376                           DAG.getBasicBlock(MBB));
2377 
2378   DAG.setRoot(BrRange);
2379 }
2380 
2381 /// visitBitTestCase - this function produces one "bit test"
2382 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2383                                            MachineBasicBlock* NextMBB,
2384                                            BranchProbability BranchProbToNext,
2385                                            unsigned Reg,
2386                                            BitTestCase &B,
2387                                            MachineBasicBlock *SwitchBB) {
2388   SDLoc dl = getCurSDLoc();
2389   MVT VT = BB.RegVT;
2390   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2391   SDValue Cmp;
2392   unsigned PopCount = countPopulation(B.Mask);
2393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2394   if (PopCount == 1) {
2395     // Testing for a single bit; just compare the shift count with what it
2396     // would need to be to shift a 1 bit in that position.
2397     Cmp = DAG.getSetCC(
2398         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2399         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2400         ISD::SETEQ);
2401   } else if (PopCount == BB.Range) {
2402     // There is only one zero bit in the range, test for it directly.
2403     Cmp = DAG.getSetCC(
2404         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2405         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2406         ISD::SETNE);
2407   } else {
2408     // Make desired shift
2409     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2410                                     DAG.getConstant(1, dl, VT), ShiftOp);
2411 
2412     // Emit bit tests and jumps
2413     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2414                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2415     Cmp = DAG.getSetCC(
2416         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2417         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2418   }
2419 
2420   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2421   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2422   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2423   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2424   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2425   // one as they are relative probabilities (and thus work more like weights),
2426   // and hence we need to normalize them to let the sum of them become one.
2427   SwitchBB->normalizeSuccProbs();
2428 
2429   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2430                               MVT::Other, getControlRoot(),
2431                               Cmp, DAG.getBasicBlock(B.TargetBB));
2432 
2433   // Avoid emitting unnecessary branches to the next block.
2434   if (NextMBB != NextBlock(SwitchBB))
2435     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2436                         DAG.getBasicBlock(NextMBB));
2437 
2438   DAG.setRoot(BrAnd);
2439 }
2440 
2441 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2442   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2443 
2444   // Retrieve successors. Look through artificial IR level blocks like
2445   // catchswitch for successors.
2446   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2447   const BasicBlock *EHPadBB = I.getSuccessor(1);
2448 
2449   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2450   // have to do anything here to lower funclet bundles.
2451   assert(!I.hasOperandBundlesOtherThan(
2452              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2453          "Cannot lower invokes with arbitrary operand bundles yet!");
2454 
2455   const Value *Callee(I.getCalledValue());
2456   const Function *Fn = dyn_cast<Function>(Callee);
2457   if (isa<InlineAsm>(Callee))
2458     visitInlineAsm(&I);
2459   else if (Fn && Fn->isIntrinsic()) {
2460     switch (Fn->getIntrinsicID()) {
2461     default:
2462       llvm_unreachable("Cannot invoke this intrinsic");
2463     case Intrinsic::donothing:
2464       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2465       break;
2466     case Intrinsic::experimental_patchpoint_void:
2467     case Intrinsic::experimental_patchpoint_i64:
2468       visitPatchpoint(&I, EHPadBB);
2469       break;
2470     case Intrinsic::experimental_gc_statepoint:
2471       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2472       break;
2473     }
2474   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2475     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2476     // Eventually we will support lowering the @llvm.experimental.deoptimize
2477     // intrinsic, and right now there are no plans to support other intrinsics
2478     // with deopt state.
2479     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2480   } else {
2481     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2482   }
2483 
2484   // If the value of the invoke is used outside of its defining block, make it
2485   // available as a virtual register.
2486   // We already took care of the exported value for the statepoint instruction
2487   // during call to the LowerStatepoint.
2488   if (!isStatepoint(I)) {
2489     CopyToExportRegsIfNeeded(&I);
2490   }
2491 
2492   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2493   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2494   BranchProbability EHPadBBProb =
2495       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2496           : BranchProbability::getZero();
2497   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2498 
2499   // Update successor info.
2500   addSuccessorWithProb(InvokeMBB, Return);
2501   for (auto &UnwindDest : UnwindDests) {
2502     UnwindDest.first->setIsEHPad();
2503     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2504   }
2505   InvokeMBB->normalizeSuccProbs();
2506 
2507   // Drop into normal successor.
2508   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2509                           MVT::Other, getControlRoot(),
2510                           DAG.getBasicBlock(Return)));
2511 }
2512 
2513 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2514   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2515 }
2516 
2517 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2518   assert(FuncInfo.MBB->isEHPad() &&
2519          "Call to landingpad not in landing pad!");
2520 
2521   MachineBasicBlock *MBB = FuncInfo.MBB;
2522   addLandingPadInfo(LP, *MBB);
2523 
2524   // If there aren't registers to copy the values into (e.g., during SjLj
2525   // exceptions), then don't bother to create these DAG nodes.
2526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2527   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2528   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2529       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2530     return;
2531 
2532   // If landingpad's return type is token type, we don't create DAG nodes
2533   // for its exception pointer and selector value. The extraction of exception
2534   // pointer or selector value from token type landingpads is not currently
2535   // supported.
2536   if (LP.getType()->isTokenTy())
2537     return;
2538 
2539   SmallVector<EVT, 2> ValueVTs;
2540   SDLoc dl = getCurSDLoc();
2541   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2542   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2543 
2544   // Get the two live-in registers as SDValues. The physregs have already been
2545   // copied into virtual registers.
2546   SDValue Ops[2];
2547   if (FuncInfo.ExceptionPointerVirtReg) {
2548     Ops[0] = DAG.getZExtOrTrunc(
2549         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2550                            FuncInfo.ExceptionPointerVirtReg,
2551                            TLI.getPointerTy(DAG.getDataLayout())),
2552         dl, ValueVTs[0]);
2553   } else {
2554     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2555   }
2556   Ops[1] = DAG.getZExtOrTrunc(
2557       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2558                          FuncInfo.ExceptionSelectorVirtReg,
2559                          TLI.getPointerTy(DAG.getDataLayout())),
2560       dl, ValueVTs[1]);
2561 
2562   // Merge into one.
2563   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2564                             DAG.getVTList(ValueVTs), Ops);
2565   setValue(&LP, Res);
2566 }
2567 
2568 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2569 #ifndef NDEBUG
2570   for (const CaseCluster &CC : Clusters)
2571     assert(CC.Low == CC.High && "Input clusters must be single-case");
2572 #endif
2573 
2574   llvm::sort(Clusters.begin(), Clusters.end(),
2575              [](const CaseCluster &a, const CaseCluster &b) {
2576     return a.Low->getValue().slt(b.Low->getValue());
2577   });
2578 
2579   // Merge adjacent clusters with the same destination.
2580   const unsigned N = Clusters.size();
2581   unsigned DstIndex = 0;
2582   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2583     CaseCluster &CC = Clusters[SrcIndex];
2584     const ConstantInt *CaseVal = CC.Low;
2585     MachineBasicBlock *Succ = CC.MBB;
2586 
2587     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2588         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2589       // If this case has the same successor and is a neighbour, merge it into
2590       // the previous cluster.
2591       Clusters[DstIndex - 1].High = CaseVal;
2592       Clusters[DstIndex - 1].Prob += CC.Prob;
2593     } else {
2594       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2595                    sizeof(Clusters[SrcIndex]));
2596     }
2597   }
2598   Clusters.resize(DstIndex);
2599 }
2600 
2601 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2602                                            MachineBasicBlock *Last) {
2603   // Update JTCases.
2604   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2605     if (JTCases[i].first.HeaderBB == First)
2606       JTCases[i].first.HeaderBB = Last;
2607 
2608   // Update BitTestCases.
2609   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2610     if (BitTestCases[i].Parent == First)
2611       BitTestCases[i].Parent = Last;
2612 }
2613 
2614 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2615   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2616 
2617   // Update machine-CFG edges with unique successors.
2618   SmallSet<BasicBlock*, 32> Done;
2619   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2620     BasicBlock *BB = I.getSuccessor(i);
2621     bool Inserted = Done.insert(BB).second;
2622     if (!Inserted)
2623         continue;
2624 
2625     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2626     addSuccessorWithProb(IndirectBrMBB, Succ);
2627   }
2628   IndirectBrMBB->normalizeSuccProbs();
2629 
2630   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2631                           MVT::Other, getControlRoot(),
2632                           getValue(I.getAddress())));
2633 }
2634 
2635 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2636   if (!DAG.getTarget().Options.TrapUnreachable)
2637     return;
2638 
2639   // We may be able to ignore unreachable behind a noreturn call.
2640   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2641     const BasicBlock &BB = *I.getParent();
2642     if (&I != &BB.front()) {
2643       BasicBlock::const_iterator PredI =
2644         std::prev(BasicBlock::const_iterator(&I));
2645       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2646         if (Call->doesNotReturn())
2647           return;
2648       }
2649     }
2650   }
2651 
2652   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2653 }
2654 
2655 void SelectionDAGBuilder::visitFSub(const User &I) {
2656   // -0.0 - X --> fneg
2657   Type *Ty = I.getType();
2658   if (isa<Constant>(I.getOperand(0)) &&
2659       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2660     SDValue Op2 = getValue(I.getOperand(1));
2661     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2662                              Op2.getValueType(), Op2));
2663     return;
2664   }
2665 
2666   visitBinary(I, ISD::FSUB);
2667 }
2668 
2669 /// Checks if the given instruction performs a vector reduction, in which case
2670 /// we have the freedom to alter the elements in the result as long as the
2671 /// reduction of them stays unchanged.
2672 static bool isVectorReductionOp(const User *I) {
2673   const Instruction *Inst = dyn_cast<Instruction>(I);
2674   if (!Inst || !Inst->getType()->isVectorTy())
2675     return false;
2676 
2677   auto OpCode = Inst->getOpcode();
2678   switch (OpCode) {
2679   case Instruction::Add:
2680   case Instruction::Mul:
2681   case Instruction::And:
2682   case Instruction::Or:
2683   case Instruction::Xor:
2684     break;
2685   case Instruction::FAdd:
2686   case Instruction::FMul:
2687     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2688       if (FPOp->getFastMathFlags().isFast())
2689         break;
2690     LLVM_FALLTHROUGH;
2691   default:
2692     return false;
2693   }
2694 
2695   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2696   // Ensure the reduction size is a power of 2.
2697   if (!isPowerOf2_32(ElemNum))
2698     return false;
2699 
2700   unsigned ElemNumToReduce = ElemNum;
2701 
2702   // Do DFS search on the def-use chain from the given instruction. We only
2703   // allow four kinds of operations during the search until we reach the
2704   // instruction that extracts the first element from the vector:
2705   //
2706   //   1. The reduction operation of the same opcode as the given instruction.
2707   //
2708   //   2. PHI node.
2709   //
2710   //   3. ShuffleVector instruction together with a reduction operation that
2711   //      does a partial reduction.
2712   //
2713   //   4. ExtractElement that extracts the first element from the vector, and we
2714   //      stop searching the def-use chain here.
2715   //
2716   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2717   // from 1-3 to the stack to continue the DFS. The given instruction is not
2718   // a reduction operation if we meet any other instructions other than those
2719   // listed above.
2720 
2721   SmallVector<const User *, 16> UsersToVisit{Inst};
2722   SmallPtrSet<const User *, 16> Visited;
2723   bool ReduxExtracted = false;
2724 
2725   while (!UsersToVisit.empty()) {
2726     auto User = UsersToVisit.back();
2727     UsersToVisit.pop_back();
2728     if (!Visited.insert(User).second)
2729       continue;
2730 
2731     for (const auto &U : User->users()) {
2732       auto Inst = dyn_cast<Instruction>(U);
2733       if (!Inst)
2734         return false;
2735 
2736       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2737         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2738           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2739             return false;
2740         UsersToVisit.push_back(U);
2741       } else if (const ShuffleVectorInst *ShufInst =
2742                      dyn_cast<ShuffleVectorInst>(U)) {
2743         // Detect the following pattern: A ShuffleVector instruction together
2744         // with a reduction that do partial reduction on the first and second
2745         // ElemNumToReduce / 2 elements, and store the result in
2746         // ElemNumToReduce / 2 elements in another vector.
2747 
2748         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2749         if (ResultElements < ElemNum)
2750           return false;
2751 
2752         if (ElemNumToReduce == 1)
2753           return false;
2754         if (!isa<UndefValue>(U->getOperand(1)))
2755           return false;
2756         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2757           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2758             return false;
2759         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2760           if (ShufInst->getMaskValue(i) != -1)
2761             return false;
2762 
2763         // There is only one user of this ShuffleVector instruction, which
2764         // must be a reduction operation.
2765         if (!U->hasOneUse())
2766           return false;
2767 
2768         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2769         if (!U2 || U2->getOpcode() != OpCode)
2770           return false;
2771 
2772         // Check operands of the reduction operation.
2773         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2774             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2775           UsersToVisit.push_back(U2);
2776           ElemNumToReduce /= 2;
2777         } else
2778           return false;
2779       } else if (isa<ExtractElementInst>(U)) {
2780         // At this moment we should have reduced all elements in the vector.
2781         if (ElemNumToReduce != 1)
2782           return false;
2783 
2784         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2785         if (!Val || !Val->isZero())
2786           return false;
2787 
2788         ReduxExtracted = true;
2789       } else
2790         return false;
2791     }
2792   }
2793   return ReduxExtracted;
2794 }
2795 
2796 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2797   SDNodeFlags Flags;
2798   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2799     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2800     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2801   }
2802   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2803     Flags.setExact(ExactOp->isExact());
2804   }
2805   if (isVectorReductionOp(&I)) {
2806     Flags.setVectorReduction(true);
2807     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2808   }
2809 
2810   SDValue Op1 = getValue(I.getOperand(0));
2811   SDValue Op2 = getValue(I.getOperand(1));
2812   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2813                                      Op1, Op2, Flags);
2814   setValue(&I, BinNodeValue);
2815 }
2816 
2817 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2818   SDValue Op1 = getValue(I.getOperand(0));
2819   SDValue Op2 = getValue(I.getOperand(1));
2820 
2821   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2822       Op2.getValueType(), DAG.getDataLayout());
2823 
2824   // Coerce the shift amount to the right type if we can.
2825   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2826     unsigned ShiftSize = ShiftTy.getSizeInBits();
2827     unsigned Op2Size = Op2.getValueSizeInBits();
2828     SDLoc DL = getCurSDLoc();
2829 
2830     // If the operand is smaller than the shift count type, promote it.
2831     if (ShiftSize > Op2Size)
2832       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2833 
2834     // If the operand is larger than the shift count type but the shift
2835     // count type has enough bits to represent any shift value, truncate
2836     // it now. This is a common case and it exposes the truncate to
2837     // optimization early.
2838     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2839       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2840     // Otherwise we'll need to temporarily settle for some other convenient
2841     // type.  Type legalization will make adjustments once the shiftee is split.
2842     else
2843       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2844   }
2845 
2846   bool nuw = false;
2847   bool nsw = false;
2848   bool exact = false;
2849 
2850   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2851 
2852     if (const OverflowingBinaryOperator *OFBinOp =
2853             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2854       nuw = OFBinOp->hasNoUnsignedWrap();
2855       nsw = OFBinOp->hasNoSignedWrap();
2856     }
2857     if (const PossiblyExactOperator *ExactOp =
2858             dyn_cast<const PossiblyExactOperator>(&I))
2859       exact = ExactOp->isExact();
2860   }
2861   SDNodeFlags Flags;
2862   Flags.setExact(exact);
2863   Flags.setNoSignedWrap(nsw);
2864   Flags.setNoUnsignedWrap(nuw);
2865   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2866                             Flags);
2867   setValue(&I, Res);
2868 }
2869 
2870 void SelectionDAGBuilder::visitSDiv(const User &I) {
2871   SDValue Op1 = getValue(I.getOperand(0));
2872   SDValue Op2 = getValue(I.getOperand(1));
2873 
2874   SDNodeFlags Flags;
2875   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2876                  cast<PossiblyExactOperator>(&I)->isExact());
2877   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2878                            Op2, Flags));
2879 }
2880 
2881 void SelectionDAGBuilder::visitICmp(const User &I) {
2882   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2883   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2884     predicate = IC->getPredicate();
2885   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2886     predicate = ICmpInst::Predicate(IC->getPredicate());
2887   SDValue Op1 = getValue(I.getOperand(0));
2888   SDValue Op2 = getValue(I.getOperand(1));
2889   ISD::CondCode Opcode = getICmpCondCode(predicate);
2890 
2891   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2892                                                         I.getType());
2893   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2894 }
2895 
2896 void SelectionDAGBuilder::visitFCmp(const User &I) {
2897   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2898   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2899     predicate = FC->getPredicate();
2900   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2901     predicate = FCmpInst::Predicate(FC->getPredicate());
2902   SDValue Op1 = getValue(I.getOperand(0));
2903   SDValue Op2 = getValue(I.getOperand(1));
2904 
2905   ISD::CondCode Condition = getFCmpCondCode(predicate);
2906   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2907   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2908     Condition = getFCmpCodeWithoutNaN(Condition);
2909 
2910   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2911                                                         I.getType());
2912   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2913 }
2914 
2915 // Check if the condition of the select has one use or two users that are both
2916 // selects with the same condition.
2917 static bool hasOnlySelectUsers(const Value *Cond) {
2918   return llvm::all_of(Cond->users(), [](const Value *V) {
2919     return isa<SelectInst>(V);
2920   });
2921 }
2922 
2923 void SelectionDAGBuilder::visitSelect(const User &I) {
2924   SmallVector<EVT, 4> ValueVTs;
2925   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2926                   ValueVTs);
2927   unsigned NumValues = ValueVTs.size();
2928   if (NumValues == 0) return;
2929 
2930   SmallVector<SDValue, 4> Values(NumValues);
2931   SDValue Cond     = getValue(I.getOperand(0));
2932   SDValue LHSVal   = getValue(I.getOperand(1));
2933   SDValue RHSVal   = getValue(I.getOperand(2));
2934   auto BaseOps = {Cond};
2935   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2936     ISD::VSELECT : ISD::SELECT;
2937 
2938   // Min/max matching is only viable if all output VTs are the same.
2939   if (is_splat(ValueVTs)) {
2940     EVT VT = ValueVTs[0];
2941     LLVMContext &Ctx = *DAG.getContext();
2942     auto &TLI = DAG.getTargetLoweringInfo();
2943 
2944     // We care about the legality of the operation after it has been type
2945     // legalized.
2946     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2947            VT != TLI.getTypeToTransformTo(Ctx, VT))
2948       VT = TLI.getTypeToTransformTo(Ctx, VT);
2949 
2950     // If the vselect is legal, assume we want to leave this as a vector setcc +
2951     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2952     // min/max is legal on the scalar type.
2953     bool UseScalarMinMax = VT.isVector() &&
2954       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2955 
2956     Value *LHS, *RHS;
2957     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2958     ISD::NodeType Opc = ISD::DELETED_NODE;
2959     switch (SPR.Flavor) {
2960     case SPF_UMAX:    Opc = ISD::UMAX; break;
2961     case SPF_UMIN:    Opc = ISD::UMIN; break;
2962     case SPF_SMAX:    Opc = ISD::SMAX; break;
2963     case SPF_SMIN:    Opc = ISD::SMIN; break;
2964     case SPF_FMINNUM:
2965       switch (SPR.NaNBehavior) {
2966       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2967       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2968       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2969       case SPNB_RETURNS_ANY: {
2970         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2971           Opc = ISD::FMINNUM;
2972         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2973           Opc = ISD::FMINNAN;
2974         else if (UseScalarMinMax)
2975           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2976             ISD::FMINNUM : ISD::FMINNAN;
2977         break;
2978       }
2979       }
2980       break;
2981     case SPF_FMAXNUM:
2982       switch (SPR.NaNBehavior) {
2983       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2984       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2985       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2986       case SPNB_RETURNS_ANY:
2987 
2988         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2989           Opc = ISD::FMAXNUM;
2990         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2991           Opc = ISD::FMAXNAN;
2992         else if (UseScalarMinMax)
2993           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2994             ISD::FMAXNUM : ISD::FMAXNAN;
2995         break;
2996       }
2997       break;
2998     default: break;
2999     }
3000 
3001     if (Opc != ISD::DELETED_NODE &&
3002         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3003          (UseScalarMinMax &&
3004           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3005         // If the underlying comparison instruction is used by any other
3006         // instruction, the consumed instructions won't be destroyed, so it is
3007         // not profitable to convert to a min/max.
3008         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3009       OpCode = Opc;
3010       LHSVal = getValue(LHS);
3011       RHSVal = getValue(RHS);
3012       BaseOps = {};
3013     }
3014   }
3015 
3016   for (unsigned i = 0; i != NumValues; ++i) {
3017     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3018     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3019     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3020     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3021                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3022                             Ops);
3023   }
3024 
3025   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3026                            DAG.getVTList(ValueVTs), Values));
3027 }
3028 
3029 void SelectionDAGBuilder::visitTrunc(const User &I) {
3030   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3031   SDValue N = getValue(I.getOperand(0));
3032   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3033                                                         I.getType());
3034   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3035 }
3036 
3037 void SelectionDAGBuilder::visitZExt(const User &I) {
3038   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3039   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3040   SDValue N = getValue(I.getOperand(0));
3041   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3042                                                         I.getType());
3043   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3044 }
3045 
3046 void SelectionDAGBuilder::visitSExt(const User &I) {
3047   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3048   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3049   SDValue N = getValue(I.getOperand(0));
3050   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3051                                                         I.getType());
3052   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3053 }
3054 
3055 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3056   // FPTrunc is never a no-op cast, no need to check
3057   SDValue N = getValue(I.getOperand(0));
3058   SDLoc dl = getCurSDLoc();
3059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3060   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3061   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3062                            DAG.getTargetConstant(
3063                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3064 }
3065 
3066 void SelectionDAGBuilder::visitFPExt(const User &I) {
3067   // FPExt is never a no-op cast, no need to check
3068   SDValue N = getValue(I.getOperand(0));
3069   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3070                                                         I.getType());
3071   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3072 }
3073 
3074 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3075   // FPToUI is never a no-op cast, no need to check
3076   SDValue N = getValue(I.getOperand(0));
3077   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3078                                                         I.getType());
3079   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3080 }
3081 
3082 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3083   // FPToSI is never a no-op cast, no need to check
3084   SDValue N = getValue(I.getOperand(0));
3085   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3086                                                         I.getType());
3087   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3088 }
3089 
3090 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3091   // UIToFP is never a no-op cast, no need to check
3092   SDValue N = getValue(I.getOperand(0));
3093   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3094                                                         I.getType());
3095   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3096 }
3097 
3098 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3099   // SIToFP is never a no-op cast, no need to check
3100   SDValue N = getValue(I.getOperand(0));
3101   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3102                                                         I.getType());
3103   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3104 }
3105 
3106 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3107   // What to do depends on the size of the integer and the size of the pointer.
3108   // We can either truncate, zero extend, or no-op, accordingly.
3109   SDValue N = getValue(I.getOperand(0));
3110   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3111                                                         I.getType());
3112   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3113 }
3114 
3115 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3116   // What to do depends on the size of the integer and the size of the pointer.
3117   // We can either truncate, zero extend, or no-op, accordingly.
3118   SDValue N = getValue(I.getOperand(0));
3119   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3120                                                         I.getType());
3121   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3122 }
3123 
3124 void SelectionDAGBuilder::visitBitCast(const User &I) {
3125   SDValue N = getValue(I.getOperand(0));
3126   SDLoc dl = getCurSDLoc();
3127   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3128                                                         I.getType());
3129 
3130   // BitCast assures us that source and destination are the same size so this is
3131   // either a BITCAST or a no-op.
3132   if (DestVT != N.getValueType())
3133     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3134                              DestVT, N)); // convert types.
3135   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3136   // might fold any kind of constant expression to an integer constant and that
3137   // is not what we are looking for. Only recognize a bitcast of a genuine
3138   // constant integer as an opaque constant.
3139   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3140     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3141                                  /*isOpaque*/true));
3142   else
3143     setValue(&I, N);            // noop cast.
3144 }
3145 
3146 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3148   const Value *SV = I.getOperand(0);
3149   SDValue N = getValue(SV);
3150   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3151 
3152   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3153   unsigned DestAS = I.getType()->getPointerAddressSpace();
3154 
3155   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3156     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3157 
3158   setValue(&I, N);
3159 }
3160 
3161 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3163   SDValue InVec = getValue(I.getOperand(0));
3164   SDValue InVal = getValue(I.getOperand(1));
3165   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3166                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3167   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3168                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3169                            InVec, InVal, InIdx));
3170 }
3171 
3172 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3174   SDValue InVec = getValue(I.getOperand(0));
3175   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3176                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3177   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3178                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3179                            InVec, InIdx));
3180 }
3181 
3182 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3183   SDValue Src1 = getValue(I.getOperand(0));
3184   SDValue Src2 = getValue(I.getOperand(1));
3185   SDLoc DL = getCurSDLoc();
3186 
3187   SmallVector<int, 8> Mask;
3188   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3189   unsigned MaskNumElts = Mask.size();
3190 
3191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3192   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3193   EVT SrcVT = Src1.getValueType();
3194   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3195 
3196   if (SrcNumElts == MaskNumElts) {
3197     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3198     return;
3199   }
3200 
3201   // Normalize the shuffle vector since mask and vector length don't match.
3202   if (SrcNumElts < MaskNumElts) {
3203     // Mask is longer than the source vectors. We can use concatenate vector to
3204     // make the mask and vectors lengths match.
3205 
3206     if (MaskNumElts % SrcNumElts == 0) {
3207       // Mask length is a multiple of the source vector length.
3208       // Check if the shuffle is some kind of concatenation of the input
3209       // vectors.
3210       unsigned NumConcat = MaskNumElts / SrcNumElts;
3211       bool IsConcat = true;
3212       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3213       for (unsigned i = 0; i != MaskNumElts; ++i) {
3214         int Idx = Mask[i];
3215         if (Idx < 0)
3216           continue;
3217         // Ensure the indices in each SrcVT sized piece are sequential and that
3218         // the same source is used for the whole piece.
3219         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3220             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3221              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3222           IsConcat = false;
3223           break;
3224         }
3225         // Remember which source this index came from.
3226         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3227       }
3228 
3229       // The shuffle is concatenating multiple vectors together. Just emit
3230       // a CONCAT_VECTORS operation.
3231       if (IsConcat) {
3232         SmallVector<SDValue, 8> ConcatOps;
3233         for (auto Src : ConcatSrcs) {
3234           if (Src < 0)
3235             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3236           else if (Src == 0)
3237             ConcatOps.push_back(Src1);
3238           else
3239             ConcatOps.push_back(Src2);
3240         }
3241         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3242         return;
3243       }
3244     }
3245 
3246     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3247     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3248     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3249                                     PaddedMaskNumElts);
3250 
3251     // Pad both vectors with undefs to make them the same length as the mask.
3252     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3253 
3254     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3255     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3256     MOps1[0] = Src1;
3257     MOps2[0] = Src2;
3258 
3259     Src1 = Src1.isUndef()
3260                ? DAG.getUNDEF(PaddedVT)
3261                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3262     Src2 = Src2.isUndef()
3263                ? DAG.getUNDEF(PaddedVT)
3264                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3265 
3266     // Readjust mask for new input vector length.
3267     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3268     for (unsigned i = 0; i != MaskNumElts; ++i) {
3269       int Idx = Mask[i];
3270       if (Idx >= (int)SrcNumElts)
3271         Idx -= SrcNumElts - PaddedMaskNumElts;
3272       MappedOps[i] = Idx;
3273     }
3274 
3275     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3276 
3277     // If the concatenated vector was padded, extract a subvector with the
3278     // correct number of elements.
3279     if (MaskNumElts != PaddedMaskNumElts)
3280       Result = DAG.getNode(
3281           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3282           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3283 
3284     setValue(&I, Result);
3285     return;
3286   }
3287 
3288   if (SrcNumElts > MaskNumElts) {
3289     // Analyze the access pattern of the vector to see if we can extract
3290     // two subvectors and do the shuffle.
3291     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3292     bool CanExtract = true;
3293     for (int Idx : Mask) {
3294       unsigned Input = 0;
3295       if (Idx < 0)
3296         continue;
3297 
3298       if (Idx >= (int)SrcNumElts) {
3299         Input = 1;
3300         Idx -= SrcNumElts;
3301       }
3302 
3303       // If all the indices come from the same MaskNumElts sized portion of
3304       // the sources we can use extract. Also make sure the extract wouldn't
3305       // extract past the end of the source.
3306       int NewStartIdx = alignDown(Idx, MaskNumElts);
3307       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3308           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3309         CanExtract = false;
3310       // Make sure we always update StartIdx as we use it to track if all
3311       // elements are undef.
3312       StartIdx[Input] = NewStartIdx;
3313     }
3314 
3315     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3316       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3317       return;
3318     }
3319     if (CanExtract) {
3320       // Extract appropriate subvector and generate a vector shuffle
3321       for (unsigned Input = 0; Input < 2; ++Input) {
3322         SDValue &Src = Input == 0 ? Src1 : Src2;
3323         if (StartIdx[Input] < 0)
3324           Src = DAG.getUNDEF(VT);
3325         else {
3326           Src = DAG.getNode(
3327               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3328               DAG.getConstant(StartIdx[Input], DL,
3329                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3330         }
3331       }
3332 
3333       // Calculate new mask.
3334       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3335       for (int &Idx : MappedOps) {
3336         if (Idx >= (int)SrcNumElts)
3337           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3338         else if (Idx >= 0)
3339           Idx -= StartIdx[0];
3340       }
3341 
3342       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3343       return;
3344     }
3345   }
3346 
3347   // We can't use either concat vectors or extract subvectors so fall back to
3348   // replacing the shuffle with extract and build vector.
3349   // to insert and build vector.
3350   EVT EltVT = VT.getVectorElementType();
3351   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3352   SmallVector<SDValue,8> Ops;
3353   for (int Idx : Mask) {
3354     SDValue Res;
3355 
3356     if (Idx < 0) {
3357       Res = DAG.getUNDEF(EltVT);
3358     } else {
3359       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3360       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3361 
3362       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3363                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3364     }
3365 
3366     Ops.push_back(Res);
3367   }
3368 
3369   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3370 }
3371 
3372 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3373   ArrayRef<unsigned> Indices;
3374   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3375     Indices = IV->getIndices();
3376   else
3377     Indices = cast<ConstantExpr>(&I)->getIndices();
3378 
3379   const Value *Op0 = I.getOperand(0);
3380   const Value *Op1 = I.getOperand(1);
3381   Type *AggTy = I.getType();
3382   Type *ValTy = Op1->getType();
3383   bool IntoUndef = isa<UndefValue>(Op0);
3384   bool FromUndef = isa<UndefValue>(Op1);
3385 
3386   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3387 
3388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3389   SmallVector<EVT, 4> AggValueVTs;
3390   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3391   SmallVector<EVT, 4> ValValueVTs;
3392   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3393 
3394   unsigned NumAggValues = AggValueVTs.size();
3395   unsigned NumValValues = ValValueVTs.size();
3396   SmallVector<SDValue, 4> Values(NumAggValues);
3397 
3398   // Ignore an insertvalue that produces an empty object
3399   if (!NumAggValues) {
3400     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3401     return;
3402   }
3403 
3404   SDValue Agg = getValue(Op0);
3405   unsigned i = 0;
3406   // Copy the beginning value(s) from the original aggregate.
3407   for (; i != LinearIndex; ++i)
3408     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3409                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3410   // Copy values from the inserted value(s).
3411   if (NumValValues) {
3412     SDValue Val = getValue(Op1);
3413     for (; i != LinearIndex + NumValValues; ++i)
3414       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3415                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3416   }
3417   // Copy remaining value(s) from the original aggregate.
3418   for (; i != NumAggValues; ++i)
3419     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3420                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3421 
3422   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3423                            DAG.getVTList(AggValueVTs), Values));
3424 }
3425 
3426 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3427   ArrayRef<unsigned> Indices;
3428   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3429     Indices = EV->getIndices();
3430   else
3431     Indices = cast<ConstantExpr>(&I)->getIndices();
3432 
3433   const Value *Op0 = I.getOperand(0);
3434   Type *AggTy = Op0->getType();
3435   Type *ValTy = I.getType();
3436   bool OutOfUndef = isa<UndefValue>(Op0);
3437 
3438   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3439 
3440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3441   SmallVector<EVT, 4> ValValueVTs;
3442   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3443 
3444   unsigned NumValValues = ValValueVTs.size();
3445 
3446   // Ignore a extractvalue that produces an empty object
3447   if (!NumValValues) {
3448     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3449     return;
3450   }
3451 
3452   SmallVector<SDValue, 4> Values(NumValValues);
3453 
3454   SDValue Agg = getValue(Op0);
3455   // Copy out the selected value(s).
3456   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3457     Values[i - LinearIndex] =
3458       OutOfUndef ?
3459         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3460         SDValue(Agg.getNode(), Agg.getResNo() + i);
3461 
3462   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3463                            DAG.getVTList(ValValueVTs), Values));
3464 }
3465 
3466 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3467   Value *Op0 = I.getOperand(0);
3468   // Note that the pointer operand may be a vector of pointers. Take the scalar
3469   // element which holds a pointer.
3470   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3471   SDValue N = getValue(Op0);
3472   SDLoc dl = getCurSDLoc();
3473 
3474   // Normalize Vector GEP - all scalar operands should be converted to the
3475   // splat vector.
3476   unsigned VectorWidth = I.getType()->isVectorTy() ?
3477     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3478 
3479   if (VectorWidth && !N.getValueType().isVector()) {
3480     LLVMContext &Context = *DAG.getContext();
3481     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3482     N = DAG.getSplatBuildVector(VT, dl, N);
3483   }
3484 
3485   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3486        GTI != E; ++GTI) {
3487     const Value *Idx = GTI.getOperand();
3488     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3489       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3490       if (Field) {
3491         // N = N + Offset
3492         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3493 
3494         // In an inbounds GEP with an offset that is nonnegative even when
3495         // interpreted as signed, assume there is no unsigned overflow.
3496         SDNodeFlags Flags;
3497         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3498           Flags.setNoUnsignedWrap(true);
3499 
3500         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3501                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3502       }
3503     } else {
3504       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3505       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3506       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3507 
3508       // If this is a scalar constant or a splat vector of constants,
3509       // handle it quickly.
3510       const auto *CI = dyn_cast<ConstantInt>(Idx);
3511       if (!CI && isa<ConstantDataVector>(Idx) &&
3512           cast<ConstantDataVector>(Idx)->getSplatValue())
3513         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3514 
3515       if (CI) {
3516         if (CI->isZero())
3517           continue;
3518         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3519         LLVMContext &Context = *DAG.getContext();
3520         SDValue OffsVal = VectorWidth ?
3521           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3522           DAG.getConstant(Offs, dl, IdxTy);
3523 
3524         // In an inbouds GEP with an offset that is nonnegative even when
3525         // interpreted as signed, assume there is no unsigned overflow.
3526         SDNodeFlags Flags;
3527         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3528           Flags.setNoUnsignedWrap(true);
3529 
3530         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3531         continue;
3532       }
3533 
3534       // N = N + Idx * ElementSize;
3535       SDValue IdxN = getValue(Idx);
3536 
3537       if (!IdxN.getValueType().isVector() && VectorWidth) {
3538         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3539         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3540       }
3541 
3542       // If the index is smaller or larger than intptr_t, truncate or extend
3543       // it.
3544       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3545 
3546       // If this is a multiply by a power of two, turn it into a shl
3547       // immediately.  This is a very common case.
3548       if (ElementSize != 1) {
3549         if (ElementSize.isPowerOf2()) {
3550           unsigned Amt = ElementSize.logBase2();
3551           IdxN = DAG.getNode(ISD::SHL, dl,
3552                              N.getValueType(), IdxN,
3553                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3554         } else {
3555           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3556           IdxN = DAG.getNode(ISD::MUL, dl,
3557                              N.getValueType(), IdxN, Scale);
3558         }
3559       }
3560 
3561       N = DAG.getNode(ISD::ADD, dl,
3562                       N.getValueType(), N, IdxN);
3563     }
3564   }
3565 
3566   setValue(&I, N);
3567 }
3568 
3569 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3570   // If this is a fixed sized alloca in the entry block of the function,
3571   // allocate it statically on the stack.
3572   if (FuncInfo.StaticAllocaMap.count(&I))
3573     return;   // getValue will auto-populate this.
3574 
3575   SDLoc dl = getCurSDLoc();
3576   Type *Ty = I.getAllocatedType();
3577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3578   auto &DL = DAG.getDataLayout();
3579   uint64_t TySize = DL.getTypeAllocSize(Ty);
3580   unsigned Align =
3581       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3582 
3583   SDValue AllocSize = getValue(I.getArraySize());
3584 
3585   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3586   if (AllocSize.getValueType() != IntPtr)
3587     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3588 
3589   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3590                           AllocSize,
3591                           DAG.getConstant(TySize, dl, IntPtr));
3592 
3593   // Handle alignment.  If the requested alignment is less than or equal to
3594   // the stack alignment, ignore it.  If the size is greater than or equal to
3595   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3596   unsigned StackAlign =
3597       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3598   if (Align <= StackAlign)
3599     Align = 0;
3600 
3601   // Round the size of the allocation up to the stack alignment size
3602   // by add SA-1 to the size. This doesn't overflow because we're computing
3603   // an address inside an alloca.
3604   SDNodeFlags Flags;
3605   Flags.setNoUnsignedWrap(true);
3606   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3607                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3608 
3609   // Mask out the low bits for alignment purposes.
3610   AllocSize =
3611       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3612                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3613 
3614   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3615   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3616   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3617   setValue(&I, DSA);
3618   DAG.setRoot(DSA.getValue(1));
3619 
3620   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3621 }
3622 
3623 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3624   if (I.isAtomic())
3625     return visitAtomicLoad(I);
3626 
3627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3628   const Value *SV = I.getOperand(0);
3629   if (TLI.supportSwiftError()) {
3630     // Swifterror values can come from either a function parameter with
3631     // swifterror attribute or an alloca with swifterror attribute.
3632     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3633       if (Arg->hasSwiftErrorAttr())
3634         return visitLoadFromSwiftError(I);
3635     }
3636 
3637     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3638       if (Alloca->isSwiftError())
3639         return visitLoadFromSwiftError(I);
3640     }
3641   }
3642 
3643   SDValue Ptr = getValue(SV);
3644 
3645   Type *Ty = I.getType();
3646 
3647   bool isVolatile = I.isVolatile();
3648   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3649   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3650   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3651   unsigned Alignment = I.getAlignment();
3652 
3653   AAMDNodes AAInfo;
3654   I.getAAMetadata(AAInfo);
3655   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3656 
3657   SmallVector<EVT, 4> ValueVTs;
3658   SmallVector<uint64_t, 4> Offsets;
3659   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3660   unsigned NumValues = ValueVTs.size();
3661   if (NumValues == 0)
3662     return;
3663 
3664   SDValue Root;
3665   bool ConstantMemory = false;
3666   if (isVolatile || NumValues > MaxParallelChains)
3667     // Serialize volatile loads with other side effects.
3668     Root = getRoot();
3669   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3670                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3671     // Do not serialize (non-volatile) loads of constant memory with anything.
3672     Root = DAG.getEntryNode();
3673     ConstantMemory = true;
3674   } else {
3675     // Do not serialize non-volatile loads against each other.
3676     Root = DAG.getRoot();
3677   }
3678 
3679   SDLoc dl = getCurSDLoc();
3680 
3681   if (isVolatile)
3682     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3683 
3684   // An aggregate load cannot wrap around the address space, so offsets to its
3685   // parts don't wrap either.
3686   SDNodeFlags Flags;
3687   Flags.setNoUnsignedWrap(true);
3688 
3689   SmallVector<SDValue, 4> Values(NumValues);
3690   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3691   EVT PtrVT = Ptr.getValueType();
3692   unsigned ChainI = 0;
3693   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3694     // Serializing loads here may result in excessive register pressure, and
3695     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3696     // could recover a bit by hoisting nodes upward in the chain by recognizing
3697     // they are side-effect free or do not alias. The optimizer should really
3698     // avoid this case by converting large object/array copies to llvm.memcpy
3699     // (MaxParallelChains should always remain as failsafe).
3700     if (ChainI == MaxParallelChains) {
3701       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3702       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3703                                   makeArrayRef(Chains.data(), ChainI));
3704       Root = Chain;
3705       ChainI = 0;
3706     }
3707     SDValue A = DAG.getNode(ISD::ADD, dl,
3708                             PtrVT, Ptr,
3709                             DAG.getConstant(Offsets[i], dl, PtrVT),
3710                             Flags);
3711     auto MMOFlags = MachineMemOperand::MONone;
3712     if (isVolatile)
3713       MMOFlags |= MachineMemOperand::MOVolatile;
3714     if (isNonTemporal)
3715       MMOFlags |= MachineMemOperand::MONonTemporal;
3716     if (isInvariant)
3717       MMOFlags |= MachineMemOperand::MOInvariant;
3718     if (isDereferenceable)
3719       MMOFlags |= MachineMemOperand::MODereferenceable;
3720     MMOFlags |= TLI.getMMOFlags(I);
3721 
3722     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3723                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3724                             MMOFlags, AAInfo, Ranges);
3725 
3726     Values[i] = L;
3727     Chains[ChainI] = L.getValue(1);
3728   }
3729 
3730   if (!ConstantMemory) {
3731     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3732                                 makeArrayRef(Chains.data(), ChainI));
3733     if (isVolatile)
3734       DAG.setRoot(Chain);
3735     else
3736       PendingLoads.push_back(Chain);
3737   }
3738 
3739   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3740                            DAG.getVTList(ValueVTs), Values));
3741 }
3742 
3743 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3744   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3745          "call visitStoreToSwiftError when backend supports swifterror");
3746 
3747   SmallVector<EVT, 4> ValueVTs;
3748   SmallVector<uint64_t, 4> Offsets;
3749   const Value *SrcV = I.getOperand(0);
3750   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3751                   SrcV->getType(), ValueVTs, &Offsets);
3752   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3753          "expect a single EVT for swifterror");
3754 
3755   SDValue Src = getValue(SrcV);
3756   // Create a virtual register, then update the virtual register.
3757   unsigned VReg; bool CreatedVReg;
3758   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3759   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3760   // Chain can be getRoot or getControlRoot.
3761   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3762                                       SDValue(Src.getNode(), Src.getResNo()));
3763   DAG.setRoot(CopyNode);
3764   if (CreatedVReg)
3765     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3766 }
3767 
3768 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3769   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3770          "call visitLoadFromSwiftError when backend supports swifterror");
3771 
3772   assert(!I.isVolatile() &&
3773          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3774          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3775          "Support volatile, non temporal, invariant for load_from_swift_error");
3776 
3777   const Value *SV = I.getOperand(0);
3778   Type *Ty = I.getType();
3779   AAMDNodes AAInfo;
3780   I.getAAMetadata(AAInfo);
3781   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3782              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3783          "load_from_swift_error should not be constant memory");
3784 
3785   SmallVector<EVT, 4> ValueVTs;
3786   SmallVector<uint64_t, 4> Offsets;
3787   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3788                   ValueVTs, &Offsets);
3789   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3790          "expect a single EVT for swifterror");
3791 
3792   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3793   SDValue L = DAG.getCopyFromReg(
3794       getRoot(), getCurSDLoc(),
3795       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3796       ValueVTs[0]);
3797 
3798   setValue(&I, L);
3799 }
3800 
3801 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3802   if (I.isAtomic())
3803     return visitAtomicStore(I);
3804 
3805   const Value *SrcV = I.getOperand(0);
3806   const Value *PtrV = I.getOperand(1);
3807 
3808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3809   if (TLI.supportSwiftError()) {
3810     // Swifterror values can come from either a function parameter with
3811     // swifterror attribute or an alloca with swifterror attribute.
3812     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3813       if (Arg->hasSwiftErrorAttr())
3814         return visitStoreToSwiftError(I);
3815     }
3816 
3817     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3818       if (Alloca->isSwiftError())
3819         return visitStoreToSwiftError(I);
3820     }
3821   }
3822 
3823   SmallVector<EVT, 4> ValueVTs;
3824   SmallVector<uint64_t, 4> Offsets;
3825   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3826                   SrcV->getType(), ValueVTs, &Offsets);
3827   unsigned NumValues = ValueVTs.size();
3828   if (NumValues == 0)
3829     return;
3830 
3831   // Get the lowered operands. Note that we do this after
3832   // checking if NumResults is zero, because with zero results
3833   // the operands won't have values in the map.
3834   SDValue Src = getValue(SrcV);
3835   SDValue Ptr = getValue(PtrV);
3836 
3837   SDValue Root = getRoot();
3838   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3839   SDLoc dl = getCurSDLoc();
3840   EVT PtrVT = Ptr.getValueType();
3841   unsigned Alignment = I.getAlignment();
3842   AAMDNodes AAInfo;
3843   I.getAAMetadata(AAInfo);
3844 
3845   auto MMOFlags = MachineMemOperand::MONone;
3846   if (I.isVolatile())
3847     MMOFlags |= MachineMemOperand::MOVolatile;
3848   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3849     MMOFlags |= MachineMemOperand::MONonTemporal;
3850   MMOFlags |= TLI.getMMOFlags(I);
3851 
3852   // An aggregate load cannot wrap around the address space, so offsets to its
3853   // parts don't wrap either.
3854   SDNodeFlags Flags;
3855   Flags.setNoUnsignedWrap(true);
3856 
3857   unsigned ChainI = 0;
3858   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3859     // See visitLoad comments.
3860     if (ChainI == MaxParallelChains) {
3861       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3862                                   makeArrayRef(Chains.data(), ChainI));
3863       Root = Chain;
3864       ChainI = 0;
3865     }
3866     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3867                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3868     SDValue St = DAG.getStore(
3869         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3870         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3871     Chains[ChainI] = St;
3872   }
3873 
3874   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3875                                   makeArrayRef(Chains.data(), ChainI));
3876   DAG.setRoot(StoreNode);
3877 }
3878 
3879 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3880                                            bool IsCompressing) {
3881   SDLoc sdl = getCurSDLoc();
3882 
3883   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3884                            unsigned& Alignment) {
3885     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3886     Src0 = I.getArgOperand(0);
3887     Ptr = I.getArgOperand(1);
3888     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3889     Mask = I.getArgOperand(3);
3890   };
3891   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3892                            unsigned& Alignment) {
3893     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3894     Src0 = I.getArgOperand(0);
3895     Ptr = I.getArgOperand(1);
3896     Mask = I.getArgOperand(2);
3897     Alignment = 0;
3898   };
3899 
3900   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3901   unsigned Alignment;
3902   if (IsCompressing)
3903     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3904   else
3905     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3906 
3907   SDValue Ptr = getValue(PtrOperand);
3908   SDValue Src0 = getValue(Src0Operand);
3909   SDValue Mask = getValue(MaskOperand);
3910 
3911   EVT VT = Src0.getValueType();
3912   if (!Alignment)
3913     Alignment = DAG.getEVTAlignment(VT);
3914 
3915   AAMDNodes AAInfo;
3916   I.getAAMetadata(AAInfo);
3917 
3918   MachineMemOperand *MMO =
3919     DAG.getMachineFunction().
3920     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3921                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3922                           Alignment, AAInfo);
3923   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3924                                          MMO, false /* Truncating */,
3925                                          IsCompressing);
3926   DAG.setRoot(StoreNode);
3927   setValue(&I, StoreNode);
3928 }
3929 
3930 // Get a uniform base for the Gather/Scatter intrinsic.
3931 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3932 // We try to represent it as a base pointer + vector of indices.
3933 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3934 // The first operand of the GEP may be a single pointer or a vector of pointers
3935 // Example:
3936 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3937 //  or
3938 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3939 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3940 //
3941 // When the first GEP operand is a single pointer - it is the uniform base we
3942 // are looking for. If first operand of the GEP is a splat vector - we
3943 // extract the splat value and use it as a uniform base.
3944 // In all other cases the function returns 'false'.
3945 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3946                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3947   SelectionDAG& DAG = SDB->DAG;
3948   LLVMContext &Context = *DAG.getContext();
3949 
3950   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3951   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3952   if (!GEP)
3953     return false;
3954 
3955   const Value *GEPPtr = GEP->getPointerOperand();
3956   if (!GEPPtr->getType()->isVectorTy())
3957     Ptr = GEPPtr;
3958   else if (!(Ptr = getSplatValue(GEPPtr)))
3959     return false;
3960 
3961   unsigned FinalIndex = GEP->getNumOperands() - 1;
3962   Value *IndexVal = GEP->getOperand(FinalIndex);
3963 
3964   // Ensure all the other indices are 0.
3965   for (unsigned i = 1; i < FinalIndex; ++i) {
3966     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3967     if (!C || !C->isZero())
3968       return false;
3969   }
3970 
3971   // The operands of the GEP may be defined in another basic block.
3972   // In this case we'll not find nodes for the operands.
3973   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3974     return false;
3975 
3976   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3977   const DataLayout &DL = DAG.getDataLayout();
3978   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3979                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3980   Base = SDB->getValue(Ptr);
3981   Index = SDB->getValue(IndexVal);
3982 
3983   if (!Index.getValueType().isVector()) {
3984     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3985     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3986     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3987   }
3988   return true;
3989 }
3990 
3991 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3992   SDLoc sdl = getCurSDLoc();
3993 
3994   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3995   const Value *Ptr = I.getArgOperand(1);
3996   SDValue Src0 = getValue(I.getArgOperand(0));
3997   SDValue Mask = getValue(I.getArgOperand(3));
3998   EVT VT = Src0.getValueType();
3999   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4000   if (!Alignment)
4001     Alignment = DAG.getEVTAlignment(VT);
4002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4003 
4004   AAMDNodes AAInfo;
4005   I.getAAMetadata(AAInfo);
4006 
4007   SDValue Base;
4008   SDValue Index;
4009   SDValue Scale;
4010   const Value *BasePtr = Ptr;
4011   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4012 
4013   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4014   MachineMemOperand *MMO = DAG.getMachineFunction().
4015     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4016                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4017                          Alignment, AAInfo);
4018   if (!UniformBase) {
4019     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4020     Index = getValue(Ptr);
4021     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4022   }
4023   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4024   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4025                                          Ops, MMO);
4026   DAG.setRoot(Scatter);
4027   setValue(&I, Scatter);
4028 }
4029 
4030 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4031   SDLoc sdl = getCurSDLoc();
4032 
4033   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4034                            unsigned& Alignment) {
4035     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4036     Ptr = I.getArgOperand(0);
4037     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4038     Mask = I.getArgOperand(2);
4039     Src0 = I.getArgOperand(3);
4040   };
4041   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4042                            unsigned& Alignment) {
4043     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4044     Ptr = I.getArgOperand(0);
4045     Alignment = 0;
4046     Mask = I.getArgOperand(1);
4047     Src0 = I.getArgOperand(2);
4048   };
4049 
4050   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4051   unsigned Alignment;
4052   if (IsExpanding)
4053     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4054   else
4055     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4056 
4057   SDValue Ptr = getValue(PtrOperand);
4058   SDValue Src0 = getValue(Src0Operand);
4059   SDValue Mask = getValue(MaskOperand);
4060 
4061   EVT VT = Src0.getValueType();
4062   if (!Alignment)
4063     Alignment = DAG.getEVTAlignment(VT);
4064 
4065   AAMDNodes AAInfo;
4066   I.getAAMetadata(AAInfo);
4067   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4068 
4069   // Do not serialize masked loads of constant memory with anything.
4070   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4071       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4072   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4073 
4074   MachineMemOperand *MMO =
4075     DAG.getMachineFunction().
4076     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4077                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4078                           Alignment, AAInfo, Ranges);
4079 
4080   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4081                                    ISD::NON_EXTLOAD, IsExpanding);
4082   if (AddToChain)
4083     PendingLoads.push_back(Load.getValue(1));
4084   setValue(&I, Load);
4085 }
4086 
4087 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4088   SDLoc sdl = getCurSDLoc();
4089 
4090   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4091   const Value *Ptr = I.getArgOperand(0);
4092   SDValue Src0 = getValue(I.getArgOperand(3));
4093   SDValue Mask = getValue(I.getArgOperand(2));
4094 
4095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4096   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4097   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4098   if (!Alignment)
4099     Alignment = DAG.getEVTAlignment(VT);
4100 
4101   AAMDNodes AAInfo;
4102   I.getAAMetadata(AAInfo);
4103   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4104 
4105   SDValue Root = DAG.getRoot();
4106   SDValue Base;
4107   SDValue Index;
4108   SDValue Scale;
4109   const Value *BasePtr = Ptr;
4110   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4111   bool ConstantMemory = false;
4112   if (UniformBase &&
4113       AA && AA->pointsToConstantMemory(MemoryLocation(
4114           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4115           AAInfo))) {
4116     // Do not serialize (non-volatile) loads of constant memory with anything.
4117     Root = DAG.getEntryNode();
4118     ConstantMemory = true;
4119   }
4120 
4121   MachineMemOperand *MMO =
4122     DAG.getMachineFunction().
4123     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4124                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4125                          Alignment, AAInfo, Ranges);
4126 
4127   if (!UniformBase) {
4128     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4129     Index = getValue(Ptr);
4130     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4131   }
4132   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4133   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4134                                        Ops, MMO);
4135 
4136   SDValue OutChain = Gather.getValue(1);
4137   if (!ConstantMemory)
4138     PendingLoads.push_back(OutChain);
4139   setValue(&I, Gather);
4140 }
4141 
4142 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4143   SDLoc dl = getCurSDLoc();
4144   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4145   AtomicOrdering FailureOrder = I.getFailureOrdering();
4146   SyncScope::ID SSID = I.getSyncScopeID();
4147 
4148   SDValue InChain = getRoot();
4149 
4150   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4151   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4152   SDValue L = DAG.getAtomicCmpSwap(
4153       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4154       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4155       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4156       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4157 
4158   SDValue OutChain = L.getValue(2);
4159 
4160   setValue(&I, L);
4161   DAG.setRoot(OutChain);
4162 }
4163 
4164 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4165   SDLoc dl = getCurSDLoc();
4166   ISD::NodeType NT;
4167   switch (I.getOperation()) {
4168   default: llvm_unreachable("Unknown atomicrmw operation");
4169   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4170   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4171   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4172   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4173   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4174   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4175   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4176   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4177   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4178   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4179   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4180   }
4181   AtomicOrdering Order = I.getOrdering();
4182   SyncScope::ID SSID = I.getSyncScopeID();
4183 
4184   SDValue InChain = getRoot();
4185 
4186   SDValue L =
4187     DAG.getAtomic(NT, dl,
4188                   getValue(I.getValOperand()).getSimpleValueType(),
4189                   InChain,
4190                   getValue(I.getPointerOperand()),
4191                   getValue(I.getValOperand()),
4192                   I.getPointerOperand(),
4193                   /* Alignment=*/ 0, Order, SSID);
4194 
4195   SDValue OutChain = L.getValue(1);
4196 
4197   setValue(&I, L);
4198   DAG.setRoot(OutChain);
4199 }
4200 
4201 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4202   SDLoc dl = getCurSDLoc();
4203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4204   SDValue Ops[3];
4205   Ops[0] = getRoot();
4206   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4207                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4208   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4209                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4210   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4211 }
4212 
4213 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4214   SDLoc dl = getCurSDLoc();
4215   AtomicOrdering Order = I.getOrdering();
4216   SyncScope::ID SSID = I.getSyncScopeID();
4217 
4218   SDValue InChain = getRoot();
4219 
4220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4221   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4222 
4223   if (!TLI.supportsUnalignedAtomics() &&
4224       I.getAlignment() < VT.getStoreSize())
4225     report_fatal_error("Cannot generate unaligned atomic load");
4226 
4227   MachineMemOperand *MMO =
4228       DAG.getMachineFunction().
4229       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4230                            MachineMemOperand::MOVolatile |
4231                            MachineMemOperand::MOLoad,
4232                            VT.getStoreSize(),
4233                            I.getAlignment() ? I.getAlignment() :
4234                                               DAG.getEVTAlignment(VT),
4235                            AAMDNodes(), nullptr, SSID, Order);
4236 
4237   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4238   SDValue L =
4239       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4240                     getValue(I.getPointerOperand()), MMO);
4241 
4242   SDValue OutChain = L.getValue(1);
4243 
4244   setValue(&I, L);
4245   DAG.setRoot(OutChain);
4246 }
4247 
4248 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4249   SDLoc dl = getCurSDLoc();
4250 
4251   AtomicOrdering Order = I.getOrdering();
4252   SyncScope::ID SSID = I.getSyncScopeID();
4253 
4254   SDValue InChain = getRoot();
4255 
4256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4257   EVT VT =
4258       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4259 
4260   if (I.getAlignment() < VT.getStoreSize())
4261     report_fatal_error("Cannot generate unaligned atomic store");
4262 
4263   SDValue OutChain =
4264     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4265                   InChain,
4266                   getValue(I.getPointerOperand()),
4267                   getValue(I.getValueOperand()),
4268                   I.getPointerOperand(), I.getAlignment(),
4269                   Order, SSID);
4270 
4271   DAG.setRoot(OutChain);
4272 }
4273 
4274 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4275 /// node.
4276 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4277                                                unsigned Intrinsic) {
4278   // Ignore the callsite's attributes. A specific call site may be marked with
4279   // readnone, but the lowering code will expect the chain based on the
4280   // definition.
4281   const Function *F = I.getCalledFunction();
4282   bool HasChain = !F->doesNotAccessMemory();
4283   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4284 
4285   // Build the operand list.
4286   SmallVector<SDValue, 8> Ops;
4287   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4288     if (OnlyLoad) {
4289       // We don't need to serialize loads against other loads.
4290       Ops.push_back(DAG.getRoot());
4291     } else {
4292       Ops.push_back(getRoot());
4293     }
4294   }
4295 
4296   // Info is set by getTgtMemInstrinsic
4297   TargetLowering::IntrinsicInfo Info;
4298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4299   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4300                                                DAG.getMachineFunction(),
4301                                                Intrinsic);
4302 
4303   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4304   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4305       Info.opc == ISD::INTRINSIC_W_CHAIN)
4306     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4307                                         TLI.getPointerTy(DAG.getDataLayout())));
4308 
4309   // Add all operands of the call to the operand list.
4310   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4311     SDValue Op = getValue(I.getArgOperand(i));
4312     Ops.push_back(Op);
4313   }
4314 
4315   SmallVector<EVT, 4> ValueVTs;
4316   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4317 
4318   if (HasChain)
4319     ValueVTs.push_back(MVT::Other);
4320 
4321   SDVTList VTs = DAG.getVTList(ValueVTs);
4322 
4323   // Create the node.
4324   SDValue Result;
4325   if (IsTgtIntrinsic) {
4326     // This is target intrinsic that touches memory
4327     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4328       Ops, Info.memVT,
4329       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4330       Info.flags, Info.size);
4331   } else if (!HasChain) {
4332     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4333   } else if (!I.getType()->isVoidTy()) {
4334     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4335   } else {
4336     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4337   }
4338 
4339   if (HasChain) {
4340     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4341     if (OnlyLoad)
4342       PendingLoads.push_back(Chain);
4343     else
4344       DAG.setRoot(Chain);
4345   }
4346 
4347   if (!I.getType()->isVoidTy()) {
4348     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4349       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4350       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4351     } else
4352       Result = lowerRangeToAssertZExt(DAG, I, Result);
4353 
4354     setValue(&I, Result);
4355   }
4356 }
4357 
4358 /// GetSignificand - Get the significand and build it into a floating-point
4359 /// number with exponent of 1:
4360 ///
4361 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4362 ///
4363 /// where Op is the hexadecimal representation of floating point value.
4364 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4365   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4366                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4367   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4368                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4369   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4370 }
4371 
4372 /// GetExponent - Get the exponent:
4373 ///
4374 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4375 ///
4376 /// where Op is the hexadecimal representation of floating point value.
4377 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4378                            const TargetLowering &TLI, const SDLoc &dl) {
4379   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4380                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4381   SDValue t1 = DAG.getNode(
4382       ISD::SRL, dl, MVT::i32, t0,
4383       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4384   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4385                            DAG.getConstant(127, dl, MVT::i32));
4386   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4387 }
4388 
4389 /// getF32Constant - Get 32-bit floating point constant.
4390 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4391                               const SDLoc &dl) {
4392   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4393                            MVT::f32);
4394 }
4395 
4396 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4397                                        SelectionDAG &DAG) {
4398   // TODO: What fast-math-flags should be set on the floating-point nodes?
4399 
4400   //   IntegerPartOfX = ((int32_t)(t0);
4401   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4402 
4403   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4404   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4405   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4406 
4407   //   IntegerPartOfX <<= 23;
4408   IntegerPartOfX = DAG.getNode(
4409       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4410       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4411                                   DAG.getDataLayout())));
4412 
4413   SDValue TwoToFractionalPartOfX;
4414   if (LimitFloatPrecision <= 6) {
4415     // For floating-point precision of 6:
4416     //
4417     //   TwoToFractionalPartOfX =
4418     //     0.997535578f +
4419     //       (0.735607626f + 0.252464424f * x) * x;
4420     //
4421     // error 0.0144103317, which is 6 bits
4422     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4423                              getF32Constant(DAG, 0x3e814304, dl));
4424     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4425                              getF32Constant(DAG, 0x3f3c50c8, dl));
4426     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4427     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4428                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4429   } else if (LimitFloatPrecision <= 12) {
4430     // For floating-point precision of 12:
4431     //
4432     //   TwoToFractionalPartOfX =
4433     //     0.999892986f +
4434     //       (0.696457318f +
4435     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4436     //
4437     // error 0.000107046256, which is 13 to 14 bits
4438     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4439                              getF32Constant(DAG, 0x3da235e3, dl));
4440     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4441                              getF32Constant(DAG, 0x3e65b8f3, dl));
4442     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4443     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4444                              getF32Constant(DAG, 0x3f324b07, dl));
4445     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4446     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4447                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4448   } else { // LimitFloatPrecision <= 18
4449     // For floating-point precision of 18:
4450     //
4451     //   TwoToFractionalPartOfX =
4452     //     0.999999982f +
4453     //       (0.693148872f +
4454     //         (0.240227044f +
4455     //           (0.554906021e-1f +
4456     //             (0.961591928e-2f +
4457     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4458     // error 2.47208000*10^(-7), which is better than 18 bits
4459     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4460                              getF32Constant(DAG, 0x3924b03e, dl));
4461     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4462                              getF32Constant(DAG, 0x3ab24b87, dl));
4463     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4464     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4465                              getF32Constant(DAG, 0x3c1d8c17, dl));
4466     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4467     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4468                              getF32Constant(DAG, 0x3d634a1d, dl));
4469     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4470     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4471                              getF32Constant(DAG, 0x3e75fe14, dl));
4472     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4473     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4474                               getF32Constant(DAG, 0x3f317234, dl));
4475     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4476     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4477                                          getF32Constant(DAG, 0x3f800000, dl));
4478   }
4479 
4480   // Add the exponent into the result in integer domain.
4481   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4482   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4483                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4484 }
4485 
4486 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4487 /// limited-precision mode.
4488 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4489                          const TargetLowering &TLI) {
4490   if (Op.getValueType() == MVT::f32 &&
4491       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4492 
4493     // Put the exponent in the right bit position for later addition to the
4494     // final result:
4495     //
4496     //   #define LOG2OFe 1.4426950f
4497     //   t0 = Op * LOG2OFe
4498 
4499     // TODO: What fast-math-flags should be set here?
4500     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4501                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4502     return getLimitedPrecisionExp2(t0, dl, DAG);
4503   }
4504 
4505   // No special expansion.
4506   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4507 }
4508 
4509 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4510 /// limited-precision mode.
4511 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4512                          const TargetLowering &TLI) {
4513   // TODO: What fast-math-flags should be set on the floating-point nodes?
4514 
4515   if (Op.getValueType() == MVT::f32 &&
4516       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4517     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4518 
4519     // Scale the exponent by log(2) [0.69314718f].
4520     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4521     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4522                                         getF32Constant(DAG, 0x3f317218, dl));
4523 
4524     // Get the significand and build it into a floating-point number with
4525     // exponent of 1.
4526     SDValue X = GetSignificand(DAG, Op1, dl);
4527 
4528     SDValue LogOfMantissa;
4529     if (LimitFloatPrecision <= 6) {
4530       // For floating-point precision of 6:
4531       //
4532       //   LogofMantissa =
4533       //     -1.1609546f +
4534       //       (1.4034025f - 0.23903021f * x) * x;
4535       //
4536       // error 0.0034276066, which is better than 8 bits
4537       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4538                                getF32Constant(DAG, 0xbe74c456, dl));
4539       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4540                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4541       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4542       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4543                                   getF32Constant(DAG, 0x3f949a29, dl));
4544     } else if (LimitFloatPrecision <= 12) {
4545       // For floating-point precision of 12:
4546       //
4547       //   LogOfMantissa =
4548       //     -1.7417939f +
4549       //       (2.8212026f +
4550       //         (-1.4699568f +
4551       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4552       //
4553       // error 0.000061011436, which is 14 bits
4554       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4555                                getF32Constant(DAG, 0xbd67b6d6, dl));
4556       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4557                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4558       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4559       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4560                                getF32Constant(DAG, 0x3fbc278b, dl));
4561       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4562       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4563                                getF32Constant(DAG, 0x40348e95, dl));
4564       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4565       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4566                                   getF32Constant(DAG, 0x3fdef31a, dl));
4567     } else { // LimitFloatPrecision <= 18
4568       // For floating-point precision of 18:
4569       //
4570       //   LogOfMantissa =
4571       //     -2.1072184f +
4572       //       (4.2372794f +
4573       //         (-3.7029485f +
4574       //           (2.2781945f +
4575       //             (-0.87823314f +
4576       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4577       //
4578       // error 0.0000023660568, which is better than 18 bits
4579       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4580                                getF32Constant(DAG, 0xbc91e5ac, dl));
4581       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4582                                getF32Constant(DAG, 0x3e4350aa, dl));
4583       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4584       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4585                                getF32Constant(DAG, 0x3f60d3e3, dl));
4586       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4587       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4588                                getF32Constant(DAG, 0x4011cdf0, dl));
4589       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4590       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4591                                getF32Constant(DAG, 0x406cfd1c, dl));
4592       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4593       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4594                                getF32Constant(DAG, 0x408797cb, dl));
4595       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4596       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4597                                   getF32Constant(DAG, 0x4006dcab, dl));
4598     }
4599 
4600     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4601   }
4602 
4603   // No special expansion.
4604   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4605 }
4606 
4607 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4608 /// limited-precision mode.
4609 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4610                           const TargetLowering &TLI) {
4611   // TODO: What fast-math-flags should be set on the floating-point nodes?
4612 
4613   if (Op.getValueType() == MVT::f32 &&
4614       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4615     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4616 
4617     // Get the exponent.
4618     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4619 
4620     // Get the significand and build it into a floating-point number with
4621     // exponent of 1.
4622     SDValue X = GetSignificand(DAG, Op1, dl);
4623 
4624     // Different possible minimax approximations of significand in
4625     // floating-point for various degrees of accuracy over [1,2].
4626     SDValue Log2ofMantissa;
4627     if (LimitFloatPrecision <= 6) {
4628       // For floating-point precision of 6:
4629       //
4630       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4631       //
4632       // error 0.0049451742, which is more than 7 bits
4633       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4634                                getF32Constant(DAG, 0xbeb08fe0, dl));
4635       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4636                                getF32Constant(DAG, 0x40019463, dl));
4637       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4638       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4639                                    getF32Constant(DAG, 0x3fd6633d, dl));
4640     } else if (LimitFloatPrecision <= 12) {
4641       // For floating-point precision of 12:
4642       //
4643       //   Log2ofMantissa =
4644       //     -2.51285454f +
4645       //       (4.07009056f +
4646       //         (-2.12067489f +
4647       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4648       //
4649       // error 0.0000876136000, which is better than 13 bits
4650       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4651                                getF32Constant(DAG, 0xbda7262e, dl));
4652       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4653                                getF32Constant(DAG, 0x3f25280b, dl));
4654       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4655       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4656                                getF32Constant(DAG, 0x4007b923, dl));
4657       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4658       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4659                                getF32Constant(DAG, 0x40823e2f, dl));
4660       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4661       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4662                                    getF32Constant(DAG, 0x4020d29c, dl));
4663     } else { // LimitFloatPrecision <= 18
4664       // For floating-point precision of 18:
4665       //
4666       //   Log2ofMantissa =
4667       //     -3.0400495f +
4668       //       (6.1129976f +
4669       //         (-5.3420409f +
4670       //           (3.2865683f +
4671       //             (-1.2669343f +
4672       //               (0.27515199f -
4673       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4674       //
4675       // error 0.0000018516, which is better than 18 bits
4676       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4677                                getF32Constant(DAG, 0xbcd2769e, dl));
4678       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4679                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4680       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4681       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4682                                getF32Constant(DAG, 0x3fa22ae7, dl));
4683       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4684       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4685                                getF32Constant(DAG, 0x40525723, dl));
4686       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4687       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4688                                getF32Constant(DAG, 0x40aaf200, dl));
4689       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4690       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4691                                getF32Constant(DAG, 0x40c39dad, dl));
4692       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4693       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4694                                    getF32Constant(DAG, 0x4042902c, dl));
4695     }
4696 
4697     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4698   }
4699 
4700   // No special expansion.
4701   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4702 }
4703 
4704 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4705 /// limited-precision mode.
4706 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4707                            const TargetLowering &TLI) {
4708   // TODO: What fast-math-flags should be set on the floating-point nodes?
4709 
4710   if (Op.getValueType() == MVT::f32 &&
4711       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4712     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4713 
4714     // Scale the exponent by log10(2) [0.30102999f].
4715     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4716     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4717                                         getF32Constant(DAG, 0x3e9a209a, dl));
4718 
4719     // Get the significand and build it into a floating-point number with
4720     // exponent of 1.
4721     SDValue X = GetSignificand(DAG, Op1, dl);
4722 
4723     SDValue Log10ofMantissa;
4724     if (LimitFloatPrecision <= 6) {
4725       // For floating-point precision of 6:
4726       //
4727       //   Log10ofMantissa =
4728       //     -0.50419619f +
4729       //       (0.60948995f - 0.10380950f * x) * x;
4730       //
4731       // error 0.0014886165, which is 6 bits
4732       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4733                                getF32Constant(DAG, 0xbdd49a13, dl));
4734       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4735                                getF32Constant(DAG, 0x3f1c0789, dl));
4736       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4737       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4738                                     getF32Constant(DAG, 0x3f011300, dl));
4739     } else if (LimitFloatPrecision <= 12) {
4740       // For floating-point precision of 12:
4741       //
4742       //   Log10ofMantissa =
4743       //     -0.64831180f +
4744       //       (0.91751397f +
4745       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4746       //
4747       // error 0.00019228036, which is better than 12 bits
4748       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4749                                getF32Constant(DAG, 0x3d431f31, dl));
4750       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4751                                getF32Constant(DAG, 0x3ea21fb2, dl));
4752       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4753       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4754                                getF32Constant(DAG, 0x3f6ae232, dl));
4755       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4756       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4757                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4758     } else { // LimitFloatPrecision <= 18
4759       // For floating-point precision of 18:
4760       //
4761       //   Log10ofMantissa =
4762       //     -0.84299375f +
4763       //       (1.5327582f +
4764       //         (-1.0688956f +
4765       //           (0.49102474f +
4766       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4767       //
4768       // error 0.0000037995730, which is better than 18 bits
4769       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4770                                getF32Constant(DAG, 0x3c5d51ce, dl));
4771       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4772                                getF32Constant(DAG, 0x3e00685a, dl));
4773       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4774       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4775                                getF32Constant(DAG, 0x3efb6798, dl));
4776       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4777       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4778                                getF32Constant(DAG, 0x3f88d192, dl));
4779       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4780       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4781                                getF32Constant(DAG, 0x3fc4316c, dl));
4782       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4783       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4784                                     getF32Constant(DAG, 0x3f57ce70, dl));
4785     }
4786 
4787     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4788   }
4789 
4790   // No special expansion.
4791   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4792 }
4793 
4794 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4795 /// limited-precision mode.
4796 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4797                           const TargetLowering &TLI) {
4798   if (Op.getValueType() == MVT::f32 &&
4799       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4800     return getLimitedPrecisionExp2(Op, dl, DAG);
4801 
4802   // No special expansion.
4803   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4804 }
4805 
4806 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4807 /// limited-precision mode with x == 10.0f.
4808 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4809                          SelectionDAG &DAG, const TargetLowering &TLI) {
4810   bool IsExp10 = false;
4811   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4812       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4813     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4814       APFloat Ten(10.0f);
4815       IsExp10 = LHSC->isExactlyValue(Ten);
4816     }
4817   }
4818 
4819   // TODO: What fast-math-flags should be set on the FMUL node?
4820   if (IsExp10) {
4821     // Put the exponent in the right bit position for later addition to the
4822     // final result:
4823     //
4824     //   #define LOG2OF10 3.3219281f
4825     //   t0 = Op * LOG2OF10;
4826     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4827                              getF32Constant(DAG, 0x40549a78, dl));
4828     return getLimitedPrecisionExp2(t0, dl, DAG);
4829   }
4830 
4831   // No special expansion.
4832   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4833 }
4834 
4835 /// ExpandPowI - Expand a llvm.powi intrinsic.
4836 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4837                           SelectionDAG &DAG) {
4838   // If RHS is a constant, we can expand this out to a multiplication tree,
4839   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4840   // optimizing for size, we only want to do this if the expansion would produce
4841   // a small number of multiplies, otherwise we do the full expansion.
4842   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4843     // Get the exponent as a positive value.
4844     unsigned Val = RHSC->getSExtValue();
4845     if ((int)Val < 0) Val = -Val;
4846 
4847     // powi(x, 0) -> 1.0
4848     if (Val == 0)
4849       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4850 
4851     const Function &F = DAG.getMachineFunction().getFunction();
4852     if (!F.optForSize() ||
4853         // If optimizing for size, don't insert too many multiplies.
4854         // This inserts up to 5 multiplies.
4855         countPopulation(Val) + Log2_32(Val) < 7) {
4856       // We use the simple binary decomposition method to generate the multiply
4857       // sequence.  There are more optimal ways to do this (for example,
4858       // powi(x,15) generates one more multiply than it should), but this has
4859       // the benefit of being both really simple and much better than a libcall.
4860       SDValue Res;  // Logically starts equal to 1.0
4861       SDValue CurSquare = LHS;
4862       // TODO: Intrinsics should have fast-math-flags that propagate to these
4863       // nodes.
4864       while (Val) {
4865         if (Val & 1) {
4866           if (Res.getNode())
4867             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4868           else
4869             Res = CurSquare;  // 1.0*CurSquare.
4870         }
4871 
4872         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4873                                 CurSquare, CurSquare);
4874         Val >>= 1;
4875       }
4876 
4877       // If the original was negative, invert the result, producing 1/(x*x*x).
4878       if (RHSC->getSExtValue() < 0)
4879         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4880                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4881       return Res;
4882     }
4883   }
4884 
4885   // Otherwise, expand to a libcall.
4886   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4887 }
4888 
4889 // getUnderlyingArgReg - Find underlying register used for a truncated or
4890 // bitcasted argument.
4891 static unsigned getUnderlyingArgReg(const SDValue &N) {
4892   switch (N.getOpcode()) {
4893   case ISD::CopyFromReg:
4894     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4895   case ISD::BITCAST:
4896   case ISD::AssertZext:
4897   case ISD::AssertSext:
4898   case ISD::TRUNCATE:
4899     return getUnderlyingArgReg(N.getOperand(0));
4900   default:
4901     return 0;
4902   }
4903 }
4904 
4905 /// If the DbgValueInst is a dbg_value of a function argument, create the
4906 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4907 /// instruction selection, they will be inserted to the entry BB.
4908 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4909     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4910     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4911   const Argument *Arg = dyn_cast<Argument>(V);
4912   if (!Arg)
4913     return false;
4914 
4915   MachineFunction &MF = DAG.getMachineFunction();
4916   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4917 
4918   bool IsIndirect = false;
4919   Optional<MachineOperand> Op;
4920   // Some arguments' frame index is recorded during argument lowering.
4921   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4922   if (FI != std::numeric_limits<int>::max())
4923     Op = MachineOperand::CreateFI(FI);
4924 
4925   if (!Op && N.getNode()) {
4926     unsigned Reg = getUnderlyingArgReg(N);
4927     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4928       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4929       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4930       if (PR)
4931         Reg = PR;
4932     }
4933     if (Reg) {
4934       Op = MachineOperand::CreateReg(Reg, false);
4935       IsIndirect = IsDbgDeclare;
4936     }
4937   }
4938 
4939   if (!Op && N.getNode())
4940     // Check if frame index is available.
4941     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4942       if (FrameIndexSDNode *FINode =
4943           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4944         Op = MachineOperand::CreateFI(FINode->getIndex());
4945 
4946   if (!Op) {
4947     // Check if ValueMap has reg number.
4948     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4949     if (VMI != FuncInfo.ValueMap.end()) {
4950       const auto &TLI = DAG.getTargetLoweringInfo();
4951       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4952                        V->getType(), getABIRegCopyCC(V));
4953       if (RFV.occupiesMultipleRegs()) {
4954         unsigned Offset = 0;
4955         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4956           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4957           auto FragmentExpr = DIExpression::createFragmentExpression(
4958               Expr, Offset, RegAndSize.second);
4959           if (!FragmentExpr)
4960             continue;
4961           FuncInfo.ArgDbgValues.push_back(
4962               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4963                       Op->getReg(), Variable, *FragmentExpr));
4964           Offset += RegAndSize.second;
4965         }
4966         return true;
4967       }
4968       Op = MachineOperand::CreateReg(VMI->second, false);
4969       IsIndirect = IsDbgDeclare;
4970     }
4971   }
4972 
4973   if (!Op)
4974     return false;
4975 
4976   assert(Variable->isValidLocationForIntrinsic(DL) &&
4977          "Expected inlined-at fields to agree");
4978   IsIndirect = (Op->isReg()) ? IsIndirect : true;
4979   FuncInfo.ArgDbgValues.push_back(
4980       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4981               *Op, Variable, Expr));
4982 
4983   return true;
4984 }
4985 
4986 /// Return the appropriate SDDbgValue based on N.
4987 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4988                                              DILocalVariable *Variable,
4989                                              DIExpression *Expr,
4990                                              const DebugLoc &dl,
4991                                              unsigned DbgSDNodeOrder) {
4992   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4993     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4994     // stack slot locations.
4995     //
4996     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
4997     // debug values here after optimization:
4998     //
4999     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5000     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5001     //
5002     // Both describe the direct values of their associated variables.
5003     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5004                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5005   }
5006   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5007                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5008 }
5009 
5010 // VisualStudio defines setjmp as _setjmp
5011 #if defined(_MSC_VER) && defined(setjmp) && \
5012                          !defined(setjmp_undefined_for_msvc)
5013 #  pragma push_macro("setjmp")
5014 #  undef setjmp
5015 #  define setjmp_undefined_for_msvc
5016 #endif
5017 
5018 /// Lower the call to the specified intrinsic function. If we want to emit this
5019 /// as a call to a named external function, return the name. Otherwise, lower it
5020 /// and return null.
5021 const char *
5022 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5024   SDLoc sdl = getCurSDLoc();
5025   DebugLoc dl = getCurDebugLoc();
5026   SDValue Res;
5027 
5028   switch (Intrinsic) {
5029   default:
5030     // By default, turn this into a target intrinsic node.
5031     visitTargetIntrinsic(I, Intrinsic);
5032     return nullptr;
5033   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5034   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5035   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5036   case Intrinsic::returnaddress:
5037     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5038                              TLI.getPointerTy(DAG.getDataLayout()),
5039                              getValue(I.getArgOperand(0))));
5040     return nullptr;
5041   case Intrinsic::addressofreturnaddress:
5042     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5043                              TLI.getPointerTy(DAG.getDataLayout())));
5044     return nullptr;
5045   case Intrinsic::frameaddress:
5046     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5047                              TLI.getPointerTy(DAG.getDataLayout()),
5048                              getValue(I.getArgOperand(0))));
5049     return nullptr;
5050   case Intrinsic::read_register: {
5051     Value *Reg = I.getArgOperand(0);
5052     SDValue Chain = getRoot();
5053     SDValue RegName =
5054         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5055     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5056     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5057       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5058     setValue(&I, Res);
5059     DAG.setRoot(Res.getValue(1));
5060     return nullptr;
5061   }
5062   case Intrinsic::write_register: {
5063     Value *Reg = I.getArgOperand(0);
5064     Value *RegValue = I.getArgOperand(1);
5065     SDValue Chain = getRoot();
5066     SDValue RegName =
5067         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5068     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5069                             RegName, getValue(RegValue)));
5070     return nullptr;
5071   }
5072   case Intrinsic::setjmp:
5073     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5074   case Intrinsic::longjmp:
5075     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5076   case Intrinsic::memcpy: {
5077     const auto &MCI = cast<MemCpyInst>(I);
5078     SDValue Op1 = getValue(I.getArgOperand(0));
5079     SDValue Op2 = getValue(I.getArgOperand(1));
5080     SDValue Op3 = getValue(I.getArgOperand(2));
5081     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5082     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5083     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5084     unsigned Align = MinAlign(DstAlign, SrcAlign);
5085     bool isVol = MCI.isVolatile();
5086     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5087     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5088     // node.
5089     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5090                                false, isTC,
5091                                MachinePointerInfo(I.getArgOperand(0)),
5092                                MachinePointerInfo(I.getArgOperand(1)));
5093     updateDAGForMaybeTailCall(MC);
5094     return nullptr;
5095   }
5096   case Intrinsic::memset: {
5097     const auto &MSI = cast<MemSetInst>(I);
5098     SDValue Op1 = getValue(I.getArgOperand(0));
5099     SDValue Op2 = getValue(I.getArgOperand(1));
5100     SDValue Op3 = getValue(I.getArgOperand(2));
5101     // @llvm.memset defines 0 and 1 to both mean no alignment.
5102     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5103     bool isVol = MSI.isVolatile();
5104     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5105     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5106                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5107     updateDAGForMaybeTailCall(MS);
5108     return nullptr;
5109   }
5110   case Intrinsic::memmove: {
5111     const auto &MMI = cast<MemMoveInst>(I);
5112     SDValue Op1 = getValue(I.getArgOperand(0));
5113     SDValue Op2 = getValue(I.getArgOperand(1));
5114     SDValue Op3 = getValue(I.getArgOperand(2));
5115     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5116     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5117     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5118     unsigned Align = MinAlign(DstAlign, SrcAlign);
5119     bool isVol = MMI.isVolatile();
5120     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5121     // FIXME: Support passing different dest/src alignments to the memmove DAG
5122     // node.
5123     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5124                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5125                                 MachinePointerInfo(I.getArgOperand(1)));
5126     updateDAGForMaybeTailCall(MM);
5127     return nullptr;
5128   }
5129   case Intrinsic::memcpy_element_unordered_atomic: {
5130     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5131     SDValue Dst = getValue(MI.getRawDest());
5132     SDValue Src = getValue(MI.getRawSource());
5133     SDValue Length = getValue(MI.getLength());
5134 
5135     unsigned DstAlign = MI.getDestAlignment();
5136     unsigned SrcAlign = MI.getSourceAlignment();
5137     Type *LengthTy = MI.getLength()->getType();
5138     unsigned ElemSz = MI.getElementSizeInBytes();
5139     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5140     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5141                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5142                                      MachinePointerInfo(MI.getRawDest()),
5143                                      MachinePointerInfo(MI.getRawSource()));
5144     updateDAGForMaybeTailCall(MC);
5145     return nullptr;
5146   }
5147   case Intrinsic::memmove_element_unordered_atomic: {
5148     auto &MI = cast<AtomicMemMoveInst>(I);
5149     SDValue Dst = getValue(MI.getRawDest());
5150     SDValue Src = getValue(MI.getRawSource());
5151     SDValue Length = getValue(MI.getLength());
5152 
5153     unsigned DstAlign = MI.getDestAlignment();
5154     unsigned SrcAlign = MI.getSourceAlignment();
5155     Type *LengthTy = MI.getLength()->getType();
5156     unsigned ElemSz = MI.getElementSizeInBytes();
5157     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5158     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5159                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5160                                       MachinePointerInfo(MI.getRawDest()),
5161                                       MachinePointerInfo(MI.getRawSource()));
5162     updateDAGForMaybeTailCall(MC);
5163     return nullptr;
5164   }
5165   case Intrinsic::memset_element_unordered_atomic: {
5166     auto &MI = cast<AtomicMemSetInst>(I);
5167     SDValue Dst = getValue(MI.getRawDest());
5168     SDValue Val = getValue(MI.getValue());
5169     SDValue Length = getValue(MI.getLength());
5170 
5171     unsigned DstAlign = MI.getDestAlignment();
5172     Type *LengthTy = MI.getLength()->getType();
5173     unsigned ElemSz = MI.getElementSizeInBytes();
5174     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5175     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5176                                      LengthTy, ElemSz, isTC,
5177                                      MachinePointerInfo(MI.getRawDest()));
5178     updateDAGForMaybeTailCall(MC);
5179     return nullptr;
5180   }
5181   case Intrinsic::dbg_addr:
5182   case Intrinsic::dbg_declare: {
5183     const auto &DI = cast<DbgVariableIntrinsic>(I);
5184     DILocalVariable *Variable = DI.getVariable();
5185     DIExpression *Expression = DI.getExpression();
5186     dropDanglingDebugInfo(Variable, Expression);
5187     assert(Variable && "Missing variable");
5188 
5189     // Check if address has undef value.
5190     const Value *Address = DI.getVariableLocation();
5191     if (!Address || isa<UndefValue>(Address) ||
5192         (Address->use_empty() && !isa<Argument>(Address))) {
5193       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5194       return nullptr;
5195     }
5196 
5197     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5198 
5199     // Check if this variable can be described by a frame index, typically
5200     // either as a static alloca or a byval parameter.
5201     int FI = std::numeric_limits<int>::max();
5202     if (const auto *AI =
5203             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5204       if (AI->isStaticAlloca()) {
5205         auto I = FuncInfo.StaticAllocaMap.find(AI);
5206         if (I != FuncInfo.StaticAllocaMap.end())
5207           FI = I->second;
5208       }
5209     } else if (const auto *Arg = dyn_cast<Argument>(
5210                    Address->stripInBoundsConstantOffsets())) {
5211       FI = FuncInfo.getArgumentFrameIndex(Arg);
5212     }
5213 
5214     // llvm.dbg.addr is control dependent and always generates indirect
5215     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5216     // the MachineFunction variable table.
5217     if (FI != std::numeric_limits<int>::max()) {
5218       if (Intrinsic == Intrinsic::dbg_addr) {
5219         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5220             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5221         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5222       }
5223       return nullptr;
5224     }
5225 
5226     SDValue &N = NodeMap[Address];
5227     if (!N.getNode() && isa<Argument>(Address))
5228       // Check unused arguments map.
5229       N = UnusedArgNodeMap[Address];
5230     SDDbgValue *SDV;
5231     if (N.getNode()) {
5232       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5233         Address = BCI->getOperand(0);
5234       // Parameters are handled specially.
5235       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5236       if (isParameter && FINode) {
5237         // Byval parameter. We have a frame index at this point.
5238         SDV =
5239             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5240                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5241       } else if (isa<Argument>(Address)) {
5242         // Address is an argument, so try to emit its dbg value using
5243         // virtual register info from the FuncInfo.ValueMap.
5244         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5245         return nullptr;
5246       } else {
5247         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5248                               true, dl, SDNodeOrder);
5249       }
5250       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5251     } else {
5252       // If Address is an argument then try to emit its dbg value using
5253       // virtual register info from the FuncInfo.ValueMap.
5254       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5255                                     N)) {
5256         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5257       }
5258     }
5259     return nullptr;
5260   }
5261   case Intrinsic::dbg_label: {
5262     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5263     DILabel *Label = DI.getLabel();
5264     assert(Label && "Missing label");
5265 
5266     SDDbgLabel *SDV;
5267     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5268     DAG.AddDbgLabel(SDV);
5269     return nullptr;
5270   }
5271   case Intrinsic::dbg_value: {
5272     const DbgValueInst &DI = cast<DbgValueInst>(I);
5273     assert(DI.getVariable() && "Missing variable");
5274 
5275     DILocalVariable *Variable = DI.getVariable();
5276     DIExpression *Expression = DI.getExpression();
5277     dropDanglingDebugInfo(Variable, Expression);
5278     const Value *V = DI.getValue();
5279     if (!V)
5280       return nullptr;
5281 
5282     SDDbgValue *SDV;
5283     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5284       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5285       DAG.AddDbgValue(SDV, nullptr, false);
5286       return nullptr;
5287     }
5288 
5289     // Do not use getValue() in here; we don't want to generate code at
5290     // this point if it hasn't been done yet.
5291     SDValue N = NodeMap[V];
5292     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5293       N = UnusedArgNodeMap[V];
5294     if (N.getNode()) {
5295       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5296         return nullptr;
5297       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5298       DAG.AddDbgValue(SDV, N.getNode(), false);
5299       return nullptr;
5300     }
5301 
5302     // PHI nodes have already been selected, so we should know which VReg that
5303     // is assigns to already.
5304     if (isa<PHINode>(V)) {
5305       auto VMI = FuncInfo.ValueMap.find(V);
5306       if (VMI != FuncInfo.ValueMap.end()) {
5307         unsigned Reg = VMI->second;
5308         // The PHI node may be split up into several MI PHI nodes (in
5309         // FunctionLoweringInfo::set).
5310         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5311                          V->getType(), None);
5312         if (RFV.occupiesMultipleRegs()) {
5313           unsigned Offset = 0;
5314           unsigned BitsToDescribe = 0;
5315           if (auto VarSize = Variable->getSizeInBits())
5316             BitsToDescribe = *VarSize;
5317           if (auto Fragment = Expression->getFragmentInfo())
5318             BitsToDescribe = Fragment->SizeInBits;
5319           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5320             unsigned RegisterSize = RegAndSize.second;
5321             // Bail out if all bits are described already.
5322             if (Offset >= BitsToDescribe)
5323               break;
5324             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5325                 ? BitsToDescribe - Offset
5326                 : RegisterSize;
5327             auto FragmentExpr = DIExpression::createFragmentExpression(
5328                 Expression, Offset, FragmentSize);
5329             if (!FragmentExpr)
5330                 continue;
5331             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5332                                       false, dl, SDNodeOrder);
5333             DAG.AddDbgValue(SDV, nullptr, false);
5334             Offset += RegisterSize;
5335           }
5336         } else {
5337           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5338                                     SDNodeOrder);
5339           DAG.AddDbgValue(SDV, nullptr, false);
5340         }
5341         return nullptr;
5342       }
5343     }
5344 
5345     // TODO: When we get here we will either drop the dbg.value completely, or
5346     // we try to move it forward by letting it dangle for awhile. So we should
5347     // probably add an extra DbgValue to the DAG here, with a reference to
5348     // "noreg", to indicate that we have lost the debug location for the
5349     // variable.
5350 
5351     if (!V->use_empty() ) {
5352       // Do not call getValue(V) yet, as we don't want to generate code.
5353       // Remember it for later.
5354       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5355       return nullptr;
5356     }
5357 
5358     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5359     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5360     return nullptr;
5361   }
5362 
5363   case Intrinsic::eh_typeid_for: {
5364     // Find the type id for the given typeinfo.
5365     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5366     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5367     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5368     setValue(&I, Res);
5369     return nullptr;
5370   }
5371 
5372   case Intrinsic::eh_return_i32:
5373   case Intrinsic::eh_return_i64:
5374     DAG.getMachineFunction().setCallsEHReturn(true);
5375     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5376                             MVT::Other,
5377                             getControlRoot(),
5378                             getValue(I.getArgOperand(0)),
5379                             getValue(I.getArgOperand(1))));
5380     return nullptr;
5381   case Intrinsic::eh_unwind_init:
5382     DAG.getMachineFunction().setCallsUnwindInit(true);
5383     return nullptr;
5384   case Intrinsic::eh_dwarf_cfa:
5385     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5386                              TLI.getPointerTy(DAG.getDataLayout()),
5387                              getValue(I.getArgOperand(0))));
5388     return nullptr;
5389   case Intrinsic::eh_sjlj_callsite: {
5390     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5391     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5392     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5393     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5394 
5395     MMI.setCurrentCallSite(CI->getZExtValue());
5396     return nullptr;
5397   }
5398   case Intrinsic::eh_sjlj_functioncontext: {
5399     // Get and store the index of the function context.
5400     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5401     AllocaInst *FnCtx =
5402       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5403     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5404     MFI.setFunctionContextIndex(FI);
5405     return nullptr;
5406   }
5407   case Intrinsic::eh_sjlj_setjmp: {
5408     SDValue Ops[2];
5409     Ops[0] = getRoot();
5410     Ops[1] = getValue(I.getArgOperand(0));
5411     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5412                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5413     setValue(&I, Op.getValue(0));
5414     DAG.setRoot(Op.getValue(1));
5415     return nullptr;
5416   }
5417   case Intrinsic::eh_sjlj_longjmp:
5418     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5419                             getRoot(), getValue(I.getArgOperand(0))));
5420     return nullptr;
5421   case Intrinsic::eh_sjlj_setup_dispatch:
5422     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5423                             getRoot()));
5424     return nullptr;
5425   case Intrinsic::masked_gather:
5426     visitMaskedGather(I);
5427     return nullptr;
5428   case Intrinsic::masked_load:
5429     visitMaskedLoad(I);
5430     return nullptr;
5431   case Intrinsic::masked_scatter:
5432     visitMaskedScatter(I);
5433     return nullptr;
5434   case Intrinsic::masked_store:
5435     visitMaskedStore(I);
5436     return nullptr;
5437   case Intrinsic::masked_expandload:
5438     visitMaskedLoad(I, true /* IsExpanding */);
5439     return nullptr;
5440   case Intrinsic::masked_compressstore:
5441     visitMaskedStore(I, true /* IsCompressing */);
5442     return nullptr;
5443   case Intrinsic::x86_mmx_pslli_w:
5444   case Intrinsic::x86_mmx_pslli_d:
5445   case Intrinsic::x86_mmx_pslli_q:
5446   case Intrinsic::x86_mmx_psrli_w:
5447   case Intrinsic::x86_mmx_psrli_d:
5448   case Intrinsic::x86_mmx_psrli_q:
5449   case Intrinsic::x86_mmx_psrai_w:
5450   case Intrinsic::x86_mmx_psrai_d: {
5451     SDValue ShAmt = getValue(I.getArgOperand(1));
5452     if (isa<ConstantSDNode>(ShAmt)) {
5453       visitTargetIntrinsic(I, Intrinsic);
5454       return nullptr;
5455     }
5456     unsigned NewIntrinsic = 0;
5457     EVT ShAmtVT = MVT::v2i32;
5458     switch (Intrinsic) {
5459     case Intrinsic::x86_mmx_pslli_w:
5460       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5461       break;
5462     case Intrinsic::x86_mmx_pslli_d:
5463       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5464       break;
5465     case Intrinsic::x86_mmx_pslli_q:
5466       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5467       break;
5468     case Intrinsic::x86_mmx_psrli_w:
5469       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5470       break;
5471     case Intrinsic::x86_mmx_psrli_d:
5472       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5473       break;
5474     case Intrinsic::x86_mmx_psrli_q:
5475       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5476       break;
5477     case Intrinsic::x86_mmx_psrai_w:
5478       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5479       break;
5480     case Intrinsic::x86_mmx_psrai_d:
5481       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5482       break;
5483     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5484     }
5485 
5486     // The vector shift intrinsics with scalars uses 32b shift amounts but
5487     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5488     // to be zero.
5489     // We must do this early because v2i32 is not a legal type.
5490     SDValue ShOps[2];
5491     ShOps[0] = ShAmt;
5492     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5493     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5494     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5495     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5496     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5497                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5498                        getValue(I.getArgOperand(0)), ShAmt);
5499     setValue(&I, Res);
5500     return nullptr;
5501   }
5502   case Intrinsic::powi:
5503     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5504                             getValue(I.getArgOperand(1)), DAG));
5505     return nullptr;
5506   case Intrinsic::log:
5507     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5508     return nullptr;
5509   case Intrinsic::log2:
5510     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5511     return nullptr;
5512   case Intrinsic::log10:
5513     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5514     return nullptr;
5515   case Intrinsic::exp:
5516     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5517     return nullptr;
5518   case Intrinsic::exp2:
5519     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5520     return nullptr;
5521   case Intrinsic::pow:
5522     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5523                            getValue(I.getArgOperand(1)), DAG, TLI));
5524     return nullptr;
5525   case Intrinsic::sqrt:
5526   case Intrinsic::fabs:
5527   case Intrinsic::sin:
5528   case Intrinsic::cos:
5529   case Intrinsic::floor:
5530   case Intrinsic::ceil:
5531   case Intrinsic::trunc:
5532   case Intrinsic::rint:
5533   case Intrinsic::nearbyint:
5534   case Intrinsic::round:
5535   case Intrinsic::canonicalize: {
5536     unsigned Opcode;
5537     switch (Intrinsic) {
5538     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5539     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5540     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5541     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5542     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5543     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5544     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5545     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5546     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5547     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5548     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5549     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5550     }
5551 
5552     setValue(&I, DAG.getNode(Opcode, sdl,
5553                              getValue(I.getArgOperand(0)).getValueType(),
5554                              getValue(I.getArgOperand(0))));
5555     return nullptr;
5556   }
5557   case Intrinsic::minnum: {
5558     auto VT = getValue(I.getArgOperand(0)).getValueType();
5559     unsigned Opc =
5560         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5561             ? ISD::FMINNAN
5562             : ISD::FMINNUM;
5563     setValue(&I, DAG.getNode(Opc, sdl, VT,
5564                              getValue(I.getArgOperand(0)),
5565                              getValue(I.getArgOperand(1))));
5566     return nullptr;
5567   }
5568   case Intrinsic::maxnum: {
5569     auto VT = getValue(I.getArgOperand(0)).getValueType();
5570     unsigned Opc =
5571         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5572             ? ISD::FMAXNAN
5573             : ISD::FMAXNUM;
5574     setValue(&I, DAG.getNode(Opc, sdl, VT,
5575                              getValue(I.getArgOperand(0)),
5576                              getValue(I.getArgOperand(1))));
5577     return nullptr;
5578   }
5579   case Intrinsic::copysign:
5580     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5581                              getValue(I.getArgOperand(0)).getValueType(),
5582                              getValue(I.getArgOperand(0)),
5583                              getValue(I.getArgOperand(1))));
5584     return nullptr;
5585   case Intrinsic::fma:
5586     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5587                              getValue(I.getArgOperand(0)).getValueType(),
5588                              getValue(I.getArgOperand(0)),
5589                              getValue(I.getArgOperand(1)),
5590                              getValue(I.getArgOperand(2))));
5591     return nullptr;
5592   case Intrinsic::experimental_constrained_fadd:
5593   case Intrinsic::experimental_constrained_fsub:
5594   case Intrinsic::experimental_constrained_fmul:
5595   case Intrinsic::experimental_constrained_fdiv:
5596   case Intrinsic::experimental_constrained_frem:
5597   case Intrinsic::experimental_constrained_fma:
5598   case Intrinsic::experimental_constrained_sqrt:
5599   case Intrinsic::experimental_constrained_pow:
5600   case Intrinsic::experimental_constrained_powi:
5601   case Intrinsic::experimental_constrained_sin:
5602   case Intrinsic::experimental_constrained_cos:
5603   case Intrinsic::experimental_constrained_exp:
5604   case Intrinsic::experimental_constrained_exp2:
5605   case Intrinsic::experimental_constrained_log:
5606   case Intrinsic::experimental_constrained_log10:
5607   case Intrinsic::experimental_constrained_log2:
5608   case Intrinsic::experimental_constrained_rint:
5609   case Intrinsic::experimental_constrained_nearbyint:
5610     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5611     return nullptr;
5612   case Intrinsic::fmuladd: {
5613     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5614     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5615         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5616       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5617                                getValue(I.getArgOperand(0)).getValueType(),
5618                                getValue(I.getArgOperand(0)),
5619                                getValue(I.getArgOperand(1)),
5620                                getValue(I.getArgOperand(2))));
5621     } else {
5622       // TODO: Intrinsic calls should have fast-math-flags.
5623       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5624                                 getValue(I.getArgOperand(0)).getValueType(),
5625                                 getValue(I.getArgOperand(0)),
5626                                 getValue(I.getArgOperand(1)));
5627       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5628                                 getValue(I.getArgOperand(0)).getValueType(),
5629                                 Mul,
5630                                 getValue(I.getArgOperand(2)));
5631       setValue(&I, Add);
5632     }
5633     return nullptr;
5634   }
5635   case Intrinsic::convert_to_fp16:
5636     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5637                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5638                                          getValue(I.getArgOperand(0)),
5639                                          DAG.getTargetConstant(0, sdl,
5640                                                                MVT::i32))));
5641     return nullptr;
5642   case Intrinsic::convert_from_fp16:
5643     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5644                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5645                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5646                                          getValue(I.getArgOperand(0)))));
5647     return nullptr;
5648   case Intrinsic::pcmarker: {
5649     SDValue Tmp = getValue(I.getArgOperand(0));
5650     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5651     return nullptr;
5652   }
5653   case Intrinsic::readcyclecounter: {
5654     SDValue Op = getRoot();
5655     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5656                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5657     setValue(&I, Res);
5658     DAG.setRoot(Res.getValue(1));
5659     return nullptr;
5660   }
5661   case Intrinsic::bitreverse:
5662     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5663                              getValue(I.getArgOperand(0)).getValueType(),
5664                              getValue(I.getArgOperand(0))));
5665     return nullptr;
5666   case Intrinsic::bswap:
5667     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5668                              getValue(I.getArgOperand(0)).getValueType(),
5669                              getValue(I.getArgOperand(0))));
5670     return nullptr;
5671   case Intrinsic::cttz: {
5672     SDValue Arg = getValue(I.getArgOperand(0));
5673     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5674     EVT Ty = Arg.getValueType();
5675     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5676                              sdl, Ty, Arg));
5677     return nullptr;
5678   }
5679   case Intrinsic::ctlz: {
5680     SDValue Arg = getValue(I.getArgOperand(0));
5681     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5682     EVT Ty = Arg.getValueType();
5683     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5684                              sdl, Ty, Arg));
5685     return nullptr;
5686   }
5687   case Intrinsic::ctpop: {
5688     SDValue Arg = getValue(I.getArgOperand(0));
5689     EVT Ty = Arg.getValueType();
5690     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5691     return nullptr;
5692   }
5693   case Intrinsic::fshl:
5694   case Intrinsic::fshr: {
5695     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5696     SDValue X = getValue(I.getArgOperand(0));
5697     SDValue Y = getValue(I.getArgOperand(1));
5698     SDValue Z = getValue(I.getArgOperand(2));
5699     EVT VT = X.getValueType();
5700     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5701     SDValue Zero = DAG.getConstant(0, sdl, VT);
5702     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5703 
5704     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5705     // avoid the select that is necessary in the general case to filter out
5706     // the 0-shift possibility that leads to UB.
5707     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5708       // TODO: This should also be done if the operation is custom, but we have
5709       // to make sure targets are handling the modulo shift amount as expected.
5710       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5711       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5712         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5713         return nullptr;
5714       }
5715 
5716       // Some targets only rotate one way. Try the opposite direction.
5717       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5718       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5719         // Negate the shift amount because it is safe to ignore the high bits.
5720         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5721         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5722         return nullptr;
5723       }
5724 
5725       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5726       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5727       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5728       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5729       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5730       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5731       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5732       return nullptr;
5733     }
5734 
5735     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5736     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5737     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5738     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5739     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5740     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5741 
5742     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5743     // and that is undefined. We must compare and select to avoid UB.
5744     EVT CCVT = MVT::i1;
5745     if (VT.isVector())
5746       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5747 
5748     // For fshl, 0-shift returns the 1st arg (X).
5749     // For fshr, 0-shift returns the 2nd arg (Y).
5750     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5751     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5752     return nullptr;
5753   }
5754   case Intrinsic::stacksave: {
5755     SDValue Op = getRoot();
5756     Res = DAG.getNode(
5757         ISD::STACKSAVE, sdl,
5758         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5759     setValue(&I, Res);
5760     DAG.setRoot(Res.getValue(1));
5761     return nullptr;
5762   }
5763   case Intrinsic::stackrestore:
5764     Res = getValue(I.getArgOperand(0));
5765     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5766     return nullptr;
5767   case Intrinsic::get_dynamic_area_offset: {
5768     SDValue Op = getRoot();
5769     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5770     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5771     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5772     // target.
5773     if (PtrTy != ResTy)
5774       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5775                          " intrinsic!");
5776     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5777                       Op);
5778     DAG.setRoot(Op);
5779     setValue(&I, Res);
5780     return nullptr;
5781   }
5782   case Intrinsic::stackguard: {
5783     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5784     MachineFunction &MF = DAG.getMachineFunction();
5785     const Module &M = *MF.getFunction().getParent();
5786     SDValue Chain = getRoot();
5787     if (TLI.useLoadStackGuardNode()) {
5788       Res = getLoadStackGuard(DAG, sdl, Chain);
5789     } else {
5790       const Value *Global = TLI.getSDagStackGuard(M);
5791       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5792       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5793                         MachinePointerInfo(Global, 0), Align,
5794                         MachineMemOperand::MOVolatile);
5795     }
5796     if (TLI.useStackGuardXorFP())
5797       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5798     DAG.setRoot(Chain);
5799     setValue(&I, Res);
5800     return nullptr;
5801   }
5802   case Intrinsic::stackprotector: {
5803     // Emit code into the DAG to store the stack guard onto the stack.
5804     MachineFunction &MF = DAG.getMachineFunction();
5805     MachineFrameInfo &MFI = MF.getFrameInfo();
5806     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5807     SDValue Src, Chain = getRoot();
5808 
5809     if (TLI.useLoadStackGuardNode())
5810       Src = getLoadStackGuard(DAG, sdl, Chain);
5811     else
5812       Src = getValue(I.getArgOperand(0));   // The guard's value.
5813 
5814     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5815 
5816     int FI = FuncInfo.StaticAllocaMap[Slot];
5817     MFI.setStackProtectorIndex(FI);
5818 
5819     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5820 
5821     // Store the stack protector onto the stack.
5822     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5823                                                  DAG.getMachineFunction(), FI),
5824                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5825     setValue(&I, Res);
5826     DAG.setRoot(Res);
5827     return nullptr;
5828   }
5829   case Intrinsic::objectsize: {
5830     // If we don't know by now, we're never going to know.
5831     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5832 
5833     assert(CI && "Non-constant type in __builtin_object_size?");
5834 
5835     SDValue Arg = getValue(I.getCalledValue());
5836     EVT Ty = Arg.getValueType();
5837 
5838     if (CI->isZero())
5839       Res = DAG.getConstant(-1ULL, sdl, Ty);
5840     else
5841       Res = DAG.getConstant(0, sdl, Ty);
5842 
5843     setValue(&I, Res);
5844     return nullptr;
5845   }
5846   case Intrinsic::annotation:
5847   case Intrinsic::ptr_annotation:
5848   case Intrinsic::launder_invariant_group:
5849   case Intrinsic::strip_invariant_group:
5850     // Drop the intrinsic, but forward the value
5851     setValue(&I, getValue(I.getOperand(0)));
5852     return nullptr;
5853   case Intrinsic::assume:
5854   case Intrinsic::var_annotation:
5855   case Intrinsic::sideeffect:
5856     // Discard annotate attributes, assumptions, and artificial side-effects.
5857     return nullptr;
5858 
5859   case Intrinsic::codeview_annotation: {
5860     // Emit a label associated with this metadata.
5861     MachineFunction &MF = DAG.getMachineFunction();
5862     MCSymbol *Label =
5863         MF.getMMI().getContext().createTempSymbol("annotation", true);
5864     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5865     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5866     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5867     DAG.setRoot(Res);
5868     return nullptr;
5869   }
5870 
5871   case Intrinsic::init_trampoline: {
5872     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5873 
5874     SDValue Ops[6];
5875     Ops[0] = getRoot();
5876     Ops[1] = getValue(I.getArgOperand(0));
5877     Ops[2] = getValue(I.getArgOperand(1));
5878     Ops[3] = getValue(I.getArgOperand(2));
5879     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5880     Ops[5] = DAG.getSrcValue(F);
5881 
5882     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5883 
5884     DAG.setRoot(Res);
5885     return nullptr;
5886   }
5887   case Intrinsic::adjust_trampoline:
5888     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5889                              TLI.getPointerTy(DAG.getDataLayout()),
5890                              getValue(I.getArgOperand(0))));
5891     return nullptr;
5892   case Intrinsic::gcroot: {
5893     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5894            "only valid in functions with gc specified, enforced by Verifier");
5895     assert(GFI && "implied by previous");
5896     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5897     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5898 
5899     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5900     GFI->addStackRoot(FI->getIndex(), TypeMap);
5901     return nullptr;
5902   }
5903   case Intrinsic::gcread:
5904   case Intrinsic::gcwrite:
5905     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5906   case Intrinsic::flt_rounds:
5907     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5908     return nullptr;
5909 
5910   case Intrinsic::expect:
5911     // Just replace __builtin_expect(exp, c) with EXP.
5912     setValue(&I, getValue(I.getArgOperand(0)));
5913     return nullptr;
5914 
5915   case Intrinsic::debugtrap:
5916   case Intrinsic::trap: {
5917     StringRef TrapFuncName =
5918         I.getAttributes()
5919             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5920             .getValueAsString();
5921     if (TrapFuncName.empty()) {
5922       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5923         ISD::TRAP : ISD::DEBUGTRAP;
5924       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5925       return nullptr;
5926     }
5927     TargetLowering::ArgListTy Args;
5928 
5929     TargetLowering::CallLoweringInfo CLI(DAG);
5930     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5931         CallingConv::C, I.getType(),
5932         DAG.getExternalSymbol(TrapFuncName.data(),
5933                               TLI.getPointerTy(DAG.getDataLayout())),
5934         std::move(Args));
5935 
5936     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5937     DAG.setRoot(Result.second);
5938     return nullptr;
5939   }
5940 
5941   case Intrinsic::uadd_with_overflow:
5942   case Intrinsic::sadd_with_overflow:
5943   case Intrinsic::usub_with_overflow:
5944   case Intrinsic::ssub_with_overflow:
5945   case Intrinsic::umul_with_overflow:
5946   case Intrinsic::smul_with_overflow: {
5947     ISD::NodeType Op;
5948     switch (Intrinsic) {
5949     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5950     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5951     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5952     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5953     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5954     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5955     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5956     }
5957     SDValue Op1 = getValue(I.getArgOperand(0));
5958     SDValue Op2 = getValue(I.getArgOperand(1));
5959 
5960     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5961     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5962     return nullptr;
5963   }
5964   case Intrinsic::prefetch: {
5965     SDValue Ops[5];
5966     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5967     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5968     Ops[0] = DAG.getRoot();
5969     Ops[1] = getValue(I.getArgOperand(0));
5970     Ops[2] = getValue(I.getArgOperand(1));
5971     Ops[3] = getValue(I.getArgOperand(2));
5972     Ops[4] = getValue(I.getArgOperand(3));
5973     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5974                                              DAG.getVTList(MVT::Other), Ops,
5975                                              EVT::getIntegerVT(*Context, 8),
5976                                              MachinePointerInfo(I.getArgOperand(0)),
5977                                              0, /* align */
5978                                              Flags);
5979 
5980     // Chain the prefetch in parallell with any pending loads, to stay out of
5981     // the way of later optimizations.
5982     PendingLoads.push_back(Result);
5983     Result = getRoot();
5984     DAG.setRoot(Result);
5985     return nullptr;
5986   }
5987   case Intrinsic::lifetime_start:
5988   case Intrinsic::lifetime_end: {
5989     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5990     // Stack coloring is not enabled in O0, discard region information.
5991     if (TM.getOptLevel() == CodeGenOpt::None)
5992       return nullptr;
5993 
5994     SmallVector<Value *, 4> Allocas;
5995     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5996 
5997     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5998            E = Allocas.end(); Object != E; ++Object) {
5999       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6000 
6001       // Could not find an Alloca.
6002       if (!LifetimeObject)
6003         continue;
6004 
6005       // First check that the Alloca is static, otherwise it won't have a
6006       // valid frame index.
6007       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6008       if (SI == FuncInfo.StaticAllocaMap.end())
6009         return nullptr;
6010 
6011       int FI = SI->second;
6012 
6013       SDValue Ops[2];
6014       Ops[0] = getRoot();
6015       Ops[1] =
6016           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6017       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6018 
6019       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6020       DAG.setRoot(Res);
6021     }
6022     return nullptr;
6023   }
6024   case Intrinsic::invariant_start:
6025     // Discard region information.
6026     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6027     return nullptr;
6028   case Intrinsic::invariant_end:
6029     // Discard region information.
6030     return nullptr;
6031   case Intrinsic::clear_cache:
6032     return TLI.getClearCacheBuiltinName();
6033   case Intrinsic::donothing:
6034     // ignore
6035     return nullptr;
6036   case Intrinsic::experimental_stackmap:
6037     visitStackmap(I);
6038     return nullptr;
6039   case Intrinsic::experimental_patchpoint_void:
6040   case Intrinsic::experimental_patchpoint_i64:
6041     visitPatchpoint(&I);
6042     return nullptr;
6043   case Intrinsic::experimental_gc_statepoint:
6044     LowerStatepoint(ImmutableStatepoint(&I));
6045     return nullptr;
6046   case Intrinsic::experimental_gc_result:
6047     visitGCResult(cast<GCResultInst>(I));
6048     return nullptr;
6049   case Intrinsic::experimental_gc_relocate:
6050     visitGCRelocate(cast<GCRelocateInst>(I));
6051     return nullptr;
6052   case Intrinsic::instrprof_increment:
6053     llvm_unreachable("instrprof failed to lower an increment");
6054   case Intrinsic::instrprof_value_profile:
6055     llvm_unreachable("instrprof failed to lower a value profiling call");
6056   case Intrinsic::localescape: {
6057     MachineFunction &MF = DAG.getMachineFunction();
6058     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6059 
6060     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6061     // is the same on all targets.
6062     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6063       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6064       if (isa<ConstantPointerNull>(Arg))
6065         continue; // Skip null pointers. They represent a hole in index space.
6066       AllocaInst *Slot = cast<AllocaInst>(Arg);
6067       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6068              "can only escape static allocas");
6069       int FI = FuncInfo.StaticAllocaMap[Slot];
6070       MCSymbol *FrameAllocSym =
6071           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6072               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6073       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6074               TII->get(TargetOpcode::LOCAL_ESCAPE))
6075           .addSym(FrameAllocSym)
6076           .addFrameIndex(FI);
6077     }
6078 
6079     return nullptr;
6080   }
6081 
6082   case Intrinsic::localrecover: {
6083     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6084     MachineFunction &MF = DAG.getMachineFunction();
6085     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6086 
6087     // Get the symbol that defines the frame offset.
6088     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6089     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6090     unsigned IdxVal =
6091         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6092     MCSymbol *FrameAllocSym =
6093         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6094             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6095 
6096     // Create a MCSymbol for the label to avoid any target lowering
6097     // that would make this PC relative.
6098     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6099     SDValue OffsetVal =
6100         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6101 
6102     // Add the offset to the FP.
6103     Value *FP = I.getArgOperand(1);
6104     SDValue FPVal = getValue(FP);
6105     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6106     setValue(&I, Add);
6107 
6108     return nullptr;
6109   }
6110 
6111   case Intrinsic::eh_exceptionpointer:
6112   case Intrinsic::eh_exceptioncode: {
6113     // Get the exception pointer vreg, copy from it, and resize it to fit.
6114     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6115     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6116     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6117     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6118     SDValue N =
6119         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6120     if (Intrinsic == Intrinsic::eh_exceptioncode)
6121       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6122     setValue(&I, N);
6123     return nullptr;
6124   }
6125   case Intrinsic::xray_customevent: {
6126     // Here we want to make sure that the intrinsic behaves as if it has a
6127     // specific calling convention, and only for x86_64.
6128     // FIXME: Support other platforms later.
6129     const auto &Triple = DAG.getTarget().getTargetTriple();
6130     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6131       return nullptr;
6132 
6133     SDLoc DL = getCurSDLoc();
6134     SmallVector<SDValue, 8> Ops;
6135 
6136     // We want to say that we always want the arguments in registers.
6137     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6138     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6139     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6140     SDValue Chain = getRoot();
6141     Ops.push_back(LogEntryVal);
6142     Ops.push_back(StrSizeVal);
6143     Ops.push_back(Chain);
6144 
6145     // We need to enforce the calling convention for the callsite, so that
6146     // argument ordering is enforced correctly, and that register allocation can
6147     // see that some registers may be assumed clobbered and have to preserve
6148     // them across calls to the intrinsic.
6149     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6150                                            DL, NodeTys, Ops);
6151     SDValue patchableNode = SDValue(MN, 0);
6152     DAG.setRoot(patchableNode);
6153     setValue(&I, patchableNode);
6154     return nullptr;
6155   }
6156   case Intrinsic::xray_typedevent: {
6157     // Here we want to make sure that the intrinsic behaves as if it has a
6158     // specific calling convention, and only for x86_64.
6159     // FIXME: Support other platforms later.
6160     const auto &Triple = DAG.getTarget().getTargetTriple();
6161     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6162       return nullptr;
6163 
6164     SDLoc DL = getCurSDLoc();
6165     SmallVector<SDValue, 8> Ops;
6166 
6167     // We want to say that we always want the arguments in registers.
6168     // It's unclear to me how manipulating the selection DAG here forces callers
6169     // to provide arguments in registers instead of on the stack.
6170     SDValue LogTypeId = getValue(I.getArgOperand(0));
6171     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6172     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6173     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6174     SDValue Chain = getRoot();
6175     Ops.push_back(LogTypeId);
6176     Ops.push_back(LogEntryVal);
6177     Ops.push_back(StrSizeVal);
6178     Ops.push_back(Chain);
6179 
6180     // We need to enforce the calling convention for the callsite, so that
6181     // argument ordering is enforced correctly, and that register allocation can
6182     // see that some registers may be assumed clobbered and have to preserve
6183     // them across calls to the intrinsic.
6184     MachineSDNode *MN = DAG.getMachineNode(
6185         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6186     SDValue patchableNode = SDValue(MN, 0);
6187     DAG.setRoot(patchableNode);
6188     setValue(&I, patchableNode);
6189     return nullptr;
6190   }
6191   case Intrinsic::experimental_deoptimize:
6192     LowerDeoptimizeCall(&I);
6193     return nullptr;
6194 
6195   case Intrinsic::experimental_vector_reduce_fadd:
6196   case Intrinsic::experimental_vector_reduce_fmul:
6197   case Intrinsic::experimental_vector_reduce_add:
6198   case Intrinsic::experimental_vector_reduce_mul:
6199   case Intrinsic::experimental_vector_reduce_and:
6200   case Intrinsic::experimental_vector_reduce_or:
6201   case Intrinsic::experimental_vector_reduce_xor:
6202   case Intrinsic::experimental_vector_reduce_smax:
6203   case Intrinsic::experimental_vector_reduce_smin:
6204   case Intrinsic::experimental_vector_reduce_umax:
6205   case Intrinsic::experimental_vector_reduce_umin:
6206   case Intrinsic::experimental_vector_reduce_fmax:
6207   case Intrinsic::experimental_vector_reduce_fmin:
6208     visitVectorReduce(I, Intrinsic);
6209     return nullptr;
6210 
6211   case Intrinsic::icall_branch_funnel: {
6212     SmallVector<SDValue, 16> Ops;
6213     Ops.push_back(DAG.getRoot());
6214     Ops.push_back(getValue(I.getArgOperand(0)));
6215 
6216     int64_t Offset;
6217     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6218         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6219     if (!Base)
6220       report_fatal_error(
6221           "llvm.icall.branch.funnel operand must be a GlobalValue");
6222     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6223 
6224     struct BranchFunnelTarget {
6225       int64_t Offset;
6226       SDValue Target;
6227     };
6228     SmallVector<BranchFunnelTarget, 8> Targets;
6229 
6230     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6231       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6232           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6233       if (ElemBase != Base)
6234         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6235                            "to the same GlobalValue");
6236 
6237       SDValue Val = getValue(I.getArgOperand(Op + 1));
6238       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6239       if (!GA)
6240         report_fatal_error(
6241             "llvm.icall.branch.funnel operand must be a GlobalValue");
6242       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6243                                      GA->getGlobal(), getCurSDLoc(),
6244                                      Val.getValueType(), GA->getOffset())});
6245     }
6246     llvm::sort(Targets.begin(), Targets.end(),
6247                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6248                  return T1.Offset < T2.Offset;
6249                });
6250 
6251     for (auto &T : Targets) {
6252       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6253       Ops.push_back(T.Target);
6254     }
6255 
6256     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6257                                  getCurSDLoc(), MVT::Other, Ops),
6258               0);
6259     DAG.setRoot(N);
6260     setValue(&I, N);
6261     HasTailCall = true;
6262     return nullptr;
6263   }
6264 
6265   case Intrinsic::wasm_landingpad_index: {
6266     // TODO store landing pad index in a map, which will be used when generating
6267     // LSDA information
6268     return nullptr;
6269   }
6270   }
6271 }
6272 
6273 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6274     const ConstrainedFPIntrinsic &FPI) {
6275   SDLoc sdl = getCurSDLoc();
6276   unsigned Opcode;
6277   switch (FPI.getIntrinsicID()) {
6278   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6279   case Intrinsic::experimental_constrained_fadd:
6280     Opcode = ISD::STRICT_FADD;
6281     break;
6282   case Intrinsic::experimental_constrained_fsub:
6283     Opcode = ISD::STRICT_FSUB;
6284     break;
6285   case Intrinsic::experimental_constrained_fmul:
6286     Opcode = ISD::STRICT_FMUL;
6287     break;
6288   case Intrinsic::experimental_constrained_fdiv:
6289     Opcode = ISD::STRICT_FDIV;
6290     break;
6291   case Intrinsic::experimental_constrained_frem:
6292     Opcode = ISD::STRICT_FREM;
6293     break;
6294   case Intrinsic::experimental_constrained_fma:
6295     Opcode = ISD::STRICT_FMA;
6296     break;
6297   case Intrinsic::experimental_constrained_sqrt:
6298     Opcode = ISD::STRICT_FSQRT;
6299     break;
6300   case Intrinsic::experimental_constrained_pow:
6301     Opcode = ISD::STRICT_FPOW;
6302     break;
6303   case Intrinsic::experimental_constrained_powi:
6304     Opcode = ISD::STRICT_FPOWI;
6305     break;
6306   case Intrinsic::experimental_constrained_sin:
6307     Opcode = ISD::STRICT_FSIN;
6308     break;
6309   case Intrinsic::experimental_constrained_cos:
6310     Opcode = ISD::STRICT_FCOS;
6311     break;
6312   case Intrinsic::experimental_constrained_exp:
6313     Opcode = ISD::STRICT_FEXP;
6314     break;
6315   case Intrinsic::experimental_constrained_exp2:
6316     Opcode = ISD::STRICT_FEXP2;
6317     break;
6318   case Intrinsic::experimental_constrained_log:
6319     Opcode = ISD::STRICT_FLOG;
6320     break;
6321   case Intrinsic::experimental_constrained_log10:
6322     Opcode = ISD::STRICT_FLOG10;
6323     break;
6324   case Intrinsic::experimental_constrained_log2:
6325     Opcode = ISD::STRICT_FLOG2;
6326     break;
6327   case Intrinsic::experimental_constrained_rint:
6328     Opcode = ISD::STRICT_FRINT;
6329     break;
6330   case Intrinsic::experimental_constrained_nearbyint:
6331     Opcode = ISD::STRICT_FNEARBYINT;
6332     break;
6333   }
6334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6335   SDValue Chain = getRoot();
6336   SmallVector<EVT, 4> ValueVTs;
6337   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6338   ValueVTs.push_back(MVT::Other); // Out chain
6339 
6340   SDVTList VTs = DAG.getVTList(ValueVTs);
6341   SDValue Result;
6342   if (FPI.isUnaryOp())
6343     Result = DAG.getNode(Opcode, sdl, VTs,
6344                          { Chain, getValue(FPI.getArgOperand(0)) });
6345   else if (FPI.isTernaryOp())
6346     Result = DAG.getNode(Opcode, sdl, VTs,
6347                          { Chain, getValue(FPI.getArgOperand(0)),
6348                                   getValue(FPI.getArgOperand(1)),
6349                                   getValue(FPI.getArgOperand(2)) });
6350   else
6351     Result = DAG.getNode(Opcode, sdl, VTs,
6352                          { Chain, getValue(FPI.getArgOperand(0)),
6353                            getValue(FPI.getArgOperand(1))  });
6354 
6355   assert(Result.getNode()->getNumValues() == 2);
6356   SDValue OutChain = Result.getValue(1);
6357   DAG.setRoot(OutChain);
6358   SDValue FPResult = Result.getValue(0);
6359   setValue(&FPI, FPResult);
6360 }
6361 
6362 std::pair<SDValue, SDValue>
6363 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6364                                     const BasicBlock *EHPadBB) {
6365   MachineFunction &MF = DAG.getMachineFunction();
6366   MachineModuleInfo &MMI = MF.getMMI();
6367   MCSymbol *BeginLabel = nullptr;
6368 
6369   if (EHPadBB) {
6370     // Insert a label before the invoke call to mark the try range.  This can be
6371     // used to detect deletion of the invoke via the MachineModuleInfo.
6372     BeginLabel = MMI.getContext().createTempSymbol();
6373 
6374     // For SjLj, keep track of which landing pads go with which invokes
6375     // so as to maintain the ordering of pads in the LSDA.
6376     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6377     if (CallSiteIndex) {
6378       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6379       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6380 
6381       // Now that the call site is handled, stop tracking it.
6382       MMI.setCurrentCallSite(0);
6383     }
6384 
6385     // Both PendingLoads and PendingExports must be flushed here;
6386     // this call might not return.
6387     (void)getRoot();
6388     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6389 
6390     CLI.setChain(getRoot());
6391   }
6392   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6393   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6394 
6395   assert((CLI.IsTailCall || Result.second.getNode()) &&
6396          "Non-null chain expected with non-tail call!");
6397   assert((Result.second.getNode() || !Result.first.getNode()) &&
6398          "Null value expected with tail call!");
6399 
6400   if (!Result.second.getNode()) {
6401     // As a special case, a null chain means that a tail call has been emitted
6402     // and the DAG root is already updated.
6403     HasTailCall = true;
6404 
6405     // Since there's no actual continuation from this block, nothing can be
6406     // relying on us setting vregs for them.
6407     PendingExports.clear();
6408   } else {
6409     DAG.setRoot(Result.second);
6410   }
6411 
6412   if (EHPadBB) {
6413     // Insert a label at the end of the invoke call to mark the try range.  This
6414     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6415     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6416     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6417 
6418     // Inform MachineModuleInfo of range.
6419     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6420     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6421     // actually use outlined funclets and their LSDA info style.
6422     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6423       assert(CLI.CS);
6424       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6425       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6426                                 BeginLabel, EndLabel);
6427     } else {
6428       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6429     }
6430   }
6431 
6432   return Result;
6433 }
6434 
6435 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6436                                       bool isTailCall,
6437                                       const BasicBlock *EHPadBB) {
6438   auto &DL = DAG.getDataLayout();
6439   FunctionType *FTy = CS.getFunctionType();
6440   Type *RetTy = CS.getType();
6441 
6442   TargetLowering::ArgListTy Args;
6443   Args.reserve(CS.arg_size());
6444 
6445   const Value *SwiftErrorVal = nullptr;
6446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6447 
6448   // We can't tail call inside a function with a swifterror argument. Lowering
6449   // does not support this yet. It would have to move into the swifterror
6450   // register before the call.
6451   auto *Caller = CS.getInstruction()->getParent()->getParent();
6452   if (TLI.supportSwiftError() &&
6453       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6454     isTailCall = false;
6455 
6456   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6457        i != e; ++i) {
6458     TargetLowering::ArgListEntry Entry;
6459     const Value *V = *i;
6460 
6461     // Skip empty types
6462     if (V->getType()->isEmptyTy())
6463       continue;
6464 
6465     SDValue ArgNode = getValue(V);
6466     Entry.Node = ArgNode; Entry.Ty = V->getType();
6467 
6468     Entry.setAttributes(&CS, i - CS.arg_begin());
6469 
6470     // Use swifterror virtual register as input to the call.
6471     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6472       SwiftErrorVal = V;
6473       // We find the virtual register for the actual swifterror argument.
6474       // Instead of using the Value, we use the virtual register instead.
6475       Entry.Node = DAG.getRegister(FuncInfo
6476                                        .getOrCreateSwiftErrorVRegUseAt(
6477                                            CS.getInstruction(), FuncInfo.MBB, V)
6478                                        .first,
6479                                    EVT(TLI.getPointerTy(DL)));
6480     }
6481 
6482     Args.push_back(Entry);
6483 
6484     // If we have an explicit sret argument that is an Instruction, (i.e., it
6485     // might point to function-local memory), we can't meaningfully tail-call.
6486     if (Entry.IsSRet && isa<Instruction>(V))
6487       isTailCall = false;
6488   }
6489 
6490   // Check if target-independent constraints permit a tail call here.
6491   // Target-dependent constraints are checked within TLI->LowerCallTo.
6492   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6493     isTailCall = false;
6494 
6495   // Disable tail calls if there is an swifterror argument. Targets have not
6496   // been updated to support tail calls.
6497   if (TLI.supportSwiftError() && SwiftErrorVal)
6498     isTailCall = false;
6499 
6500   TargetLowering::CallLoweringInfo CLI(DAG);
6501   CLI.setDebugLoc(getCurSDLoc())
6502       .setChain(getRoot())
6503       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6504       .setTailCall(isTailCall)
6505       .setConvergent(CS.isConvergent());
6506   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6507 
6508   if (Result.first.getNode()) {
6509     const Instruction *Inst = CS.getInstruction();
6510     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6511     setValue(Inst, Result.first);
6512   }
6513 
6514   // The last element of CLI.InVals has the SDValue for swifterror return.
6515   // Here we copy it to a virtual register and update SwiftErrorMap for
6516   // book-keeping.
6517   if (SwiftErrorVal && TLI.supportSwiftError()) {
6518     // Get the last element of InVals.
6519     SDValue Src = CLI.InVals.back();
6520     unsigned VReg; bool CreatedVReg;
6521     std::tie(VReg, CreatedVReg) =
6522         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6523     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6524     // We update the virtual register for the actual swifterror argument.
6525     if (CreatedVReg)
6526       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6527     DAG.setRoot(CopyNode);
6528   }
6529 }
6530 
6531 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6532                              SelectionDAGBuilder &Builder) {
6533   // Check to see if this load can be trivially constant folded, e.g. if the
6534   // input is from a string literal.
6535   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6536     // Cast pointer to the type we really want to load.
6537     Type *LoadTy =
6538         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6539     if (LoadVT.isVector())
6540       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6541 
6542     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6543                                          PointerType::getUnqual(LoadTy));
6544 
6545     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6546             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6547       return Builder.getValue(LoadCst);
6548   }
6549 
6550   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6551   // still constant memory, the input chain can be the entry node.
6552   SDValue Root;
6553   bool ConstantMemory = false;
6554 
6555   // Do not serialize (non-volatile) loads of constant memory with anything.
6556   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6557     Root = Builder.DAG.getEntryNode();
6558     ConstantMemory = true;
6559   } else {
6560     // Do not serialize non-volatile loads against each other.
6561     Root = Builder.DAG.getRoot();
6562   }
6563 
6564   SDValue Ptr = Builder.getValue(PtrVal);
6565   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6566                                         Ptr, MachinePointerInfo(PtrVal),
6567                                         /* Alignment = */ 1);
6568 
6569   if (!ConstantMemory)
6570     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6571   return LoadVal;
6572 }
6573 
6574 /// Record the value for an instruction that produces an integer result,
6575 /// converting the type where necessary.
6576 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6577                                                   SDValue Value,
6578                                                   bool IsSigned) {
6579   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6580                                                     I.getType(), true);
6581   if (IsSigned)
6582     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6583   else
6584     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6585   setValue(&I, Value);
6586 }
6587 
6588 /// See if we can lower a memcmp call into an optimized form. If so, return
6589 /// true and lower it. Otherwise return false, and it will be lowered like a
6590 /// normal call.
6591 /// The caller already checked that \p I calls the appropriate LibFunc with a
6592 /// correct prototype.
6593 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6594   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6595   const Value *Size = I.getArgOperand(2);
6596   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6597   if (CSize && CSize->getZExtValue() == 0) {
6598     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6599                                                           I.getType(), true);
6600     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6601     return true;
6602   }
6603 
6604   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6605   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6606       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6607       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6608   if (Res.first.getNode()) {
6609     processIntegerCallValue(I, Res.first, true);
6610     PendingLoads.push_back(Res.second);
6611     return true;
6612   }
6613 
6614   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6615   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6616   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6617     return false;
6618 
6619   // If the target has a fast compare for the given size, it will return a
6620   // preferred load type for that size. Require that the load VT is legal and
6621   // that the target supports unaligned loads of that type. Otherwise, return
6622   // INVALID.
6623   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6624     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6625     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6626     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6627       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6628       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6629       // TODO: Check alignment of src and dest ptrs.
6630       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6631       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6632       if (!TLI.isTypeLegal(LVT) ||
6633           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6634           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6635         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6636     }
6637 
6638     return LVT;
6639   };
6640 
6641   // This turns into unaligned loads. We only do this if the target natively
6642   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6643   // we'll only produce a small number of byte loads.
6644   MVT LoadVT;
6645   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6646   switch (NumBitsToCompare) {
6647   default:
6648     return false;
6649   case 16:
6650     LoadVT = MVT::i16;
6651     break;
6652   case 32:
6653     LoadVT = MVT::i32;
6654     break;
6655   case 64:
6656   case 128:
6657   case 256:
6658     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6659     break;
6660   }
6661 
6662   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6663     return false;
6664 
6665   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6666   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6667 
6668   // Bitcast to a wide integer type if the loads are vectors.
6669   if (LoadVT.isVector()) {
6670     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6671     LoadL = DAG.getBitcast(CmpVT, LoadL);
6672     LoadR = DAG.getBitcast(CmpVT, LoadR);
6673   }
6674 
6675   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6676   processIntegerCallValue(I, Cmp, false);
6677   return true;
6678 }
6679 
6680 /// See if we can lower a memchr call into an optimized form. If so, return
6681 /// true and lower it. Otherwise return false, and it will be lowered like a
6682 /// normal call.
6683 /// The caller already checked that \p I calls the appropriate LibFunc with a
6684 /// correct prototype.
6685 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6686   const Value *Src = I.getArgOperand(0);
6687   const Value *Char = I.getArgOperand(1);
6688   const Value *Length = I.getArgOperand(2);
6689 
6690   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6691   std::pair<SDValue, SDValue> Res =
6692     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6693                                 getValue(Src), getValue(Char), getValue(Length),
6694                                 MachinePointerInfo(Src));
6695   if (Res.first.getNode()) {
6696     setValue(&I, Res.first);
6697     PendingLoads.push_back(Res.second);
6698     return true;
6699   }
6700 
6701   return false;
6702 }
6703 
6704 /// See if we can lower a mempcpy call into an optimized form. If so, return
6705 /// true and lower it. Otherwise return false, and it will be lowered like a
6706 /// normal call.
6707 /// The caller already checked that \p I calls the appropriate LibFunc with a
6708 /// correct prototype.
6709 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6710   SDValue Dst = getValue(I.getArgOperand(0));
6711   SDValue Src = getValue(I.getArgOperand(1));
6712   SDValue Size = getValue(I.getArgOperand(2));
6713 
6714   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6715   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6716   unsigned Align = std::min(DstAlign, SrcAlign);
6717   if (Align == 0) // Alignment of one or both could not be inferred.
6718     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6719 
6720   bool isVol = false;
6721   SDLoc sdl = getCurSDLoc();
6722 
6723   // In the mempcpy context we need to pass in a false value for isTailCall
6724   // because the return pointer needs to be adjusted by the size of
6725   // the copied memory.
6726   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6727                              false, /*isTailCall=*/false,
6728                              MachinePointerInfo(I.getArgOperand(0)),
6729                              MachinePointerInfo(I.getArgOperand(1)));
6730   assert(MC.getNode() != nullptr &&
6731          "** memcpy should not be lowered as TailCall in mempcpy context **");
6732   DAG.setRoot(MC);
6733 
6734   // Check if Size needs to be truncated or extended.
6735   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6736 
6737   // Adjust return pointer to point just past the last dst byte.
6738   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6739                                     Dst, Size);
6740   setValue(&I, DstPlusSize);
6741   return true;
6742 }
6743 
6744 /// See if we can lower a strcpy call into an optimized form.  If so, return
6745 /// true and lower it, otherwise return false and it will be lowered like a
6746 /// normal call.
6747 /// The caller already checked that \p I calls the appropriate LibFunc with a
6748 /// correct prototype.
6749 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6750   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6751 
6752   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6753   std::pair<SDValue, SDValue> Res =
6754     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6755                                 getValue(Arg0), getValue(Arg1),
6756                                 MachinePointerInfo(Arg0),
6757                                 MachinePointerInfo(Arg1), isStpcpy);
6758   if (Res.first.getNode()) {
6759     setValue(&I, Res.first);
6760     DAG.setRoot(Res.second);
6761     return true;
6762   }
6763 
6764   return false;
6765 }
6766 
6767 /// See if we can lower a strcmp call into an optimized form.  If so, return
6768 /// true and lower it, otherwise return false and it will be lowered like a
6769 /// normal call.
6770 /// The caller already checked that \p I calls the appropriate LibFunc with a
6771 /// correct prototype.
6772 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6773   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6774 
6775   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6776   std::pair<SDValue, SDValue> Res =
6777     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6778                                 getValue(Arg0), getValue(Arg1),
6779                                 MachinePointerInfo(Arg0),
6780                                 MachinePointerInfo(Arg1));
6781   if (Res.first.getNode()) {
6782     processIntegerCallValue(I, Res.first, true);
6783     PendingLoads.push_back(Res.second);
6784     return true;
6785   }
6786 
6787   return false;
6788 }
6789 
6790 /// See if we can lower a strlen call into an optimized form.  If so, return
6791 /// true and lower it, otherwise return false and it will be lowered like a
6792 /// normal call.
6793 /// The caller already checked that \p I calls the appropriate LibFunc with a
6794 /// correct prototype.
6795 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6796   const Value *Arg0 = I.getArgOperand(0);
6797 
6798   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6799   std::pair<SDValue, SDValue> Res =
6800     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6801                                 getValue(Arg0), MachinePointerInfo(Arg0));
6802   if (Res.first.getNode()) {
6803     processIntegerCallValue(I, Res.first, false);
6804     PendingLoads.push_back(Res.second);
6805     return true;
6806   }
6807 
6808   return false;
6809 }
6810 
6811 /// See if we can lower a strnlen call into an optimized form.  If so, return
6812 /// true and lower it, otherwise return false and it will be lowered like a
6813 /// normal call.
6814 /// The caller already checked that \p I calls the appropriate LibFunc with a
6815 /// correct prototype.
6816 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6817   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6818 
6819   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6820   std::pair<SDValue, SDValue> Res =
6821     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6822                                  getValue(Arg0), getValue(Arg1),
6823                                  MachinePointerInfo(Arg0));
6824   if (Res.first.getNode()) {
6825     processIntegerCallValue(I, Res.first, false);
6826     PendingLoads.push_back(Res.second);
6827     return true;
6828   }
6829 
6830   return false;
6831 }
6832 
6833 /// See if we can lower a unary floating-point operation into an SDNode with
6834 /// the specified Opcode.  If so, return true and lower it, otherwise return
6835 /// false and it will be lowered like a normal call.
6836 /// The caller already checked that \p I calls the appropriate LibFunc with a
6837 /// correct prototype.
6838 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6839                                               unsigned Opcode) {
6840   // We already checked this call's prototype; verify it doesn't modify errno.
6841   if (!I.onlyReadsMemory())
6842     return false;
6843 
6844   SDValue Tmp = getValue(I.getArgOperand(0));
6845   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6846   return true;
6847 }
6848 
6849 /// See if we can lower a binary floating-point operation into an SDNode with
6850 /// the specified Opcode. If so, return true and lower it. Otherwise return
6851 /// false, and it will be lowered like a normal call.
6852 /// The caller already checked that \p I calls the appropriate LibFunc with a
6853 /// correct prototype.
6854 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6855                                                unsigned Opcode) {
6856   // We already checked this call's prototype; verify it doesn't modify errno.
6857   if (!I.onlyReadsMemory())
6858     return false;
6859 
6860   SDValue Tmp0 = getValue(I.getArgOperand(0));
6861   SDValue Tmp1 = getValue(I.getArgOperand(1));
6862   EVT VT = Tmp0.getValueType();
6863   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6864   return true;
6865 }
6866 
6867 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6868   // Handle inline assembly differently.
6869   if (isa<InlineAsm>(I.getCalledValue())) {
6870     visitInlineAsm(&I);
6871     return;
6872   }
6873 
6874   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6875   computeUsesVAFloatArgument(I, MMI);
6876 
6877   const char *RenameFn = nullptr;
6878   if (Function *F = I.getCalledFunction()) {
6879     if (F->isDeclaration()) {
6880       // Is this an LLVM intrinsic or a target-specific intrinsic?
6881       unsigned IID = F->getIntrinsicID();
6882       if (!IID)
6883         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6884           IID = II->getIntrinsicID(F);
6885 
6886       if (IID) {
6887         RenameFn = visitIntrinsicCall(I, IID);
6888         if (!RenameFn)
6889           return;
6890       }
6891     }
6892 
6893     // Check for well-known libc/libm calls.  If the function is internal, it
6894     // can't be a library call.  Don't do the check if marked as nobuiltin for
6895     // some reason or the call site requires strict floating point semantics.
6896     LibFunc Func;
6897     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6898         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6899         LibInfo->hasOptimizedCodeGen(Func)) {
6900       switch (Func) {
6901       default: break;
6902       case LibFunc_copysign:
6903       case LibFunc_copysignf:
6904       case LibFunc_copysignl:
6905         // We already checked this call's prototype; verify it doesn't modify
6906         // errno.
6907         if (I.onlyReadsMemory()) {
6908           SDValue LHS = getValue(I.getArgOperand(0));
6909           SDValue RHS = getValue(I.getArgOperand(1));
6910           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6911                                    LHS.getValueType(), LHS, RHS));
6912           return;
6913         }
6914         break;
6915       case LibFunc_fabs:
6916       case LibFunc_fabsf:
6917       case LibFunc_fabsl:
6918         if (visitUnaryFloatCall(I, ISD::FABS))
6919           return;
6920         break;
6921       case LibFunc_fmin:
6922       case LibFunc_fminf:
6923       case LibFunc_fminl:
6924         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6925           return;
6926         break;
6927       case LibFunc_fmax:
6928       case LibFunc_fmaxf:
6929       case LibFunc_fmaxl:
6930         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6931           return;
6932         break;
6933       case LibFunc_sin:
6934       case LibFunc_sinf:
6935       case LibFunc_sinl:
6936         if (visitUnaryFloatCall(I, ISD::FSIN))
6937           return;
6938         break;
6939       case LibFunc_cos:
6940       case LibFunc_cosf:
6941       case LibFunc_cosl:
6942         if (visitUnaryFloatCall(I, ISD::FCOS))
6943           return;
6944         break;
6945       case LibFunc_sqrt:
6946       case LibFunc_sqrtf:
6947       case LibFunc_sqrtl:
6948       case LibFunc_sqrt_finite:
6949       case LibFunc_sqrtf_finite:
6950       case LibFunc_sqrtl_finite:
6951         if (visitUnaryFloatCall(I, ISD::FSQRT))
6952           return;
6953         break;
6954       case LibFunc_floor:
6955       case LibFunc_floorf:
6956       case LibFunc_floorl:
6957         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6958           return;
6959         break;
6960       case LibFunc_nearbyint:
6961       case LibFunc_nearbyintf:
6962       case LibFunc_nearbyintl:
6963         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6964           return;
6965         break;
6966       case LibFunc_ceil:
6967       case LibFunc_ceilf:
6968       case LibFunc_ceill:
6969         if (visitUnaryFloatCall(I, ISD::FCEIL))
6970           return;
6971         break;
6972       case LibFunc_rint:
6973       case LibFunc_rintf:
6974       case LibFunc_rintl:
6975         if (visitUnaryFloatCall(I, ISD::FRINT))
6976           return;
6977         break;
6978       case LibFunc_round:
6979       case LibFunc_roundf:
6980       case LibFunc_roundl:
6981         if (visitUnaryFloatCall(I, ISD::FROUND))
6982           return;
6983         break;
6984       case LibFunc_trunc:
6985       case LibFunc_truncf:
6986       case LibFunc_truncl:
6987         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6988           return;
6989         break;
6990       case LibFunc_log2:
6991       case LibFunc_log2f:
6992       case LibFunc_log2l:
6993         if (visitUnaryFloatCall(I, ISD::FLOG2))
6994           return;
6995         break;
6996       case LibFunc_exp2:
6997       case LibFunc_exp2f:
6998       case LibFunc_exp2l:
6999         if (visitUnaryFloatCall(I, ISD::FEXP2))
7000           return;
7001         break;
7002       case LibFunc_memcmp:
7003         if (visitMemCmpCall(I))
7004           return;
7005         break;
7006       case LibFunc_mempcpy:
7007         if (visitMemPCpyCall(I))
7008           return;
7009         break;
7010       case LibFunc_memchr:
7011         if (visitMemChrCall(I))
7012           return;
7013         break;
7014       case LibFunc_strcpy:
7015         if (visitStrCpyCall(I, false))
7016           return;
7017         break;
7018       case LibFunc_stpcpy:
7019         if (visitStrCpyCall(I, true))
7020           return;
7021         break;
7022       case LibFunc_strcmp:
7023         if (visitStrCmpCall(I))
7024           return;
7025         break;
7026       case LibFunc_strlen:
7027         if (visitStrLenCall(I))
7028           return;
7029         break;
7030       case LibFunc_strnlen:
7031         if (visitStrNLenCall(I))
7032           return;
7033         break;
7034       }
7035     }
7036   }
7037 
7038   SDValue Callee;
7039   if (!RenameFn)
7040     Callee = getValue(I.getCalledValue());
7041   else
7042     Callee = DAG.getExternalSymbol(
7043         RenameFn,
7044         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7045 
7046   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7047   // have to do anything here to lower funclet bundles.
7048   assert(!I.hasOperandBundlesOtherThan(
7049              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7050          "Cannot lower calls with arbitrary operand bundles!");
7051 
7052   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7053     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7054   else
7055     // Check if we can potentially perform a tail call. More detailed checking
7056     // is be done within LowerCallTo, after more information about the call is
7057     // known.
7058     LowerCallTo(&I, Callee, I.isTailCall());
7059 }
7060 
7061 namespace {
7062 
7063 /// AsmOperandInfo - This contains information for each constraint that we are
7064 /// lowering.
7065 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7066 public:
7067   /// CallOperand - If this is the result output operand or a clobber
7068   /// this is null, otherwise it is the incoming operand to the CallInst.
7069   /// This gets modified as the asm is processed.
7070   SDValue CallOperand;
7071 
7072   /// AssignedRegs - If this is a register or register class operand, this
7073   /// contains the set of register corresponding to the operand.
7074   RegsForValue AssignedRegs;
7075 
7076   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7077     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7078   }
7079 
7080   /// Whether or not this operand accesses memory
7081   bool hasMemory(const TargetLowering &TLI) const {
7082     // Indirect operand accesses access memory.
7083     if (isIndirect)
7084       return true;
7085 
7086     for (const auto &Code : Codes)
7087       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7088         return true;
7089 
7090     return false;
7091   }
7092 
7093   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7094   /// corresponds to.  If there is no Value* for this operand, it returns
7095   /// MVT::Other.
7096   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7097                            const DataLayout &DL) const {
7098     if (!CallOperandVal) return MVT::Other;
7099 
7100     if (isa<BasicBlock>(CallOperandVal))
7101       return TLI.getPointerTy(DL);
7102 
7103     llvm::Type *OpTy = CallOperandVal->getType();
7104 
7105     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7106     // If this is an indirect operand, the operand is a pointer to the
7107     // accessed type.
7108     if (isIndirect) {
7109       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7110       if (!PtrTy)
7111         report_fatal_error("Indirect operand for inline asm not a pointer!");
7112       OpTy = PtrTy->getElementType();
7113     }
7114 
7115     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7116     if (StructType *STy = dyn_cast<StructType>(OpTy))
7117       if (STy->getNumElements() == 1)
7118         OpTy = STy->getElementType(0);
7119 
7120     // If OpTy is not a single value, it may be a struct/union that we
7121     // can tile with integers.
7122     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7123       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7124       switch (BitSize) {
7125       default: break;
7126       case 1:
7127       case 8:
7128       case 16:
7129       case 32:
7130       case 64:
7131       case 128:
7132         OpTy = IntegerType::get(Context, BitSize);
7133         break;
7134       }
7135     }
7136 
7137     return TLI.getValueType(DL, OpTy, true);
7138   }
7139 };
7140 
7141 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7142 
7143 } // end anonymous namespace
7144 
7145 /// Make sure that the output operand \p OpInfo and its corresponding input
7146 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7147 /// out).
7148 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7149                                SDISelAsmOperandInfo &MatchingOpInfo,
7150                                SelectionDAG &DAG) {
7151   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7152     return;
7153 
7154   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7155   const auto &TLI = DAG.getTargetLoweringInfo();
7156 
7157   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7158       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7159                                        OpInfo.ConstraintVT);
7160   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7161       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7162                                        MatchingOpInfo.ConstraintVT);
7163   if ((OpInfo.ConstraintVT.isInteger() !=
7164        MatchingOpInfo.ConstraintVT.isInteger()) ||
7165       (MatchRC.second != InputRC.second)) {
7166     // FIXME: error out in a more elegant fashion
7167     report_fatal_error("Unsupported asm: input constraint"
7168                        " with a matching output constraint of"
7169                        " incompatible type!");
7170   }
7171   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7172 }
7173 
7174 /// Get a direct memory input to behave well as an indirect operand.
7175 /// This may introduce stores, hence the need for a \p Chain.
7176 /// \return The (possibly updated) chain.
7177 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7178                                         SDISelAsmOperandInfo &OpInfo,
7179                                         SelectionDAG &DAG) {
7180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7181 
7182   // If we don't have an indirect input, put it in the constpool if we can,
7183   // otherwise spill it to a stack slot.
7184   // TODO: This isn't quite right. We need to handle these according to
7185   // the addressing mode that the constraint wants. Also, this may take
7186   // an additional register for the computation and we don't want that
7187   // either.
7188 
7189   // If the operand is a float, integer, or vector constant, spill to a
7190   // constant pool entry to get its address.
7191   const Value *OpVal = OpInfo.CallOperandVal;
7192   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7193       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7194     OpInfo.CallOperand = DAG.getConstantPool(
7195         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7196     return Chain;
7197   }
7198 
7199   // Otherwise, create a stack slot and emit a store to it before the asm.
7200   Type *Ty = OpVal->getType();
7201   auto &DL = DAG.getDataLayout();
7202   uint64_t TySize = DL.getTypeAllocSize(Ty);
7203   unsigned Align = DL.getPrefTypeAlignment(Ty);
7204   MachineFunction &MF = DAG.getMachineFunction();
7205   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7206   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7207   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7208                        MachinePointerInfo::getFixedStack(MF, SSFI));
7209   OpInfo.CallOperand = StackSlot;
7210 
7211   return Chain;
7212 }
7213 
7214 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7215 /// specified operand.  We prefer to assign virtual registers, to allow the
7216 /// register allocator to handle the assignment process.  However, if the asm
7217 /// uses features that we can't model on machineinstrs, we have SDISel do the
7218 /// allocation.  This produces generally horrible, but correct, code.
7219 ///
7220 ///   OpInfo describes the operand
7221 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7222 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7223                                  const SDLoc &DL, SDISelAsmOperandInfo &OpInfo,
7224                                  SDISelAsmOperandInfo &RefOpInfo) {
7225   LLVMContext &Context = *DAG.getContext();
7226 
7227   MachineFunction &MF = DAG.getMachineFunction();
7228   SmallVector<unsigned, 4> Regs;
7229   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7230 
7231   // If this is a constraint for a single physreg, or a constraint for a
7232   // register class, find it.
7233   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7234       TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode,
7235                                        RefOpInfo.ConstraintVT);
7236 
7237   unsigned NumRegs = 1;
7238   if (OpInfo.ConstraintVT != MVT::Other) {
7239     // If this is an FP operand in an integer register (or visa versa), or more
7240     // generally if the operand value disagrees with the register class we plan
7241     // to stick it in, fix the operand type.
7242     //
7243     // If this is an input value, the bitcast to the new type is done now.
7244     // Bitcast for output value is done at the end of visitInlineAsm().
7245     if ((OpInfo.Type == InlineAsm::isOutput ||
7246          OpInfo.Type == InlineAsm::isInput) &&
7247         PhysReg.second &&
7248         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7249       // Try to convert to the first EVT that the reg class contains.  If the
7250       // types are identical size, use a bitcast to convert (e.g. two differing
7251       // vector types).  Note: output bitcast is done at the end of
7252       // visitInlineAsm().
7253       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7254       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7255         // Exclude indirect inputs while they are unsupported because the code
7256         // to perform the load is missing and thus OpInfo.CallOperand still
7257         // refers to the input address rather than the pointed-to value.
7258         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7259           OpInfo.CallOperand =
7260               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7261         OpInfo.ConstraintVT = RegVT;
7262         // If the operand is an FP value and we want it in integer registers,
7263         // use the corresponding integer type. This turns an f64 value into
7264         // i64, which can be passed with two i32 values on a 32-bit machine.
7265       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7266         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7267         if (OpInfo.Type == InlineAsm::isInput)
7268           OpInfo.CallOperand =
7269               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7270         OpInfo.ConstraintVT = RegVT;
7271       }
7272     }
7273 
7274     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7275   }
7276 
7277   // No need to allocate a matching input constraint since the constraint it's
7278   // matching to has already been allocated.
7279   if (OpInfo.isMatchingInputConstraint())
7280     return;
7281 
7282   MVT RegVT;
7283   EVT ValueVT = OpInfo.ConstraintVT;
7284 
7285   // If this is a constraint for a specific physical register, like {r17},
7286   // assign it now.
7287   if (unsigned AssignedReg = PhysReg.first) {
7288     const TargetRegisterClass *RC = PhysReg.second;
7289     if (OpInfo.ConstraintVT == MVT::Other)
7290       ValueVT = *TRI.legalclasstypes_begin(*RC);
7291 
7292     // Get the actual register value type.  This is important, because the user
7293     // may have asked for (e.g.) the AX register in i32 type.  We need to
7294     // remember that AX is actually i16 to get the right extension.
7295     RegVT = *TRI.legalclasstypes_begin(*RC);
7296 
7297     // This is an explicit reference to a physical register.
7298     Regs.push_back(AssignedReg);
7299 
7300     // If this is an expanded reference, add the rest of the regs to Regs.
7301     if (NumRegs != 1) {
7302       TargetRegisterClass::iterator I = RC->begin();
7303       for (; *I != AssignedReg; ++I)
7304         assert(I != RC->end() && "Didn't find reg!");
7305 
7306       // Already added the first reg.
7307       --NumRegs; ++I;
7308       for (; NumRegs; --NumRegs, ++I) {
7309         assert(I != RC->end() && "Ran out of registers to allocate!");
7310         Regs.push_back(*I);
7311       }
7312     }
7313 
7314     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7315     return;
7316   }
7317 
7318   // Otherwise, if this was a reference to an LLVM register class, create vregs
7319   // for this reference.
7320   if (const TargetRegisterClass *RC = PhysReg.second) {
7321     RegVT = *TRI.legalclasstypes_begin(*RC);
7322     if (OpInfo.ConstraintVT == MVT::Other)
7323       ValueVT = RegVT;
7324 
7325     // Create the appropriate number of virtual registers.
7326     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7327     for (; NumRegs; --NumRegs)
7328       Regs.push_back(RegInfo.createVirtualRegister(RC));
7329 
7330     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7331     return;
7332   }
7333 
7334   // Otherwise, we couldn't allocate enough registers for this.
7335 }
7336 
7337 static unsigned
7338 findMatchingInlineAsmOperand(unsigned OperandNo,
7339                              const std::vector<SDValue> &AsmNodeOperands) {
7340   // Scan until we find the definition we already emitted of this operand.
7341   unsigned CurOp = InlineAsm::Op_FirstOperand;
7342   for (; OperandNo; --OperandNo) {
7343     // Advance to the next operand.
7344     unsigned OpFlag =
7345         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7346     assert((InlineAsm::isRegDefKind(OpFlag) ||
7347             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7348             InlineAsm::isMemKind(OpFlag)) &&
7349            "Skipped past definitions?");
7350     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7351   }
7352   return CurOp;
7353 }
7354 
7355 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7356 /// \return true if it has succeeded, false otherwise
7357 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7358                               MVT RegVT, SelectionDAG &DAG) {
7359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7360   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7361   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7362     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7363       Regs.push_back(RegInfo.createVirtualRegister(RC));
7364     else
7365       return false;
7366   }
7367   return true;
7368 }
7369 
7370 namespace {
7371 
7372 class ExtraFlags {
7373   unsigned Flags = 0;
7374 
7375 public:
7376   explicit ExtraFlags(ImmutableCallSite CS) {
7377     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7378     if (IA->hasSideEffects())
7379       Flags |= InlineAsm::Extra_HasSideEffects;
7380     if (IA->isAlignStack())
7381       Flags |= InlineAsm::Extra_IsAlignStack;
7382     if (CS.isConvergent())
7383       Flags |= InlineAsm::Extra_IsConvergent;
7384     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7385   }
7386 
7387   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7388     // Ideally, we would only check against memory constraints.  However, the
7389     // meaning of an Other constraint can be target-specific and we can't easily
7390     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7391     // for Other constraints as well.
7392     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7393         OpInfo.ConstraintType == TargetLowering::C_Other) {
7394       if (OpInfo.Type == InlineAsm::isInput)
7395         Flags |= InlineAsm::Extra_MayLoad;
7396       else if (OpInfo.Type == InlineAsm::isOutput)
7397         Flags |= InlineAsm::Extra_MayStore;
7398       else if (OpInfo.Type == InlineAsm::isClobber)
7399         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7400     }
7401   }
7402 
7403   unsigned get() const { return Flags; }
7404 };
7405 
7406 } // end anonymous namespace
7407 
7408 /// visitInlineAsm - Handle a call to an InlineAsm object.
7409 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7410   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7411 
7412   /// ConstraintOperands - Information about all of the constraints.
7413   SDISelAsmOperandInfoVector ConstraintOperands;
7414 
7415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7416   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7417       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7418 
7419   bool hasMemory = false;
7420 
7421   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7422   ExtraFlags ExtraInfo(CS);
7423 
7424   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7425   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7426   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7427     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7428     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7429 
7430     MVT OpVT = MVT::Other;
7431 
7432     // Compute the value type for each operand.
7433     if (OpInfo.Type == InlineAsm::isInput ||
7434         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7435       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7436 
7437       // Process the call argument. BasicBlocks are labels, currently appearing
7438       // only in asm's.
7439       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7440         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7441       } else {
7442         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7443       }
7444 
7445       OpVT =
7446           OpInfo
7447               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7448               .getSimpleVT();
7449     }
7450 
7451     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7452       // The return value of the call is this value.  As such, there is no
7453       // corresponding argument.
7454       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7455       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7456         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7457                                       STy->getElementType(ResNo));
7458       } else {
7459         assert(ResNo == 0 && "Asm only has one result!");
7460         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7461       }
7462       ++ResNo;
7463     }
7464 
7465     OpInfo.ConstraintVT = OpVT;
7466 
7467     if (!hasMemory)
7468       hasMemory = OpInfo.hasMemory(TLI);
7469 
7470     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7471     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7472     auto TargetConstraint = TargetConstraints[i];
7473 
7474     // Compute the constraint code and ConstraintType to use.
7475     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7476 
7477     ExtraInfo.update(TargetConstraint);
7478   }
7479 
7480   SDValue Chain, Flag;
7481 
7482   // We won't need to flush pending loads if this asm doesn't touch
7483   // memory and is nonvolatile.
7484   if (hasMemory || IA->hasSideEffects())
7485     Chain = getRoot();
7486   else
7487     Chain = DAG.getRoot();
7488 
7489   // Second pass over the constraints: compute which constraint option to use
7490   // and assign registers to constraints that want a specific physreg.
7491   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7492     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7493 
7494     // If this is an output operand with a matching input operand, look up the
7495     // matching input. If their types mismatch, e.g. one is an integer, the
7496     // other is floating point, or their sizes are different, flag it as an
7497     // error.
7498     if (OpInfo.hasMatchingInput()) {
7499       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7500       patchMatchingInput(OpInfo, Input, DAG);
7501     }
7502 
7503     // Compute the constraint code and ConstraintType to use.
7504     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7505 
7506     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7507         OpInfo.Type == InlineAsm::isClobber)
7508       continue;
7509 
7510     // If this is a memory input, and if the operand is not indirect, do what we
7511     // need to provide an address for the memory input.
7512     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7513         !OpInfo.isIndirect) {
7514       assert((OpInfo.isMultipleAlternative ||
7515               (OpInfo.Type == InlineAsm::isInput)) &&
7516              "Can only indirectify direct input operands!");
7517 
7518       // Memory operands really want the address of the value.
7519       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7520 
7521       // There is no longer a Value* corresponding to this operand.
7522       OpInfo.CallOperandVal = nullptr;
7523 
7524       // It is now an indirect operand.
7525       OpInfo.isIndirect = true;
7526     }
7527 
7528     // If this constraint is for a specific register, allocate it before
7529     // anything else.
7530     SDISelAsmOperandInfo &RefOpInfo =
7531         OpInfo.isMatchingInputConstraint()
7532             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7533             : ConstraintOperands[i];
7534     if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
7535       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7536   }
7537 
7538   // Third pass - Loop over all of the operands, assigning virtual or physregs
7539   // to register class operands.
7540   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7541     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7542     SDISelAsmOperandInfo &RefOpInfo =
7543         OpInfo.isMatchingInputConstraint()
7544             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7545             : ConstraintOperands[i];
7546 
7547     // C_Register operands have already been allocated, Other/Memory don't need
7548     // to be.
7549     if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7550       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7551   }
7552 
7553   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7554   std::vector<SDValue> AsmNodeOperands;
7555   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7556   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7557       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7558 
7559   // If we have a !srcloc metadata node associated with it, we want to attach
7560   // this to the ultimately generated inline asm machineinstr.  To do this, we
7561   // pass in the third operand as this (potentially null) inline asm MDNode.
7562   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7563   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7564 
7565   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7566   // bits as operand 3.
7567   AsmNodeOperands.push_back(DAG.getTargetConstant(
7568       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7569 
7570   // Loop over all of the inputs, copying the operand values into the
7571   // appropriate registers and processing the output regs.
7572   RegsForValue RetValRegs;
7573 
7574   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7575   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7576 
7577   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7578     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7579 
7580     switch (OpInfo.Type) {
7581     case InlineAsm::isOutput:
7582       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7583           OpInfo.ConstraintType != TargetLowering::C_Register) {
7584         // Memory output, or 'other' output (e.g. 'X' constraint).
7585         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7586 
7587         unsigned ConstraintID =
7588             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7589         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7590                "Failed to convert memory constraint code to constraint id.");
7591 
7592         // Add information to the INLINEASM node to know about this output.
7593         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7594         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7595         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7596                                                         MVT::i32));
7597         AsmNodeOperands.push_back(OpInfo.CallOperand);
7598         break;
7599       }
7600 
7601       // Otherwise, this is a register or register class output.
7602 
7603       // Copy the output from the appropriate register.  Find a register that
7604       // we can use.
7605       if (OpInfo.AssignedRegs.Regs.empty()) {
7606         emitInlineAsmError(
7607             CS, "couldn't allocate output register for constraint '" +
7608                     Twine(OpInfo.ConstraintCode) + "'");
7609         return;
7610       }
7611 
7612       // If this is an indirect operand, store through the pointer after the
7613       // asm.
7614       if (OpInfo.isIndirect) {
7615         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7616                                                       OpInfo.CallOperandVal));
7617       } else {
7618         // This is the result value of the call.
7619         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7620         // Concatenate this output onto the outputs list.
7621         RetValRegs.append(OpInfo.AssignedRegs);
7622       }
7623 
7624       // Add information to the INLINEASM node to know that this register is
7625       // set.
7626       OpInfo.AssignedRegs
7627           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7628                                     ? InlineAsm::Kind_RegDefEarlyClobber
7629                                     : InlineAsm::Kind_RegDef,
7630                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7631       break;
7632 
7633     case InlineAsm::isInput: {
7634       SDValue InOperandVal = OpInfo.CallOperand;
7635 
7636       if (OpInfo.isMatchingInputConstraint()) {
7637         // If this is required to match an output register we have already set,
7638         // just use its register.
7639         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7640                                                   AsmNodeOperands);
7641         unsigned OpFlag =
7642           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7643         if (InlineAsm::isRegDefKind(OpFlag) ||
7644             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7645           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7646           if (OpInfo.isIndirect) {
7647             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7648             emitInlineAsmError(CS, "inline asm not supported yet:"
7649                                    " don't know how to handle tied "
7650                                    "indirect register inputs");
7651             return;
7652           }
7653 
7654           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7655           SmallVector<unsigned, 4> Regs;
7656 
7657           if (!createVirtualRegs(Regs,
7658                                  InlineAsm::getNumOperandRegisters(OpFlag),
7659                                  RegVT, DAG)) {
7660             emitInlineAsmError(CS, "inline asm error: This value type register "
7661                                    "class is not natively supported!");
7662             return;
7663           }
7664 
7665           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7666 
7667           SDLoc dl = getCurSDLoc();
7668           // Use the produced MatchedRegs object to
7669           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7670                                     CS.getInstruction());
7671           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7672                                            true, OpInfo.getMatchedOperand(), dl,
7673                                            DAG, AsmNodeOperands);
7674           break;
7675         }
7676 
7677         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7678         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7679                "Unexpected number of operands");
7680         // Add information to the INLINEASM node to know about this input.
7681         // See InlineAsm.h isUseOperandTiedToDef.
7682         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7683         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7684                                                     OpInfo.getMatchedOperand());
7685         AsmNodeOperands.push_back(DAG.getTargetConstant(
7686             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7687         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7688         break;
7689       }
7690 
7691       // Treat indirect 'X' constraint as memory.
7692       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7693           OpInfo.isIndirect)
7694         OpInfo.ConstraintType = TargetLowering::C_Memory;
7695 
7696       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7697         std::vector<SDValue> Ops;
7698         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7699                                           Ops, DAG);
7700         if (Ops.empty()) {
7701           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7702                                      Twine(OpInfo.ConstraintCode) + "'");
7703           return;
7704         }
7705 
7706         // Add information to the INLINEASM node to know about this input.
7707         unsigned ResOpType =
7708           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7709         AsmNodeOperands.push_back(DAG.getTargetConstant(
7710             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7711         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7712         break;
7713       }
7714 
7715       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7716         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7717         assert(InOperandVal.getValueType() ==
7718                    TLI.getPointerTy(DAG.getDataLayout()) &&
7719                "Memory operands expect pointer values");
7720 
7721         unsigned ConstraintID =
7722             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7723         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7724                "Failed to convert memory constraint code to constraint id.");
7725 
7726         // Add information to the INLINEASM node to know about this input.
7727         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7728         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7729         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7730                                                         getCurSDLoc(),
7731                                                         MVT::i32));
7732         AsmNodeOperands.push_back(InOperandVal);
7733         break;
7734       }
7735 
7736       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7737               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7738              "Unknown constraint type!");
7739 
7740       // TODO: Support this.
7741       if (OpInfo.isIndirect) {
7742         emitInlineAsmError(
7743             CS, "Don't know how to handle indirect register inputs yet "
7744                 "for constraint '" +
7745                     Twine(OpInfo.ConstraintCode) + "'");
7746         return;
7747       }
7748 
7749       // Copy the input into the appropriate registers.
7750       if (OpInfo.AssignedRegs.Regs.empty()) {
7751         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7752                                    Twine(OpInfo.ConstraintCode) + "'");
7753         return;
7754       }
7755 
7756       SDLoc dl = getCurSDLoc();
7757 
7758       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7759                                         Chain, &Flag, CS.getInstruction());
7760 
7761       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7762                                                dl, DAG, AsmNodeOperands);
7763       break;
7764     }
7765     case InlineAsm::isClobber:
7766       // Add the clobbered value to the operand list, so that the register
7767       // allocator is aware that the physreg got clobbered.
7768       if (!OpInfo.AssignedRegs.Regs.empty())
7769         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7770                                                  false, 0, getCurSDLoc(), DAG,
7771                                                  AsmNodeOperands);
7772       break;
7773     }
7774   }
7775 
7776   // Finish up input operands.  Set the input chain and add the flag last.
7777   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7778   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7779 
7780   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7781                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7782   Flag = Chain.getValue(1);
7783 
7784   // If this asm returns a register value, copy the result from that register
7785   // and set it as the value of the call.
7786   if (!RetValRegs.Regs.empty()) {
7787     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7788                                              Chain, &Flag, CS.getInstruction());
7789 
7790     llvm::Type *CSResultType = CS.getType();
7791     unsigned numRet;
7792     ArrayRef<Type *> ResultTypes;
7793     SmallVector<SDValue, 1> ResultValues(1);
7794     if (CSResultType->isSingleValueType()) {
7795       numRet = 1;
7796       ResultValues[0] = Val;
7797       ResultTypes = makeArrayRef(CSResultType);
7798     } else {
7799       numRet = CSResultType->getNumContainedTypes();
7800       assert(Val->getNumOperands() == numRet &&
7801              "Mismatch in number of output operands in asm result");
7802       ResultTypes = CSResultType->subtypes();
7803       ArrayRef<SDUse> ValueUses = Val->ops();
7804       ResultValues.resize(numRet);
7805       std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(),
7806                      [](const SDUse &u) -> SDValue { return u.get(); });
7807     }
7808     SmallVector<EVT, 1> ResultVTs(numRet);
7809     for (unsigned i = 0; i < numRet; i++) {
7810       EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]);
7811       SDValue Val = ResultValues[i];
7812       assert(ResultTypes[i]->isSized() && "Unexpected unsized type");
7813       // If the type of the inline asm call site return value is different but
7814       // has same size as the type of the asm output bitcast it.  One example
7815       // of this is for vectors with different width / number of elements.
7816       // This can happen for register classes that can contain multiple
7817       // different value types.  The preg or vreg allocated may not have the
7818       // same VT as was expected.
7819       //
7820       // This can also happen for a return value that disagrees with the
7821       // register class it is put in, eg. a double in a general-purpose
7822       // register on a 32-bit machine.
7823       if (ResultVT != Val.getValueType() &&
7824           ResultVT.getSizeInBits() == Val.getValueSizeInBits())
7825         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val);
7826       else if (ResultVT != Val.getValueType() && ResultVT.isInteger() &&
7827                Val.getValueType().isInteger()) {
7828         // If a result value was tied to an input value, the computed result
7829         // may have a wider width than the expected result.  Extract the
7830         // relevant portion.
7831         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val);
7832       }
7833 
7834       assert(ResultVT == Val.getValueType() && "Asm result value mismatch!");
7835       ResultVTs[i] = ResultVT;
7836       ResultValues[i] = Val;
7837     }
7838 
7839     Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7840                       DAG.getVTList(ResultVTs), ResultValues);
7841     setValue(CS.getInstruction(), Val);
7842     // Don't need to use this as a chain in this case.
7843     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7844       return;
7845   }
7846 
7847   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7848 
7849   // Process indirect outputs, first output all of the flagged copies out of
7850   // physregs.
7851   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7852     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7853     const Value *Ptr = IndirectStoresToEmit[i].second;
7854     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7855                                              Chain, &Flag, IA);
7856     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7857   }
7858 
7859   // Emit the non-flagged stores from the physregs.
7860   SmallVector<SDValue, 8> OutChains;
7861   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7862     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7863                                getValue(StoresToEmit[i].second),
7864                                MachinePointerInfo(StoresToEmit[i].second));
7865     OutChains.push_back(Val);
7866   }
7867 
7868   if (!OutChains.empty())
7869     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7870 
7871   DAG.setRoot(Chain);
7872 }
7873 
7874 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7875                                              const Twine &Message) {
7876   LLVMContext &Ctx = *DAG.getContext();
7877   Ctx.emitError(CS.getInstruction(), Message);
7878 
7879   // Make sure we leave the DAG in a valid state
7880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7881   SmallVector<EVT, 1> ValueVTs;
7882   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7883 
7884   if (ValueVTs.empty())
7885     return;
7886 
7887   SmallVector<SDValue, 1> Ops;
7888   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7889     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7890 
7891   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7892 }
7893 
7894 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7895   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7896                           MVT::Other, getRoot(),
7897                           getValue(I.getArgOperand(0)),
7898                           DAG.getSrcValue(I.getArgOperand(0))));
7899 }
7900 
7901 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7903   const DataLayout &DL = DAG.getDataLayout();
7904   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7905                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7906                            DAG.getSrcValue(I.getOperand(0)),
7907                            DL.getABITypeAlignment(I.getType()));
7908   setValue(&I, V);
7909   DAG.setRoot(V.getValue(1));
7910 }
7911 
7912 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7913   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7914                           MVT::Other, getRoot(),
7915                           getValue(I.getArgOperand(0)),
7916                           DAG.getSrcValue(I.getArgOperand(0))));
7917 }
7918 
7919 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7920   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7921                           MVT::Other, getRoot(),
7922                           getValue(I.getArgOperand(0)),
7923                           getValue(I.getArgOperand(1)),
7924                           DAG.getSrcValue(I.getArgOperand(0)),
7925                           DAG.getSrcValue(I.getArgOperand(1))));
7926 }
7927 
7928 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7929                                                     const Instruction &I,
7930                                                     SDValue Op) {
7931   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7932   if (!Range)
7933     return Op;
7934 
7935   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7936   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7937     return Op;
7938 
7939   APInt Lo = CR.getUnsignedMin();
7940   if (!Lo.isMinValue())
7941     return Op;
7942 
7943   APInt Hi = CR.getUnsignedMax();
7944   unsigned Bits = Hi.getActiveBits();
7945 
7946   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7947 
7948   SDLoc SL = getCurSDLoc();
7949 
7950   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7951                              DAG.getValueType(SmallVT));
7952   unsigned NumVals = Op.getNode()->getNumValues();
7953   if (NumVals == 1)
7954     return ZExt;
7955 
7956   SmallVector<SDValue, 4> Ops;
7957 
7958   Ops.push_back(ZExt);
7959   for (unsigned I = 1; I != NumVals; ++I)
7960     Ops.push_back(Op.getValue(I));
7961 
7962   return DAG.getMergeValues(Ops, SL);
7963 }
7964 
7965 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
7966 /// the call being lowered.
7967 ///
7968 /// This is a helper for lowering intrinsics that follow a target calling
7969 /// convention or require stack pointer adjustment. Only a subset of the
7970 /// intrinsic's operands need to participate in the calling convention.
7971 void SelectionDAGBuilder::populateCallLoweringInfo(
7972     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7973     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7974     bool IsPatchPoint) {
7975   TargetLowering::ArgListTy Args;
7976   Args.reserve(NumArgs);
7977 
7978   // Populate the argument list.
7979   // Attributes for args start at offset 1, after the return attribute.
7980   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7981        ArgI != ArgE; ++ArgI) {
7982     const Value *V = CS->getOperand(ArgI);
7983 
7984     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7985 
7986     TargetLowering::ArgListEntry Entry;
7987     Entry.Node = getValue(V);
7988     Entry.Ty = V->getType();
7989     Entry.setAttributes(&CS, ArgI);
7990     Args.push_back(Entry);
7991   }
7992 
7993   CLI.setDebugLoc(getCurSDLoc())
7994       .setChain(getRoot())
7995       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7996       .setDiscardResult(CS->use_empty())
7997       .setIsPatchPoint(IsPatchPoint);
7998 }
7999 
8000 /// Add a stack map intrinsic call's live variable operands to a stackmap
8001 /// or patchpoint target node's operand list.
8002 ///
8003 /// Constants are converted to TargetConstants purely as an optimization to
8004 /// avoid constant materialization and register allocation.
8005 ///
8006 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8007 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8008 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8009 /// address materialization and register allocation, but may also be required
8010 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8011 /// alloca in the entry block, then the runtime may assume that the alloca's
8012 /// StackMap location can be read immediately after compilation and that the
8013 /// location is valid at any point during execution (this is similar to the
8014 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8015 /// only available in a register, then the runtime would need to trap when
8016 /// execution reaches the StackMap in order to read the alloca's location.
8017 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8018                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8019                                 SelectionDAGBuilder &Builder) {
8020   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8021     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8022     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8023       Ops.push_back(
8024         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8025       Ops.push_back(
8026         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8027     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8028       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8029       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8030           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8031     } else
8032       Ops.push_back(OpVal);
8033   }
8034 }
8035 
8036 /// Lower llvm.experimental.stackmap directly to its target opcode.
8037 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8038   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8039   //                                  [live variables...])
8040 
8041   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8042 
8043   SDValue Chain, InFlag, Callee, NullPtr;
8044   SmallVector<SDValue, 32> Ops;
8045 
8046   SDLoc DL = getCurSDLoc();
8047   Callee = getValue(CI.getCalledValue());
8048   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8049 
8050   // The stackmap intrinsic only records the live variables (the arguemnts
8051   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8052   // intrinsic, this won't be lowered to a function call. This means we don't
8053   // have to worry about calling conventions and target specific lowering code.
8054   // Instead we perform the call lowering right here.
8055   //
8056   // chain, flag = CALLSEQ_START(chain, 0, 0)
8057   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8058   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8059   //
8060   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8061   InFlag = Chain.getValue(1);
8062 
8063   // Add the <id> and <numBytes> constants.
8064   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8065   Ops.push_back(DAG.getTargetConstant(
8066                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8067   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8068   Ops.push_back(DAG.getTargetConstant(
8069                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8070                   MVT::i32));
8071 
8072   // Push live variables for the stack map.
8073   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8074 
8075   // We are not pushing any register mask info here on the operands list,
8076   // because the stackmap doesn't clobber anything.
8077 
8078   // Push the chain and the glue flag.
8079   Ops.push_back(Chain);
8080   Ops.push_back(InFlag);
8081 
8082   // Create the STACKMAP node.
8083   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8084   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8085   Chain = SDValue(SM, 0);
8086   InFlag = Chain.getValue(1);
8087 
8088   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8089 
8090   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8091 
8092   // Set the root to the target-lowered call chain.
8093   DAG.setRoot(Chain);
8094 
8095   // Inform the Frame Information that we have a stackmap in this function.
8096   FuncInfo.MF->getFrameInfo().setHasStackMap();
8097 }
8098 
8099 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8100 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8101                                           const BasicBlock *EHPadBB) {
8102   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8103   //                                                 i32 <numBytes>,
8104   //                                                 i8* <target>,
8105   //                                                 i32 <numArgs>,
8106   //                                                 [Args...],
8107   //                                                 [live variables...])
8108 
8109   CallingConv::ID CC = CS.getCallingConv();
8110   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8111   bool HasDef = !CS->getType()->isVoidTy();
8112   SDLoc dl = getCurSDLoc();
8113   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8114 
8115   // Handle immediate and symbolic callees.
8116   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8117     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8118                                    /*isTarget=*/true);
8119   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8120     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8121                                          SDLoc(SymbolicCallee),
8122                                          SymbolicCallee->getValueType(0));
8123 
8124   // Get the real number of arguments participating in the call <numArgs>
8125   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8126   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8127 
8128   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8129   // Intrinsics include all meta-operands up to but not including CC.
8130   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8131   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8132          "Not enough arguments provided to the patchpoint intrinsic");
8133 
8134   // For AnyRegCC the arguments are lowered later on manually.
8135   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8136   Type *ReturnTy =
8137     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8138 
8139   TargetLowering::CallLoweringInfo CLI(DAG);
8140   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8141                            true);
8142   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8143 
8144   SDNode *CallEnd = Result.second.getNode();
8145   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8146     CallEnd = CallEnd->getOperand(0).getNode();
8147 
8148   /// Get a call instruction from the call sequence chain.
8149   /// Tail calls are not allowed.
8150   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8151          "Expected a callseq node.");
8152   SDNode *Call = CallEnd->getOperand(0).getNode();
8153   bool HasGlue = Call->getGluedNode();
8154 
8155   // Replace the target specific call node with the patchable intrinsic.
8156   SmallVector<SDValue, 8> Ops;
8157 
8158   // Add the <id> and <numBytes> constants.
8159   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8160   Ops.push_back(DAG.getTargetConstant(
8161                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8162   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8163   Ops.push_back(DAG.getTargetConstant(
8164                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8165                   MVT::i32));
8166 
8167   // Add the callee.
8168   Ops.push_back(Callee);
8169 
8170   // Adjust <numArgs> to account for any arguments that have been passed on the
8171   // stack instead.
8172   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8173   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8174   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8175   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8176 
8177   // Add the calling convention
8178   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8179 
8180   // Add the arguments we omitted previously. The register allocator should
8181   // place these in any free register.
8182   if (IsAnyRegCC)
8183     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8184       Ops.push_back(getValue(CS.getArgument(i)));
8185 
8186   // Push the arguments from the call instruction up to the register mask.
8187   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8188   Ops.append(Call->op_begin() + 2, e);
8189 
8190   // Push live variables for the stack map.
8191   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8192 
8193   // Push the register mask info.
8194   if (HasGlue)
8195     Ops.push_back(*(Call->op_end()-2));
8196   else
8197     Ops.push_back(*(Call->op_end()-1));
8198 
8199   // Push the chain (this is originally the first operand of the call, but
8200   // becomes now the last or second to last operand).
8201   Ops.push_back(*(Call->op_begin()));
8202 
8203   // Push the glue flag (last operand).
8204   if (HasGlue)
8205     Ops.push_back(*(Call->op_end()-1));
8206 
8207   SDVTList NodeTys;
8208   if (IsAnyRegCC && HasDef) {
8209     // Create the return types based on the intrinsic definition
8210     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8211     SmallVector<EVT, 3> ValueVTs;
8212     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8213     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8214 
8215     // There is always a chain and a glue type at the end
8216     ValueVTs.push_back(MVT::Other);
8217     ValueVTs.push_back(MVT::Glue);
8218     NodeTys = DAG.getVTList(ValueVTs);
8219   } else
8220     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8221 
8222   // Replace the target specific call node with a PATCHPOINT node.
8223   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8224                                          dl, NodeTys, Ops);
8225 
8226   // Update the NodeMap.
8227   if (HasDef) {
8228     if (IsAnyRegCC)
8229       setValue(CS.getInstruction(), SDValue(MN, 0));
8230     else
8231       setValue(CS.getInstruction(), Result.first);
8232   }
8233 
8234   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8235   // call sequence. Furthermore the location of the chain and glue can change
8236   // when the AnyReg calling convention is used and the intrinsic returns a
8237   // value.
8238   if (IsAnyRegCC && HasDef) {
8239     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8240     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8241     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8242   } else
8243     DAG.ReplaceAllUsesWith(Call, MN);
8244   DAG.DeleteNode(Call);
8245 
8246   // Inform the Frame Information that we have a patchpoint in this function.
8247   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8248 }
8249 
8250 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8251                                             unsigned Intrinsic) {
8252   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8253   SDValue Op1 = getValue(I.getArgOperand(0));
8254   SDValue Op2;
8255   if (I.getNumArgOperands() > 1)
8256     Op2 = getValue(I.getArgOperand(1));
8257   SDLoc dl = getCurSDLoc();
8258   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8259   SDValue Res;
8260   FastMathFlags FMF;
8261   if (isa<FPMathOperator>(I))
8262     FMF = I.getFastMathFlags();
8263 
8264   switch (Intrinsic) {
8265   case Intrinsic::experimental_vector_reduce_fadd:
8266     if (FMF.isFast())
8267       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8268     else
8269       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8270     break;
8271   case Intrinsic::experimental_vector_reduce_fmul:
8272     if (FMF.isFast())
8273       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8274     else
8275       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8276     break;
8277   case Intrinsic::experimental_vector_reduce_add:
8278     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8279     break;
8280   case Intrinsic::experimental_vector_reduce_mul:
8281     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8282     break;
8283   case Intrinsic::experimental_vector_reduce_and:
8284     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8285     break;
8286   case Intrinsic::experimental_vector_reduce_or:
8287     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8288     break;
8289   case Intrinsic::experimental_vector_reduce_xor:
8290     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8291     break;
8292   case Intrinsic::experimental_vector_reduce_smax:
8293     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8294     break;
8295   case Intrinsic::experimental_vector_reduce_smin:
8296     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8297     break;
8298   case Intrinsic::experimental_vector_reduce_umax:
8299     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8300     break;
8301   case Intrinsic::experimental_vector_reduce_umin:
8302     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8303     break;
8304   case Intrinsic::experimental_vector_reduce_fmax:
8305     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8306     break;
8307   case Intrinsic::experimental_vector_reduce_fmin:
8308     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8309     break;
8310   default:
8311     llvm_unreachable("Unhandled vector reduce intrinsic");
8312   }
8313   setValue(&I, Res);
8314 }
8315 
8316 /// Returns an AttributeList representing the attributes applied to the return
8317 /// value of the given call.
8318 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8319   SmallVector<Attribute::AttrKind, 2> Attrs;
8320   if (CLI.RetSExt)
8321     Attrs.push_back(Attribute::SExt);
8322   if (CLI.RetZExt)
8323     Attrs.push_back(Attribute::ZExt);
8324   if (CLI.IsInReg)
8325     Attrs.push_back(Attribute::InReg);
8326 
8327   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8328                             Attrs);
8329 }
8330 
8331 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8332 /// implementation, which just calls LowerCall.
8333 /// FIXME: When all targets are
8334 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8335 std::pair<SDValue, SDValue>
8336 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8337   // Handle the incoming return values from the call.
8338   CLI.Ins.clear();
8339   Type *OrigRetTy = CLI.RetTy;
8340   SmallVector<EVT, 4> RetTys;
8341   SmallVector<uint64_t, 4> Offsets;
8342   auto &DL = CLI.DAG.getDataLayout();
8343   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8344 
8345   if (CLI.IsPostTypeLegalization) {
8346     // If we are lowering a libcall after legalization, split the return type.
8347     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8348     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8349     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8350       EVT RetVT = OldRetTys[i];
8351       uint64_t Offset = OldOffsets[i];
8352       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8353       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8354       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8355       RetTys.append(NumRegs, RegisterVT);
8356       for (unsigned j = 0; j != NumRegs; ++j)
8357         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8358     }
8359   }
8360 
8361   SmallVector<ISD::OutputArg, 4> Outs;
8362   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8363 
8364   bool CanLowerReturn =
8365       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8366                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8367 
8368   SDValue DemoteStackSlot;
8369   int DemoteStackIdx = -100;
8370   if (!CanLowerReturn) {
8371     // FIXME: equivalent assert?
8372     // assert(!CS.hasInAllocaArgument() &&
8373     //        "sret demotion is incompatible with inalloca");
8374     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8375     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8376     MachineFunction &MF = CLI.DAG.getMachineFunction();
8377     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8378     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8379                                               DL.getAllocaAddrSpace());
8380 
8381     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8382     ArgListEntry Entry;
8383     Entry.Node = DemoteStackSlot;
8384     Entry.Ty = StackSlotPtrType;
8385     Entry.IsSExt = false;
8386     Entry.IsZExt = false;
8387     Entry.IsInReg = false;
8388     Entry.IsSRet = true;
8389     Entry.IsNest = false;
8390     Entry.IsByVal = false;
8391     Entry.IsReturned = false;
8392     Entry.IsSwiftSelf = false;
8393     Entry.IsSwiftError = false;
8394     Entry.Alignment = Align;
8395     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8396     CLI.NumFixedArgs += 1;
8397     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8398 
8399     // sret demotion isn't compatible with tail-calls, since the sret argument
8400     // points into the callers stack frame.
8401     CLI.IsTailCall = false;
8402   } else {
8403     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8404       EVT VT = RetTys[I];
8405       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8406                                                      CLI.CallConv, VT);
8407       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8408                                                        CLI.CallConv, VT);
8409       for (unsigned i = 0; i != NumRegs; ++i) {
8410         ISD::InputArg MyFlags;
8411         MyFlags.VT = RegisterVT;
8412         MyFlags.ArgVT = VT;
8413         MyFlags.Used = CLI.IsReturnValueUsed;
8414         if (CLI.RetSExt)
8415           MyFlags.Flags.setSExt();
8416         if (CLI.RetZExt)
8417           MyFlags.Flags.setZExt();
8418         if (CLI.IsInReg)
8419           MyFlags.Flags.setInReg();
8420         CLI.Ins.push_back(MyFlags);
8421       }
8422     }
8423   }
8424 
8425   // We push in swifterror return as the last element of CLI.Ins.
8426   ArgListTy &Args = CLI.getArgs();
8427   if (supportSwiftError()) {
8428     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8429       if (Args[i].IsSwiftError) {
8430         ISD::InputArg MyFlags;
8431         MyFlags.VT = getPointerTy(DL);
8432         MyFlags.ArgVT = EVT(getPointerTy(DL));
8433         MyFlags.Flags.setSwiftError();
8434         CLI.Ins.push_back(MyFlags);
8435       }
8436     }
8437   }
8438 
8439   // Handle all of the outgoing arguments.
8440   CLI.Outs.clear();
8441   CLI.OutVals.clear();
8442   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8443     SmallVector<EVT, 4> ValueVTs;
8444     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8445     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8446     Type *FinalType = Args[i].Ty;
8447     if (Args[i].IsByVal)
8448       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8449     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8450         FinalType, CLI.CallConv, CLI.IsVarArg);
8451     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8452          ++Value) {
8453       EVT VT = ValueVTs[Value];
8454       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8455       SDValue Op = SDValue(Args[i].Node.getNode(),
8456                            Args[i].Node.getResNo() + Value);
8457       ISD::ArgFlagsTy Flags;
8458 
8459       // Certain targets (such as MIPS), may have a different ABI alignment
8460       // for a type depending on the context. Give the target a chance to
8461       // specify the alignment it wants.
8462       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8463 
8464       if (Args[i].IsZExt)
8465         Flags.setZExt();
8466       if (Args[i].IsSExt)
8467         Flags.setSExt();
8468       if (Args[i].IsInReg) {
8469         // If we are using vectorcall calling convention, a structure that is
8470         // passed InReg - is surely an HVA
8471         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8472             isa<StructType>(FinalType)) {
8473           // The first value of a structure is marked
8474           if (0 == Value)
8475             Flags.setHvaStart();
8476           Flags.setHva();
8477         }
8478         // Set InReg Flag
8479         Flags.setInReg();
8480       }
8481       if (Args[i].IsSRet)
8482         Flags.setSRet();
8483       if (Args[i].IsSwiftSelf)
8484         Flags.setSwiftSelf();
8485       if (Args[i].IsSwiftError)
8486         Flags.setSwiftError();
8487       if (Args[i].IsByVal)
8488         Flags.setByVal();
8489       if (Args[i].IsInAlloca) {
8490         Flags.setInAlloca();
8491         // Set the byval flag for CCAssignFn callbacks that don't know about
8492         // inalloca.  This way we can know how many bytes we should've allocated
8493         // and how many bytes a callee cleanup function will pop.  If we port
8494         // inalloca to more targets, we'll have to add custom inalloca handling
8495         // in the various CC lowering callbacks.
8496         Flags.setByVal();
8497       }
8498       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8499         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8500         Type *ElementTy = Ty->getElementType();
8501         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8502         // For ByVal, alignment should come from FE.  BE will guess if this
8503         // info is not there but there are cases it cannot get right.
8504         unsigned FrameAlign;
8505         if (Args[i].Alignment)
8506           FrameAlign = Args[i].Alignment;
8507         else
8508           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8509         Flags.setByValAlign(FrameAlign);
8510       }
8511       if (Args[i].IsNest)
8512         Flags.setNest();
8513       if (NeedsRegBlock)
8514         Flags.setInConsecutiveRegs();
8515       Flags.setOrigAlign(OriginalAlignment);
8516 
8517       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8518                                                  CLI.CallConv, VT);
8519       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8520                                                         CLI.CallConv, VT);
8521       SmallVector<SDValue, 4> Parts(NumParts);
8522       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8523 
8524       if (Args[i].IsSExt)
8525         ExtendKind = ISD::SIGN_EXTEND;
8526       else if (Args[i].IsZExt)
8527         ExtendKind = ISD::ZERO_EXTEND;
8528 
8529       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8530       // for now.
8531       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8532           CanLowerReturn) {
8533         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8534                "unexpected use of 'returned'");
8535         // Before passing 'returned' to the target lowering code, ensure that
8536         // either the register MVT and the actual EVT are the same size or that
8537         // the return value and argument are extended in the same way; in these
8538         // cases it's safe to pass the argument register value unchanged as the
8539         // return register value (although it's at the target's option whether
8540         // to do so)
8541         // TODO: allow code generation to take advantage of partially preserved
8542         // registers rather than clobbering the entire register when the
8543         // parameter extension method is not compatible with the return
8544         // extension method
8545         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8546             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8547              CLI.RetZExt == Args[i].IsZExt))
8548           Flags.setReturned();
8549       }
8550 
8551       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8552                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8553 
8554       for (unsigned j = 0; j != NumParts; ++j) {
8555         // if it isn't first piece, alignment must be 1
8556         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8557                                i < CLI.NumFixedArgs,
8558                                i, j*Parts[j].getValueType().getStoreSize());
8559         if (NumParts > 1 && j == 0)
8560           MyFlags.Flags.setSplit();
8561         else if (j != 0) {
8562           MyFlags.Flags.setOrigAlign(1);
8563           if (j == NumParts - 1)
8564             MyFlags.Flags.setSplitEnd();
8565         }
8566 
8567         CLI.Outs.push_back(MyFlags);
8568         CLI.OutVals.push_back(Parts[j]);
8569       }
8570 
8571       if (NeedsRegBlock && Value == NumValues - 1)
8572         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8573     }
8574   }
8575 
8576   SmallVector<SDValue, 4> InVals;
8577   CLI.Chain = LowerCall(CLI, InVals);
8578 
8579   // Update CLI.InVals to use outside of this function.
8580   CLI.InVals = InVals;
8581 
8582   // Verify that the target's LowerCall behaved as expected.
8583   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8584          "LowerCall didn't return a valid chain!");
8585   assert((!CLI.IsTailCall || InVals.empty()) &&
8586          "LowerCall emitted a return value for a tail call!");
8587   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8588          "LowerCall didn't emit the correct number of values!");
8589 
8590   // For a tail call, the return value is merely live-out and there aren't
8591   // any nodes in the DAG representing it. Return a special value to
8592   // indicate that a tail call has been emitted and no more Instructions
8593   // should be processed in the current block.
8594   if (CLI.IsTailCall) {
8595     CLI.DAG.setRoot(CLI.Chain);
8596     return std::make_pair(SDValue(), SDValue());
8597   }
8598 
8599 #ifndef NDEBUG
8600   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8601     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8602     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8603            "LowerCall emitted a value with the wrong type!");
8604   }
8605 #endif
8606 
8607   SmallVector<SDValue, 4> ReturnValues;
8608   if (!CanLowerReturn) {
8609     // The instruction result is the result of loading from the
8610     // hidden sret parameter.
8611     SmallVector<EVT, 1> PVTs;
8612     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8613 
8614     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8615     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8616     EVT PtrVT = PVTs[0];
8617 
8618     unsigned NumValues = RetTys.size();
8619     ReturnValues.resize(NumValues);
8620     SmallVector<SDValue, 4> Chains(NumValues);
8621 
8622     // An aggregate return value cannot wrap around the address space, so
8623     // offsets to its parts don't wrap either.
8624     SDNodeFlags Flags;
8625     Flags.setNoUnsignedWrap(true);
8626 
8627     for (unsigned i = 0; i < NumValues; ++i) {
8628       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8629                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8630                                                         PtrVT), Flags);
8631       SDValue L = CLI.DAG.getLoad(
8632           RetTys[i], CLI.DL, CLI.Chain, Add,
8633           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8634                                             DemoteStackIdx, Offsets[i]),
8635           /* Alignment = */ 1);
8636       ReturnValues[i] = L;
8637       Chains[i] = L.getValue(1);
8638     }
8639 
8640     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8641   } else {
8642     // Collect the legal value parts into potentially illegal values
8643     // that correspond to the original function's return values.
8644     Optional<ISD::NodeType> AssertOp;
8645     if (CLI.RetSExt)
8646       AssertOp = ISD::AssertSext;
8647     else if (CLI.RetZExt)
8648       AssertOp = ISD::AssertZext;
8649     unsigned CurReg = 0;
8650     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8651       EVT VT = RetTys[I];
8652       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8653                                                      CLI.CallConv, VT);
8654       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8655                                                        CLI.CallConv, VT);
8656 
8657       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8658                                               NumRegs, RegisterVT, VT, nullptr,
8659                                               CLI.CallConv, AssertOp));
8660       CurReg += NumRegs;
8661     }
8662 
8663     // For a function returning void, there is no return value. We can't create
8664     // such a node, so we just return a null return value in that case. In
8665     // that case, nothing will actually look at the value.
8666     if (ReturnValues.empty())
8667       return std::make_pair(SDValue(), CLI.Chain);
8668   }
8669 
8670   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8671                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8672   return std::make_pair(Res, CLI.Chain);
8673 }
8674 
8675 void TargetLowering::LowerOperationWrapper(SDNode *N,
8676                                            SmallVectorImpl<SDValue> &Results,
8677                                            SelectionDAG &DAG) const {
8678   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8679     Results.push_back(Res);
8680 }
8681 
8682 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8683   llvm_unreachable("LowerOperation not implemented for this target!");
8684 }
8685 
8686 void
8687 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8688   SDValue Op = getNonRegisterValue(V);
8689   assert((Op.getOpcode() != ISD::CopyFromReg ||
8690           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8691          "Copy from a reg to the same reg!");
8692   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8693 
8694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8695   // If this is an InlineAsm we have to match the registers required, not the
8696   // notional registers required by the type.
8697 
8698   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8699                    getABIRegCopyCC(V));
8700   SDValue Chain = DAG.getEntryNode();
8701 
8702   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8703                               FuncInfo.PreferredExtendType.end())
8704                                  ? ISD::ANY_EXTEND
8705                                  : FuncInfo.PreferredExtendType[V];
8706   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8707   PendingExports.push_back(Chain);
8708 }
8709 
8710 #include "llvm/CodeGen/SelectionDAGISel.h"
8711 
8712 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8713 /// entry block, return true.  This includes arguments used by switches, since
8714 /// the switch may expand into multiple basic blocks.
8715 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8716   // With FastISel active, we may be splitting blocks, so force creation
8717   // of virtual registers for all non-dead arguments.
8718   if (FastISel)
8719     return A->use_empty();
8720 
8721   const BasicBlock &Entry = A->getParent()->front();
8722   for (const User *U : A->users())
8723     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8724       return false;  // Use not in entry block.
8725 
8726   return true;
8727 }
8728 
8729 using ArgCopyElisionMapTy =
8730     DenseMap<const Argument *,
8731              std::pair<const AllocaInst *, const StoreInst *>>;
8732 
8733 /// Scan the entry block of the function in FuncInfo for arguments that look
8734 /// like copies into a local alloca. Record any copied arguments in
8735 /// ArgCopyElisionCandidates.
8736 static void
8737 findArgumentCopyElisionCandidates(const DataLayout &DL,
8738                                   FunctionLoweringInfo *FuncInfo,
8739                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8740   // Record the state of every static alloca used in the entry block. Argument
8741   // allocas are all used in the entry block, so we need approximately as many
8742   // entries as we have arguments.
8743   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8744   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8745   unsigned NumArgs = FuncInfo->Fn->arg_size();
8746   StaticAllocas.reserve(NumArgs * 2);
8747 
8748   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8749     if (!V)
8750       return nullptr;
8751     V = V->stripPointerCasts();
8752     const auto *AI = dyn_cast<AllocaInst>(V);
8753     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8754       return nullptr;
8755     auto Iter = StaticAllocas.insert({AI, Unknown});
8756     return &Iter.first->second;
8757   };
8758 
8759   // Look for stores of arguments to static allocas. Look through bitcasts and
8760   // GEPs to handle type coercions, as long as the alloca is fully initialized
8761   // by the store. Any non-store use of an alloca escapes it and any subsequent
8762   // unanalyzed store might write it.
8763   // FIXME: Handle structs initialized with multiple stores.
8764   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8765     // Look for stores, and handle non-store uses conservatively.
8766     const auto *SI = dyn_cast<StoreInst>(&I);
8767     if (!SI) {
8768       // We will look through cast uses, so ignore them completely.
8769       if (I.isCast())
8770         continue;
8771       // Ignore debug info intrinsics, they don't escape or store to allocas.
8772       if (isa<DbgInfoIntrinsic>(I))
8773         continue;
8774       // This is an unknown instruction. Assume it escapes or writes to all
8775       // static alloca operands.
8776       for (const Use &U : I.operands()) {
8777         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8778           *Info = StaticAllocaInfo::Clobbered;
8779       }
8780       continue;
8781     }
8782 
8783     // If the stored value is a static alloca, mark it as escaped.
8784     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8785       *Info = StaticAllocaInfo::Clobbered;
8786 
8787     // Check if the destination is a static alloca.
8788     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8789     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8790     if (!Info)
8791       continue;
8792     const AllocaInst *AI = cast<AllocaInst>(Dst);
8793 
8794     // Skip allocas that have been initialized or clobbered.
8795     if (*Info != StaticAllocaInfo::Unknown)
8796       continue;
8797 
8798     // Check if the stored value is an argument, and that this store fully
8799     // initializes the alloca. Don't elide copies from the same argument twice.
8800     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8801     const auto *Arg = dyn_cast<Argument>(Val);
8802     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8803         Arg->getType()->isEmptyTy() ||
8804         DL.getTypeStoreSize(Arg->getType()) !=
8805             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8806         ArgCopyElisionCandidates.count(Arg)) {
8807       *Info = StaticAllocaInfo::Clobbered;
8808       continue;
8809     }
8810 
8811     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8812                       << '\n');
8813 
8814     // Mark this alloca and store for argument copy elision.
8815     *Info = StaticAllocaInfo::Elidable;
8816     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8817 
8818     // Stop scanning if we've seen all arguments. This will happen early in -O0
8819     // builds, which is useful, because -O0 builds have large entry blocks and
8820     // many allocas.
8821     if (ArgCopyElisionCandidates.size() == NumArgs)
8822       break;
8823   }
8824 }
8825 
8826 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8827 /// ArgVal is a load from a suitable fixed stack object.
8828 static void tryToElideArgumentCopy(
8829     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8830     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8831     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8832     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8833     SDValue ArgVal, bool &ArgHasUses) {
8834   // Check if this is a load from a fixed stack object.
8835   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8836   if (!LNode)
8837     return;
8838   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8839   if (!FINode)
8840     return;
8841 
8842   // Check that the fixed stack object is the right size and alignment.
8843   // Look at the alignment that the user wrote on the alloca instead of looking
8844   // at the stack object.
8845   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8846   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8847   const AllocaInst *AI = ArgCopyIter->second.first;
8848   int FixedIndex = FINode->getIndex();
8849   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8850   int OldIndex = AllocaIndex;
8851   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8852   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8853     LLVM_DEBUG(
8854         dbgs() << "  argument copy elision failed due to bad fixed stack "
8855                   "object size\n");
8856     return;
8857   }
8858   unsigned RequiredAlignment = AI->getAlignment();
8859   if (!RequiredAlignment) {
8860     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8861         AI->getAllocatedType());
8862   }
8863   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8864     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8865                          "greater than stack argument alignment ("
8866                       << RequiredAlignment << " vs "
8867                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8868     return;
8869   }
8870 
8871   // Perform the elision. Delete the old stack object and replace its only use
8872   // in the variable info map. Mark the stack object as mutable.
8873   LLVM_DEBUG({
8874     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8875            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8876            << '\n';
8877   });
8878   MFI.RemoveStackObject(OldIndex);
8879   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8880   AllocaIndex = FixedIndex;
8881   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8882   Chains.push_back(ArgVal.getValue(1));
8883 
8884   // Avoid emitting code for the store implementing the copy.
8885   const StoreInst *SI = ArgCopyIter->second.second;
8886   ElidedArgCopyInstrs.insert(SI);
8887 
8888   // Check for uses of the argument again so that we can avoid exporting ArgVal
8889   // if it is't used by anything other than the store.
8890   for (const Value *U : Arg.users()) {
8891     if (U != SI) {
8892       ArgHasUses = true;
8893       break;
8894     }
8895   }
8896 }
8897 
8898 void SelectionDAGISel::LowerArguments(const Function &F) {
8899   SelectionDAG &DAG = SDB->DAG;
8900   SDLoc dl = SDB->getCurSDLoc();
8901   const DataLayout &DL = DAG.getDataLayout();
8902   SmallVector<ISD::InputArg, 16> Ins;
8903 
8904   if (!FuncInfo->CanLowerReturn) {
8905     // Put in an sret pointer parameter before all the other parameters.
8906     SmallVector<EVT, 1> ValueVTs;
8907     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8908                     F.getReturnType()->getPointerTo(
8909                         DAG.getDataLayout().getAllocaAddrSpace()),
8910                     ValueVTs);
8911 
8912     // NOTE: Assuming that a pointer will never break down to more than one VT
8913     // or one register.
8914     ISD::ArgFlagsTy Flags;
8915     Flags.setSRet();
8916     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8917     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8918                          ISD::InputArg::NoArgIndex, 0);
8919     Ins.push_back(RetArg);
8920   }
8921 
8922   // Look for stores of arguments to static allocas. Mark such arguments with a
8923   // flag to ask the target to give us the memory location of that argument if
8924   // available.
8925   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8926   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8927 
8928   // Set up the incoming argument description vector.
8929   for (const Argument &Arg : F.args()) {
8930     unsigned ArgNo = Arg.getArgNo();
8931     SmallVector<EVT, 4> ValueVTs;
8932     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8933     bool isArgValueUsed = !Arg.use_empty();
8934     unsigned PartBase = 0;
8935     Type *FinalType = Arg.getType();
8936     if (Arg.hasAttribute(Attribute::ByVal))
8937       FinalType = cast<PointerType>(FinalType)->getElementType();
8938     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8939         FinalType, F.getCallingConv(), F.isVarArg());
8940     for (unsigned Value = 0, NumValues = ValueVTs.size();
8941          Value != NumValues; ++Value) {
8942       EVT VT = ValueVTs[Value];
8943       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8944       ISD::ArgFlagsTy Flags;
8945 
8946       // Certain targets (such as MIPS), may have a different ABI alignment
8947       // for a type depending on the context. Give the target a chance to
8948       // specify the alignment it wants.
8949       unsigned OriginalAlignment =
8950           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8951 
8952       if (Arg.hasAttribute(Attribute::ZExt))
8953         Flags.setZExt();
8954       if (Arg.hasAttribute(Attribute::SExt))
8955         Flags.setSExt();
8956       if (Arg.hasAttribute(Attribute::InReg)) {
8957         // If we are using vectorcall calling convention, a structure that is
8958         // passed InReg - is surely an HVA
8959         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8960             isa<StructType>(Arg.getType())) {
8961           // The first value of a structure is marked
8962           if (0 == Value)
8963             Flags.setHvaStart();
8964           Flags.setHva();
8965         }
8966         // Set InReg Flag
8967         Flags.setInReg();
8968       }
8969       if (Arg.hasAttribute(Attribute::StructRet))
8970         Flags.setSRet();
8971       if (Arg.hasAttribute(Attribute::SwiftSelf))
8972         Flags.setSwiftSelf();
8973       if (Arg.hasAttribute(Attribute::SwiftError))
8974         Flags.setSwiftError();
8975       if (Arg.hasAttribute(Attribute::ByVal))
8976         Flags.setByVal();
8977       if (Arg.hasAttribute(Attribute::InAlloca)) {
8978         Flags.setInAlloca();
8979         // Set the byval flag for CCAssignFn callbacks that don't know about
8980         // inalloca.  This way we can know how many bytes we should've allocated
8981         // and how many bytes a callee cleanup function will pop.  If we port
8982         // inalloca to more targets, we'll have to add custom inalloca handling
8983         // in the various CC lowering callbacks.
8984         Flags.setByVal();
8985       }
8986       if (F.getCallingConv() == CallingConv::X86_INTR) {
8987         // IA Interrupt passes frame (1st parameter) by value in the stack.
8988         if (ArgNo == 0)
8989           Flags.setByVal();
8990       }
8991       if (Flags.isByVal() || Flags.isInAlloca()) {
8992         PointerType *Ty = cast<PointerType>(Arg.getType());
8993         Type *ElementTy = Ty->getElementType();
8994         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8995         // For ByVal, alignment should be passed from FE.  BE will guess if
8996         // this info is not there but there are cases it cannot get right.
8997         unsigned FrameAlign;
8998         if (Arg.getParamAlignment())
8999           FrameAlign = Arg.getParamAlignment();
9000         else
9001           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9002         Flags.setByValAlign(FrameAlign);
9003       }
9004       if (Arg.hasAttribute(Attribute::Nest))
9005         Flags.setNest();
9006       if (NeedsRegBlock)
9007         Flags.setInConsecutiveRegs();
9008       Flags.setOrigAlign(OriginalAlignment);
9009       if (ArgCopyElisionCandidates.count(&Arg))
9010         Flags.setCopyElisionCandidate();
9011 
9012       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9013           *CurDAG->getContext(), F.getCallingConv(), VT);
9014       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9015           *CurDAG->getContext(), F.getCallingConv(), VT);
9016       for (unsigned i = 0; i != NumRegs; ++i) {
9017         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9018                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9019         if (NumRegs > 1 && i == 0)
9020           MyFlags.Flags.setSplit();
9021         // if it isn't first piece, alignment must be 1
9022         else if (i > 0) {
9023           MyFlags.Flags.setOrigAlign(1);
9024           if (i == NumRegs - 1)
9025             MyFlags.Flags.setSplitEnd();
9026         }
9027         Ins.push_back(MyFlags);
9028       }
9029       if (NeedsRegBlock && Value == NumValues - 1)
9030         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9031       PartBase += VT.getStoreSize();
9032     }
9033   }
9034 
9035   // Call the target to set up the argument values.
9036   SmallVector<SDValue, 8> InVals;
9037   SDValue NewRoot = TLI->LowerFormalArguments(
9038       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9039 
9040   // Verify that the target's LowerFormalArguments behaved as expected.
9041   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9042          "LowerFormalArguments didn't return a valid chain!");
9043   assert(InVals.size() == Ins.size() &&
9044          "LowerFormalArguments didn't emit the correct number of values!");
9045   LLVM_DEBUG({
9046     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9047       assert(InVals[i].getNode() &&
9048              "LowerFormalArguments emitted a null value!");
9049       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9050              "LowerFormalArguments emitted a value with the wrong type!");
9051     }
9052   });
9053 
9054   // Update the DAG with the new chain value resulting from argument lowering.
9055   DAG.setRoot(NewRoot);
9056 
9057   // Set up the argument values.
9058   unsigned i = 0;
9059   if (!FuncInfo->CanLowerReturn) {
9060     // Create a virtual register for the sret pointer, and put in a copy
9061     // from the sret argument into it.
9062     SmallVector<EVT, 1> ValueVTs;
9063     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9064                     F.getReturnType()->getPointerTo(
9065                         DAG.getDataLayout().getAllocaAddrSpace()),
9066                     ValueVTs);
9067     MVT VT = ValueVTs[0].getSimpleVT();
9068     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9069     Optional<ISD::NodeType> AssertOp = None;
9070     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9071                                         nullptr, F.getCallingConv(), AssertOp);
9072 
9073     MachineFunction& MF = SDB->DAG.getMachineFunction();
9074     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9075     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9076     FuncInfo->DemoteRegister = SRetReg;
9077     NewRoot =
9078         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9079     DAG.setRoot(NewRoot);
9080 
9081     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9082     ++i;
9083   }
9084 
9085   SmallVector<SDValue, 4> Chains;
9086   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9087   for (const Argument &Arg : F.args()) {
9088     SmallVector<SDValue, 4> ArgValues;
9089     SmallVector<EVT, 4> ValueVTs;
9090     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9091     unsigned NumValues = ValueVTs.size();
9092     if (NumValues == 0)
9093       continue;
9094 
9095     bool ArgHasUses = !Arg.use_empty();
9096 
9097     // Elide the copying store if the target loaded this argument from a
9098     // suitable fixed stack object.
9099     if (Ins[i].Flags.isCopyElisionCandidate()) {
9100       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9101                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9102                              InVals[i], ArgHasUses);
9103     }
9104 
9105     // If this argument is unused then remember its value. It is used to generate
9106     // debugging information.
9107     bool isSwiftErrorArg =
9108         TLI->supportSwiftError() &&
9109         Arg.hasAttribute(Attribute::SwiftError);
9110     if (!ArgHasUses && !isSwiftErrorArg) {
9111       SDB->setUnusedArgValue(&Arg, InVals[i]);
9112 
9113       // Also remember any frame index for use in FastISel.
9114       if (FrameIndexSDNode *FI =
9115           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9116         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9117     }
9118 
9119     for (unsigned Val = 0; Val != NumValues; ++Val) {
9120       EVT VT = ValueVTs[Val];
9121       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9122                                                       F.getCallingConv(), VT);
9123       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9124           *CurDAG->getContext(), F.getCallingConv(), VT);
9125 
9126       // Even an apparant 'unused' swifterror argument needs to be returned. So
9127       // we do generate a copy for it that can be used on return from the
9128       // function.
9129       if (ArgHasUses || isSwiftErrorArg) {
9130         Optional<ISD::NodeType> AssertOp;
9131         if (Arg.hasAttribute(Attribute::SExt))
9132           AssertOp = ISD::AssertSext;
9133         else if (Arg.hasAttribute(Attribute::ZExt))
9134           AssertOp = ISD::AssertZext;
9135 
9136         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9137                                              PartVT, VT, nullptr,
9138                                              F.getCallingConv(), AssertOp));
9139       }
9140 
9141       i += NumParts;
9142     }
9143 
9144     // We don't need to do anything else for unused arguments.
9145     if (ArgValues.empty())
9146       continue;
9147 
9148     // Note down frame index.
9149     if (FrameIndexSDNode *FI =
9150         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9151       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9152 
9153     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9154                                      SDB->getCurSDLoc());
9155 
9156     SDB->setValue(&Arg, Res);
9157     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9158       // We want to associate the argument with the frame index, among
9159       // involved operands, that correspond to the lowest address. The
9160       // getCopyFromParts function, called earlier, is swapping the order of
9161       // the operands to BUILD_PAIR depending on endianness. The result of
9162       // that swapping is that the least significant bits of the argument will
9163       // be in the first operand of the BUILD_PAIR node, and the most
9164       // significant bits will be in the second operand.
9165       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9166       if (LoadSDNode *LNode =
9167           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9168         if (FrameIndexSDNode *FI =
9169             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9170           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9171     }
9172 
9173     // Update the SwiftErrorVRegDefMap.
9174     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9175       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9176       if (TargetRegisterInfo::isVirtualRegister(Reg))
9177         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9178                                            FuncInfo->SwiftErrorArg, Reg);
9179     }
9180 
9181     // If this argument is live outside of the entry block, insert a copy from
9182     // wherever we got it to the vreg that other BB's will reference it as.
9183     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9184       // If we can, though, try to skip creating an unnecessary vreg.
9185       // FIXME: This isn't very clean... it would be nice to make this more
9186       // general.  It's also subtly incompatible with the hacks FastISel
9187       // uses with vregs.
9188       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9189       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9190         FuncInfo->ValueMap[&Arg] = Reg;
9191         continue;
9192       }
9193     }
9194     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9195       FuncInfo->InitializeRegForValue(&Arg);
9196       SDB->CopyToExportRegsIfNeeded(&Arg);
9197     }
9198   }
9199 
9200   if (!Chains.empty()) {
9201     Chains.push_back(NewRoot);
9202     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9203   }
9204 
9205   DAG.setRoot(NewRoot);
9206 
9207   assert(i == InVals.size() && "Argument register count mismatch!");
9208 
9209   // If any argument copy elisions occurred and we have debug info, update the
9210   // stale frame indices used in the dbg.declare variable info table.
9211   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9212   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9213     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9214       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9215       if (I != ArgCopyElisionFrameIndexMap.end())
9216         VI.Slot = I->second;
9217     }
9218   }
9219 
9220   // Finally, if the target has anything special to do, allow it to do so.
9221   EmitFunctionEntryCode();
9222 }
9223 
9224 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9225 /// ensure constants are generated when needed.  Remember the virtual registers
9226 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9227 /// directly add them, because expansion might result in multiple MBB's for one
9228 /// BB.  As such, the start of the BB might correspond to a different MBB than
9229 /// the end.
9230 void
9231 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9232   const TerminatorInst *TI = LLVMBB->getTerminator();
9233 
9234   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9235 
9236   // Check PHI nodes in successors that expect a value to be available from this
9237   // block.
9238   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9239     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9240     if (!isa<PHINode>(SuccBB->begin())) continue;
9241     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9242 
9243     // If this terminator has multiple identical successors (common for
9244     // switches), only handle each succ once.
9245     if (!SuccsHandled.insert(SuccMBB).second)
9246       continue;
9247 
9248     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9249 
9250     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9251     // nodes and Machine PHI nodes, but the incoming operands have not been
9252     // emitted yet.
9253     for (const PHINode &PN : SuccBB->phis()) {
9254       // Ignore dead phi's.
9255       if (PN.use_empty())
9256         continue;
9257 
9258       // Skip empty types
9259       if (PN.getType()->isEmptyTy())
9260         continue;
9261 
9262       unsigned Reg;
9263       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9264 
9265       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9266         unsigned &RegOut = ConstantsOut[C];
9267         if (RegOut == 0) {
9268           RegOut = FuncInfo.CreateRegs(C->getType());
9269           CopyValueToVirtualRegister(C, RegOut);
9270         }
9271         Reg = RegOut;
9272       } else {
9273         DenseMap<const Value *, unsigned>::iterator I =
9274           FuncInfo.ValueMap.find(PHIOp);
9275         if (I != FuncInfo.ValueMap.end())
9276           Reg = I->second;
9277         else {
9278           assert(isa<AllocaInst>(PHIOp) &&
9279                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9280                  "Didn't codegen value into a register!??");
9281           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9282           CopyValueToVirtualRegister(PHIOp, Reg);
9283         }
9284       }
9285 
9286       // Remember that this register needs to added to the machine PHI node as
9287       // the input for this MBB.
9288       SmallVector<EVT, 4> ValueVTs;
9289       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9290       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9291       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9292         EVT VT = ValueVTs[vti];
9293         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9294         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9295           FuncInfo.PHINodesToUpdate.push_back(
9296               std::make_pair(&*MBBI++, Reg + i));
9297         Reg += NumRegisters;
9298       }
9299     }
9300   }
9301 
9302   ConstantsOut.clear();
9303 }
9304 
9305 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9306 /// is 0.
9307 MachineBasicBlock *
9308 SelectionDAGBuilder::StackProtectorDescriptor::
9309 AddSuccessorMBB(const BasicBlock *BB,
9310                 MachineBasicBlock *ParentMBB,
9311                 bool IsLikely,
9312                 MachineBasicBlock *SuccMBB) {
9313   // If SuccBB has not been created yet, create it.
9314   if (!SuccMBB) {
9315     MachineFunction *MF = ParentMBB->getParent();
9316     MachineFunction::iterator BBI(ParentMBB);
9317     SuccMBB = MF->CreateMachineBasicBlock(BB);
9318     MF->insert(++BBI, SuccMBB);
9319   }
9320   // Add it as a successor of ParentMBB.
9321   ParentMBB->addSuccessor(
9322       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9323   return SuccMBB;
9324 }
9325 
9326 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9327   MachineFunction::iterator I(MBB);
9328   if (++I == FuncInfo.MF->end())
9329     return nullptr;
9330   return &*I;
9331 }
9332 
9333 /// During lowering new call nodes can be created (such as memset, etc.).
9334 /// Those will become new roots of the current DAG, but complications arise
9335 /// when they are tail calls. In such cases, the call lowering will update
9336 /// the root, but the builder still needs to know that a tail call has been
9337 /// lowered in order to avoid generating an additional return.
9338 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9339   // If the node is null, we do have a tail call.
9340   if (MaybeTC.getNode() != nullptr)
9341     DAG.setRoot(MaybeTC);
9342   else
9343     HasTailCall = true;
9344 }
9345 
9346 uint64_t
9347 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9348                                        unsigned First, unsigned Last) const {
9349   assert(Last >= First);
9350   const APInt &LowCase = Clusters[First].Low->getValue();
9351   const APInt &HighCase = Clusters[Last].High->getValue();
9352   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9353 
9354   // FIXME: A range of consecutive cases has 100% density, but only requires one
9355   // comparison to lower. We should discriminate against such consecutive ranges
9356   // in jump tables.
9357 
9358   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9359 }
9360 
9361 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9362     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9363     unsigned Last) const {
9364   assert(Last >= First);
9365   assert(TotalCases[Last] >= TotalCases[First]);
9366   uint64_t NumCases =
9367       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9368   return NumCases;
9369 }
9370 
9371 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9372                                          unsigned First, unsigned Last,
9373                                          const SwitchInst *SI,
9374                                          MachineBasicBlock *DefaultMBB,
9375                                          CaseCluster &JTCluster) {
9376   assert(First <= Last);
9377 
9378   auto Prob = BranchProbability::getZero();
9379   unsigned NumCmps = 0;
9380   std::vector<MachineBasicBlock*> Table;
9381   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9382 
9383   // Initialize probabilities in JTProbs.
9384   for (unsigned I = First; I <= Last; ++I)
9385     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9386 
9387   for (unsigned I = First; I <= Last; ++I) {
9388     assert(Clusters[I].Kind == CC_Range);
9389     Prob += Clusters[I].Prob;
9390     const APInt &Low = Clusters[I].Low->getValue();
9391     const APInt &High = Clusters[I].High->getValue();
9392     NumCmps += (Low == High) ? 1 : 2;
9393     if (I != First) {
9394       // Fill the gap between this and the previous cluster.
9395       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9396       assert(PreviousHigh.slt(Low));
9397       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9398       for (uint64_t J = 0; J < Gap; J++)
9399         Table.push_back(DefaultMBB);
9400     }
9401     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9402     for (uint64_t J = 0; J < ClusterSize; ++J)
9403       Table.push_back(Clusters[I].MBB);
9404     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9405   }
9406 
9407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9408   unsigned NumDests = JTProbs.size();
9409   if (TLI.isSuitableForBitTests(
9410           NumDests, NumCmps, Clusters[First].Low->getValue(),
9411           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9412     // Clusters[First..Last] should be lowered as bit tests instead.
9413     return false;
9414   }
9415 
9416   // Create the MBB that will load from and jump through the table.
9417   // Note: We create it here, but it's not inserted into the function yet.
9418   MachineFunction *CurMF = FuncInfo.MF;
9419   MachineBasicBlock *JumpTableMBB =
9420       CurMF->CreateMachineBasicBlock(SI->getParent());
9421 
9422   // Add successors. Note: use table order for determinism.
9423   SmallPtrSet<MachineBasicBlock *, 8> Done;
9424   for (MachineBasicBlock *Succ : Table) {
9425     if (Done.count(Succ))
9426       continue;
9427     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9428     Done.insert(Succ);
9429   }
9430   JumpTableMBB->normalizeSuccProbs();
9431 
9432   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9433                      ->createJumpTableIndex(Table);
9434 
9435   // Set up the jump table info.
9436   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9437   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9438                       Clusters[Last].High->getValue(), SI->getCondition(),
9439                       nullptr, false);
9440   JTCases.emplace_back(std::move(JTH), std::move(JT));
9441 
9442   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9443                                      JTCases.size() - 1, Prob);
9444   return true;
9445 }
9446 
9447 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9448                                          const SwitchInst *SI,
9449                                          MachineBasicBlock *DefaultMBB) {
9450 #ifndef NDEBUG
9451   // Clusters must be non-empty, sorted, and only contain Range clusters.
9452   assert(!Clusters.empty());
9453   for (CaseCluster &C : Clusters)
9454     assert(C.Kind == CC_Range);
9455   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9456     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9457 #endif
9458 
9459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9460   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9461     return;
9462 
9463   const int64_t N = Clusters.size();
9464   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9465   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9466 
9467   if (N < 2 || N < MinJumpTableEntries)
9468     return;
9469 
9470   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9471   SmallVector<unsigned, 8> TotalCases(N);
9472   for (unsigned i = 0; i < N; ++i) {
9473     const APInt &Hi = Clusters[i].High->getValue();
9474     const APInt &Lo = Clusters[i].Low->getValue();
9475     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9476     if (i != 0)
9477       TotalCases[i] += TotalCases[i - 1];
9478   }
9479 
9480   // Cheap case: the whole range may be suitable for jump table.
9481   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9482   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9483   assert(NumCases < UINT64_MAX / 100);
9484   assert(Range >= NumCases);
9485   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9486     CaseCluster JTCluster;
9487     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9488       Clusters[0] = JTCluster;
9489       Clusters.resize(1);
9490       return;
9491     }
9492   }
9493 
9494   // The algorithm below is not suitable for -O0.
9495   if (TM.getOptLevel() == CodeGenOpt::None)
9496     return;
9497 
9498   // Split Clusters into minimum number of dense partitions. The algorithm uses
9499   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9500   // for the Case Statement'" (1994), but builds the MinPartitions array in
9501   // reverse order to make it easier to reconstruct the partitions in ascending
9502   // order. In the choice between two optimal partitionings, it picks the one
9503   // which yields more jump tables.
9504 
9505   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9506   SmallVector<unsigned, 8> MinPartitions(N);
9507   // LastElement[i] is the last element of the partition starting at i.
9508   SmallVector<unsigned, 8> LastElement(N);
9509   // PartitionsScore[i] is used to break ties when choosing between two
9510   // partitionings resulting in the same number of partitions.
9511   SmallVector<unsigned, 8> PartitionsScore(N);
9512   // For PartitionsScore, a small number of comparisons is considered as good as
9513   // a jump table and a single comparison is considered better than a jump
9514   // table.
9515   enum PartitionScores : unsigned {
9516     NoTable = 0,
9517     Table = 1,
9518     FewCases = 1,
9519     SingleCase = 2
9520   };
9521 
9522   // Base case: There is only one way to partition Clusters[N-1].
9523   MinPartitions[N - 1] = 1;
9524   LastElement[N - 1] = N - 1;
9525   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9526 
9527   // Note: loop indexes are signed to avoid underflow.
9528   for (int64_t i = N - 2; i >= 0; i--) {
9529     // Find optimal partitioning of Clusters[i..N-1].
9530     // Baseline: Put Clusters[i] into a partition on its own.
9531     MinPartitions[i] = MinPartitions[i + 1] + 1;
9532     LastElement[i] = i;
9533     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9534 
9535     // Search for a solution that results in fewer partitions.
9536     for (int64_t j = N - 1; j > i; j--) {
9537       // Try building a partition from Clusters[i..j].
9538       uint64_t Range = getJumpTableRange(Clusters, i, j);
9539       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9540       assert(NumCases < UINT64_MAX / 100);
9541       assert(Range >= NumCases);
9542       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9543         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9544         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9545         int64_t NumEntries = j - i + 1;
9546 
9547         if (NumEntries == 1)
9548           Score += PartitionScores::SingleCase;
9549         else if (NumEntries <= SmallNumberOfEntries)
9550           Score += PartitionScores::FewCases;
9551         else if (NumEntries >= MinJumpTableEntries)
9552           Score += PartitionScores::Table;
9553 
9554         // If this leads to fewer partitions, or to the same number of
9555         // partitions with better score, it is a better partitioning.
9556         if (NumPartitions < MinPartitions[i] ||
9557             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9558           MinPartitions[i] = NumPartitions;
9559           LastElement[i] = j;
9560           PartitionsScore[i] = Score;
9561         }
9562       }
9563     }
9564   }
9565 
9566   // Iterate over the partitions, replacing some with jump tables in-place.
9567   unsigned DstIndex = 0;
9568   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9569     Last = LastElement[First];
9570     assert(Last >= First);
9571     assert(DstIndex <= First);
9572     unsigned NumClusters = Last - First + 1;
9573 
9574     CaseCluster JTCluster;
9575     if (NumClusters >= MinJumpTableEntries &&
9576         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9577       Clusters[DstIndex++] = JTCluster;
9578     } else {
9579       for (unsigned I = First; I <= Last; ++I)
9580         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9581     }
9582   }
9583   Clusters.resize(DstIndex);
9584 }
9585 
9586 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9587                                         unsigned First, unsigned Last,
9588                                         const SwitchInst *SI,
9589                                         CaseCluster &BTCluster) {
9590   assert(First <= Last);
9591   if (First == Last)
9592     return false;
9593 
9594   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9595   unsigned NumCmps = 0;
9596   for (int64_t I = First; I <= Last; ++I) {
9597     assert(Clusters[I].Kind == CC_Range);
9598     Dests.set(Clusters[I].MBB->getNumber());
9599     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9600   }
9601   unsigned NumDests = Dests.count();
9602 
9603   APInt Low = Clusters[First].Low->getValue();
9604   APInt High = Clusters[Last].High->getValue();
9605   assert(Low.slt(High));
9606 
9607   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9608   const DataLayout &DL = DAG.getDataLayout();
9609   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9610     return false;
9611 
9612   APInt LowBound;
9613   APInt CmpRange;
9614 
9615   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9616   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9617          "Case range must fit in bit mask!");
9618 
9619   // Check if the clusters cover a contiguous range such that no value in the
9620   // range will jump to the default statement.
9621   bool ContiguousRange = true;
9622   for (int64_t I = First + 1; I <= Last; ++I) {
9623     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9624       ContiguousRange = false;
9625       break;
9626     }
9627   }
9628 
9629   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9630     // Optimize the case where all the case values fit in a word without having
9631     // to subtract minValue. In this case, we can optimize away the subtraction.
9632     LowBound = APInt::getNullValue(Low.getBitWidth());
9633     CmpRange = High;
9634     ContiguousRange = false;
9635   } else {
9636     LowBound = Low;
9637     CmpRange = High - Low;
9638   }
9639 
9640   CaseBitsVector CBV;
9641   auto TotalProb = BranchProbability::getZero();
9642   for (unsigned i = First; i <= Last; ++i) {
9643     // Find the CaseBits for this destination.
9644     unsigned j;
9645     for (j = 0; j < CBV.size(); ++j)
9646       if (CBV[j].BB == Clusters[i].MBB)
9647         break;
9648     if (j == CBV.size())
9649       CBV.push_back(
9650           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9651     CaseBits *CB = &CBV[j];
9652 
9653     // Update Mask, Bits and ExtraProb.
9654     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9655     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9656     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9657     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9658     CB->Bits += Hi - Lo + 1;
9659     CB->ExtraProb += Clusters[i].Prob;
9660     TotalProb += Clusters[i].Prob;
9661   }
9662 
9663   BitTestInfo BTI;
9664   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9665     // Sort by probability first, number of bits second, bit mask third.
9666     if (a.ExtraProb != b.ExtraProb)
9667       return a.ExtraProb > b.ExtraProb;
9668     if (a.Bits != b.Bits)
9669       return a.Bits > b.Bits;
9670     return a.Mask < b.Mask;
9671   });
9672 
9673   for (auto &CB : CBV) {
9674     MachineBasicBlock *BitTestBB =
9675         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9676     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9677   }
9678   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9679                             SI->getCondition(), -1U, MVT::Other, false,
9680                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9681                             TotalProb);
9682 
9683   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9684                                     BitTestCases.size() - 1, TotalProb);
9685   return true;
9686 }
9687 
9688 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9689                                               const SwitchInst *SI) {
9690 // Partition Clusters into as few subsets as possible, where each subset has a
9691 // range that fits in a machine word and has <= 3 unique destinations.
9692 
9693 #ifndef NDEBUG
9694   // Clusters must be sorted and contain Range or JumpTable clusters.
9695   assert(!Clusters.empty());
9696   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9697   for (const CaseCluster &C : Clusters)
9698     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9699   for (unsigned i = 1; i < Clusters.size(); ++i)
9700     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9701 #endif
9702 
9703   // The algorithm below is not suitable for -O0.
9704   if (TM.getOptLevel() == CodeGenOpt::None)
9705     return;
9706 
9707   // If target does not have legal shift left, do not emit bit tests at all.
9708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9709   const DataLayout &DL = DAG.getDataLayout();
9710 
9711   EVT PTy = TLI.getPointerTy(DL);
9712   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9713     return;
9714 
9715   int BitWidth = PTy.getSizeInBits();
9716   const int64_t N = Clusters.size();
9717 
9718   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9719   SmallVector<unsigned, 8> MinPartitions(N);
9720   // LastElement[i] is the last element of the partition starting at i.
9721   SmallVector<unsigned, 8> LastElement(N);
9722 
9723   // FIXME: This might not be the best algorithm for finding bit test clusters.
9724 
9725   // Base case: There is only one way to partition Clusters[N-1].
9726   MinPartitions[N - 1] = 1;
9727   LastElement[N - 1] = N - 1;
9728 
9729   // Note: loop indexes are signed to avoid underflow.
9730   for (int64_t i = N - 2; i >= 0; --i) {
9731     // Find optimal partitioning of Clusters[i..N-1].
9732     // Baseline: Put Clusters[i] into a partition on its own.
9733     MinPartitions[i] = MinPartitions[i + 1] + 1;
9734     LastElement[i] = i;
9735 
9736     // Search for a solution that results in fewer partitions.
9737     // Note: the search is limited by BitWidth, reducing time complexity.
9738     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9739       // Try building a partition from Clusters[i..j].
9740 
9741       // Check the range.
9742       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9743                                Clusters[j].High->getValue(), DL))
9744         continue;
9745 
9746       // Check nbr of destinations and cluster types.
9747       // FIXME: This works, but doesn't seem very efficient.
9748       bool RangesOnly = true;
9749       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9750       for (int64_t k = i; k <= j; k++) {
9751         if (Clusters[k].Kind != CC_Range) {
9752           RangesOnly = false;
9753           break;
9754         }
9755         Dests.set(Clusters[k].MBB->getNumber());
9756       }
9757       if (!RangesOnly || Dests.count() > 3)
9758         break;
9759 
9760       // Check if it's a better partition.
9761       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9762       if (NumPartitions < MinPartitions[i]) {
9763         // Found a better partition.
9764         MinPartitions[i] = NumPartitions;
9765         LastElement[i] = j;
9766       }
9767     }
9768   }
9769 
9770   // Iterate over the partitions, replacing with bit-test clusters in-place.
9771   unsigned DstIndex = 0;
9772   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9773     Last = LastElement[First];
9774     assert(First <= Last);
9775     assert(DstIndex <= First);
9776 
9777     CaseCluster BitTestCluster;
9778     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9779       Clusters[DstIndex++] = BitTestCluster;
9780     } else {
9781       size_t NumClusters = Last - First + 1;
9782       std::memmove(&Clusters[DstIndex], &Clusters[First],
9783                    sizeof(Clusters[0]) * NumClusters);
9784       DstIndex += NumClusters;
9785     }
9786   }
9787   Clusters.resize(DstIndex);
9788 }
9789 
9790 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9791                                         MachineBasicBlock *SwitchMBB,
9792                                         MachineBasicBlock *DefaultMBB) {
9793   MachineFunction *CurMF = FuncInfo.MF;
9794   MachineBasicBlock *NextMBB = nullptr;
9795   MachineFunction::iterator BBI(W.MBB);
9796   if (++BBI != FuncInfo.MF->end())
9797     NextMBB = &*BBI;
9798 
9799   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9800 
9801   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9802 
9803   if (Size == 2 && W.MBB == SwitchMBB) {
9804     // If any two of the cases has the same destination, and if one value
9805     // is the same as the other, but has one bit unset that the other has set,
9806     // use bit manipulation to do two compares at once.  For example:
9807     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9808     // TODO: This could be extended to merge any 2 cases in switches with 3
9809     // cases.
9810     // TODO: Handle cases where W.CaseBB != SwitchBB.
9811     CaseCluster &Small = *W.FirstCluster;
9812     CaseCluster &Big = *W.LastCluster;
9813 
9814     if (Small.Low == Small.High && Big.Low == Big.High &&
9815         Small.MBB == Big.MBB) {
9816       const APInt &SmallValue = Small.Low->getValue();
9817       const APInt &BigValue = Big.Low->getValue();
9818 
9819       // Check that there is only one bit different.
9820       APInt CommonBit = BigValue ^ SmallValue;
9821       if (CommonBit.isPowerOf2()) {
9822         SDValue CondLHS = getValue(Cond);
9823         EVT VT = CondLHS.getValueType();
9824         SDLoc DL = getCurSDLoc();
9825 
9826         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9827                                  DAG.getConstant(CommonBit, DL, VT));
9828         SDValue Cond = DAG.getSetCC(
9829             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9830             ISD::SETEQ);
9831 
9832         // Update successor info.
9833         // Both Small and Big will jump to Small.BB, so we sum up the
9834         // probabilities.
9835         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9836         if (BPI)
9837           addSuccessorWithProb(
9838               SwitchMBB, DefaultMBB,
9839               // The default destination is the first successor in IR.
9840               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9841         else
9842           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9843 
9844         // Insert the true branch.
9845         SDValue BrCond =
9846             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9847                         DAG.getBasicBlock(Small.MBB));
9848         // Insert the false branch.
9849         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9850                              DAG.getBasicBlock(DefaultMBB));
9851 
9852         DAG.setRoot(BrCond);
9853         return;
9854       }
9855     }
9856   }
9857 
9858   if (TM.getOptLevel() != CodeGenOpt::None) {
9859     // Here, we order cases by probability so the most likely case will be
9860     // checked first. However, two clusters can have the same probability in
9861     // which case their relative ordering is non-deterministic. So we use Low
9862     // as a tie-breaker as clusters are guaranteed to never overlap.
9863     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9864                [](const CaseCluster &a, const CaseCluster &b) {
9865       return a.Prob != b.Prob ?
9866              a.Prob > b.Prob :
9867              a.Low->getValue().slt(b.Low->getValue());
9868     });
9869 
9870     // Rearrange the case blocks so that the last one falls through if possible
9871     // without changing the order of probabilities.
9872     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9873       --I;
9874       if (I->Prob > W.LastCluster->Prob)
9875         break;
9876       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9877         std::swap(*I, *W.LastCluster);
9878         break;
9879       }
9880     }
9881   }
9882 
9883   // Compute total probability.
9884   BranchProbability DefaultProb = W.DefaultProb;
9885   BranchProbability UnhandledProbs = DefaultProb;
9886   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9887     UnhandledProbs += I->Prob;
9888 
9889   MachineBasicBlock *CurMBB = W.MBB;
9890   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9891     MachineBasicBlock *Fallthrough;
9892     if (I == W.LastCluster) {
9893       // For the last cluster, fall through to the default destination.
9894       Fallthrough = DefaultMBB;
9895     } else {
9896       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9897       CurMF->insert(BBI, Fallthrough);
9898       // Put Cond in a virtual register to make it available from the new blocks.
9899       ExportFromCurrentBlock(Cond);
9900     }
9901     UnhandledProbs -= I->Prob;
9902 
9903     switch (I->Kind) {
9904       case CC_JumpTable: {
9905         // FIXME: Optimize away range check based on pivot comparisons.
9906         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9907         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9908 
9909         // The jump block hasn't been inserted yet; insert it here.
9910         MachineBasicBlock *JumpMBB = JT->MBB;
9911         CurMF->insert(BBI, JumpMBB);
9912 
9913         auto JumpProb = I->Prob;
9914         auto FallthroughProb = UnhandledProbs;
9915 
9916         // If the default statement is a target of the jump table, we evenly
9917         // distribute the default probability to successors of CurMBB. Also
9918         // update the probability on the edge from JumpMBB to Fallthrough.
9919         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9920                                               SE = JumpMBB->succ_end();
9921              SI != SE; ++SI) {
9922           if (*SI == DefaultMBB) {
9923             JumpProb += DefaultProb / 2;
9924             FallthroughProb -= DefaultProb / 2;
9925             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9926             JumpMBB->normalizeSuccProbs();
9927             break;
9928           }
9929         }
9930 
9931         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9932         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9933         CurMBB->normalizeSuccProbs();
9934 
9935         // The jump table header will be inserted in our current block, do the
9936         // range check, and fall through to our fallthrough block.
9937         JTH->HeaderBB = CurMBB;
9938         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9939 
9940         // If we're in the right place, emit the jump table header right now.
9941         if (CurMBB == SwitchMBB) {
9942           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9943           JTH->Emitted = true;
9944         }
9945         break;
9946       }
9947       case CC_BitTests: {
9948         // FIXME: Optimize away range check based on pivot comparisons.
9949         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9950 
9951         // The bit test blocks haven't been inserted yet; insert them here.
9952         for (BitTestCase &BTC : BTB->Cases)
9953           CurMF->insert(BBI, BTC.ThisBB);
9954 
9955         // Fill in fields of the BitTestBlock.
9956         BTB->Parent = CurMBB;
9957         BTB->Default = Fallthrough;
9958 
9959         BTB->DefaultProb = UnhandledProbs;
9960         // If the cases in bit test don't form a contiguous range, we evenly
9961         // distribute the probability on the edge to Fallthrough to two
9962         // successors of CurMBB.
9963         if (!BTB->ContiguousRange) {
9964           BTB->Prob += DefaultProb / 2;
9965           BTB->DefaultProb -= DefaultProb / 2;
9966         }
9967 
9968         // If we're in the right place, emit the bit test header right now.
9969         if (CurMBB == SwitchMBB) {
9970           visitBitTestHeader(*BTB, SwitchMBB);
9971           BTB->Emitted = true;
9972         }
9973         break;
9974       }
9975       case CC_Range: {
9976         const Value *RHS, *LHS, *MHS;
9977         ISD::CondCode CC;
9978         if (I->Low == I->High) {
9979           // Check Cond == I->Low.
9980           CC = ISD::SETEQ;
9981           LHS = Cond;
9982           RHS=I->Low;
9983           MHS = nullptr;
9984         } else {
9985           // Check I->Low <= Cond <= I->High.
9986           CC = ISD::SETLE;
9987           LHS = I->Low;
9988           MHS = Cond;
9989           RHS = I->High;
9990         }
9991 
9992         // The false probability is the sum of all unhandled cases.
9993         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9994                      getCurSDLoc(), I->Prob, UnhandledProbs);
9995 
9996         if (CurMBB == SwitchMBB)
9997           visitSwitchCase(CB, SwitchMBB);
9998         else
9999           SwitchCases.push_back(CB);
10000 
10001         break;
10002       }
10003     }
10004     CurMBB = Fallthrough;
10005   }
10006 }
10007 
10008 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10009                                               CaseClusterIt First,
10010                                               CaseClusterIt Last) {
10011   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10012     if (X.Prob != CC.Prob)
10013       return X.Prob > CC.Prob;
10014 
10015     // Ties are broken by comparing the case value.
10016     return X.Low->getValue().slt(CC.Low->getValue());
10017   });
10018 }
10019 
10020 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10021                                         const SwitchWorkListItem &W,
10022                                         Value *Cond,
10023                                         MachineBasicBlock *SwitchMBB) {
10024   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10025          "Clusters not sorted?");
10026 
10027   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10028 
10029   // Balance the tree based on branch probabilities to create a near-optimal (in
10030   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10031   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10032   CaseClusterIt LastLeft = W.FirstCluster;
10033   CaseClusterIt FirstRight = W.LastCluster;
10034   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10035   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10036 
10037   // Move LastLeft and FirstRight towards each other from opposite directions to
10038   // find a partitioning of the clusters which balances the probability on both
10039   // sides. If LeftProb and RightProb are equal, alternate which side is
10040   // taken to ensure 0-probability nodes are distributed evenly.
10041   unsigned I = 0;
10042   while (LastLeft + 1 < FirstRight) {
10043     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10044       LeftProb += (++LastLeft)->Prob;
10045     else
10046       RightProb += (--FirstRight)->Prob;
10047     I++;
10048   }
10049 
10050   while (true) {
10051     // Our binary search tree differs from a typical BST in that ours can have up
10052     // to three values in each leaf. The pivot selection above doesn't take that
10053     // into account, which means the tree might require more nodes and be less
10054     // efficient. We compensate for this here.
10055 
10056     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10057     unsigned NumRight = W.LastCluster - FirstRight + 1;
10058 
10059     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10060       // If one side has less than 3 clusters, and the other has more than 3,
10061       // consider taking a cluster from the other side.
10062 
10063       if (NumLeft < NumRight) {
10064         // Consider moving the first cluster on the right to the left side.
10065         CaseCluster &CC = *FirstRight;
10066         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10067         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10068         if (LeftSideRank <= RightSideRank) {
10069           // Moving the cluster to the left does not demote it.
10070           ++LastLeft;
10071           ++FirstRight;
10072           continue;
10073         }
10074       } else {
10075         assert(NumRight < NumLeft);
10076         // Consider moving the last element on the left to the right side.
10077         CaseCluster &CC = *LastLeft;
10078         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10079         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10080         if (RightSideRank <= LeftSideRank) {
10081           // Moving the cluster to the right does not demot it.
10082           --LastLeft;
10083           --FirstRight;
10084           continue;
10085         }
10086       }
10087     }
10088     break;
10089   }
10090 
10091   assert(LastLeft + 1 == FirstRight);
10092   assert(LastLeft >= W.FirstCluster);
10093   assert(FirstRight <= W.LastCluster);
10094 
10095   // Use the first element on the right as pivot since we will make less-than
10096   // comparisons against it.
10097   CaseClusterIt PivotCluster = FirstRight;
10098   assert(PivotCluster > W.FirstCluster);
10099   assert(PivotCluster <= W.LastCluster);
10100 
10101   CaseClusterIt FirstLeft = W.FirstCluster;
10102   CaseClusterIt LastRight = W.LastCluster;
10103 
10104   const ConstantInt *Pivot = PivotCluster->Low;
10105 
10106   // New blocks will be inserted immediately after the current one.
10107   MachineFunction::iterator BBI(W.MBB);
10108   ++BBI;
10109 
10110   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10111   // we can branch to its destination directly if it's squeezed exactly in
10112   // between the known lower bound and Pivot - 1.
10113   MachineBasicBlock *LeftMBB;
10114   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10115       FirstLeft->Low == W.GE &&
10116       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10117     LeftMBB = FirstLeft->MBB;
10118   } else {
10119     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10120     FuncInfo.MF->insert(BBI, LeftMBB);
10121     WorkList.push_back(
10122         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10123     // Put Cond in a virtual register to make it available from the new blocks.
10124     ExportFromCurrentBlock(Cond);
10125   }
10126 
10127   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10128   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10129   // directly if RHS.High equals the current upper bound.
10130   MachineBasicBlock *RightMBB;
10131   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10132       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10133     RightMBB = FirstRight->MBB;
10134   } else {
10135     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10136     FuncInfo.MF->insert(BBI, RightMBB);
10137     WorkList.push_back(
10138         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10139     // Put Cond in a virtual register to make it available from the new blocks.
10140     ExportFromCurrentBlock(Cond);
10141   }
10142 
10143   // Create the CaseBlock record that will be used to lower the branch.
10144   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10145                getCurSDLoc(), LeftProb, RightProb);
10146 
10147   if (W.MBB == SwitchMBB)
10148     visitSwitchCase(CB, SwitchMBB);
10149   else
10150     SwitchCases.push_back(CB);
10151 }
10152 
10153 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10154 // from the swith statement.
10155 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10156                                             BranchProbability PeeledCaseProb) {
10157   if (PeeledCaseProb == BranchProbability::getOne())
10158     return BranchProbability::getZero();
10159   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10160 
10161   uint32_t Numerator = CaseProb.getNumerator();
10162   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10163   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10164 }
10165 
10166 // Try to peel the top probability case if it exceeds the threshold.
10167 // Return current MachineBasicBlock for the switch statement if the peeling
10168 // does not occur.
10169 // If the peeling is performed, return the newly created MachineBasicBlock
10170 // for the peeled switch statement. Also update Clusters to remove the peeled
10171 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10172 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10173     const SwitchInst &SI, CaseClusterVector &Clusters,
10174     BranchProbability &PeeledCaseProb) {
10175   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10176   // Don't perform if there is only one cluster or optimizing for size.
10177   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10178       TM.getOptLevel() == CodeGenOpt::None ||
10179       SwitchMBB->getParent()->getFunction().optForMinSize())
10180     return SwitchMBB;
10181 
10182   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10183   unsigned PeeledCaseIndex = 0;
10184   bool SwitchPeeled = false;
10185   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10186     CaseCluster &CC = Clusters[Index];
10187     if (CC.Prob < TopCaseProb)
10188       continue;
10189     TopCaseProb = CC.Prob;
10190     PeeledCaseIndex = Index;
10191     SwitchPeeled = true;
10192   }
10193   if (!SwitchPeeled)
10194     return SwitchMBB;
10195 
10196   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10197                     << TopCaseProb << "\n");
10198 
10199   // Record the MBB for the peeled switch statement.
10200   MachineFunction::iterator BBI(SwitchMBB);
10201   ++BBI;
10202   MachineBasicBlock *PeeledSwitchMBB =
10203       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10204   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10205 
10206   ExportFromCurrentBlock(SI.getCondition());
10207   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10208   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10209                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10210   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10211 
10212   Clusters.erase(PeeledCaseIt);
10213   for (CaseCluster &CC : Clusters) {
10214     LLVM_DEBUG(
10215         dbgs() << "Scale the probablity for one cluster, before scaling: "
10216                << CC.Prob << "\n");
10217     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10218     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10219   }
10220   PeeledCaseProb = TopCaseProb;
10221   return PeeledSwitchMBB;
10222 }
10223 
10224 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10225   // Extract cases from the switch.
10226   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10227   CaseClusterVector Clusters;
10228   Clusters.reserve(SI.getNumCases());
10229   for (auto I : SI.cases()) {
10230     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10231     const ConstantInt *CaseVal = I.getCaseValue();
10232     BranchProbability Prob =
10233         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10234             : BranchProbability(1, SI.getNumCases() + 1);
10235     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10236   }
10237 
10238   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10239 
10240   // Cluster adjacent cases with the same destination. We do this at all
10241   // optimization levels because it's cheap to do and will make codegen faster
10242   // if there are many clusters.
10243   sortAndRangeify(Clusters);
10244 
10245   if (TM.getOptLevel() != CodeGenOpt::None) {
10246     // Replace an unreachable default with the most popular destination.
10247     // FIXME: Exploit unreachable default more aggressively.
10248     bool UnreachableDefault =
10249         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10250     if (UnreachableDefault && !Clusters.empty()) {
10251       DenseMap<const BasicBlock *, unsigned> Popularity;
10252       unsigned MaxPop = 0;
10253       const BasicBlock *MaxBB = nullptr;
10254       for (auto I : SI.cases()) {
10255         const BasicBlock *BB = I.getCaseSuccessor();
10256         if (++Popularity[BB] > MaxPop) {
10257           MaxPop = Popularity[BB];
10258           MaxBB = BB;
10259         }
10260       }
10261       // Set new default.
10262       assert(MaxPop > 0 && MaxBB);
10263       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10264 
10265       // Remove cases that were pointing to the destination that is now the
10266       // default.
10267       CaseClusterVector New;
10268       New.reserve(Clusters.size());
10269       for (CaseCluster &CC : Clusters) {
10270         if (CC.MBB != DefaultMBB)
10271           New.push_back(CC);
10272       }
10273       Clusters = std::move(New);
10274     }
10275   }
10276 
10277   // The branch probablity of the peeled case.
10278   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10279   MachineBasicBlock *PeeledSwitchMBB =
10280       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10281 
10282   // If there is only the default destination, jump there directly.
10283   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10284   if (Clusters.empty()) {
10285     assert(PeeledSwitchMBB == SwitchMBB);
10286     SwitchMBB->addSuccessor(DefaultMBB);
10287     if (DefaultMBB != NextBlock(SwitchMBB)) {
10288       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10289                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10290     }
10291     return;
10292   }
10293 
10294   findJumpTables(Clusters, &SI, DefaultMBB);
10295   findBitTestClusters(Clusters, &SI);
10296 
10297   LLVM_DEBUG({
10298     dbgs() << "Case clusters: ";
10299     for (const CaseCluster &C : Clusters) {
10300       if (C.Kind == CC_JumpTable)
10301         dbgs() << "JT:";
10302       if (C.Kind == CC_BitTests)
10303         dbgs() << "BT:";
10304 
10305       C.Low->getValue().print(dbgs(), true);
10306       if (C.Low != C.High) {
10307         dbgs() << '-';
10308         C.High->getValue().print(dbgs(), true);
10309       }
10310       dbgs() << ' ';
10311     }
10312     dbgs() << '\n';
10313   });
10314 
10315   assert(!Clusters.empty());
10316   SwitchWorkList WorkList;
10317   CaseClusterIt First = Clusters.begin();
10318   CaseClusterIt Last = Clusters.end() - 1;
10319   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10320   // Scale the branchprobability for DefaultMBB if the peel occurs and
10321   // DefaultMBB is not replaced.
10322   if (PeeledCaseProb != BranchProbability::getZero() &&
10323       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10324     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10325   WorkList.push_back(
10326       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10327 
10328   while (!WorkList.empty()) {
10329     SwitchWorkListItem W = WorkList.back();
10330     WorkList.pop_back();
10331     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10332 
10333     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10334         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10335       // For optimized builds, lower large range as a balanced binary tree.
10336       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10337       continue;
10338     }
10339 
10340     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10341   }
10342 }
10343